gobinance

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

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

Go to latest
Published: Nov 10, 2020 License: MIT Imports: 15 Imported by: 0

README

GoBinance

PkgGoDev codecov Test

A Binance API client written in Go. The aim is to use idiomatic go, and to provide an idiomatic go interface without the builder patterns used in the official clients and forks thereof.

Documentation

Index

Constants

View Source
const (
	// QuantityAssetQuote indicates the quantity relates to the quote asset
	QuantityAssetQuote = "QUOTE"
	// QuantityAssetBase indicates the quantity relates to the base asset
	QuantityAssetBase = "BASE"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountInformation

type AccountInformation struct {
	MakerCommission  int64
	TakerCommission  int64
	BuyerCommission  int64
	SellerCommission int64
	CanTrade         bool
	CanWithdraw      bool
	CanDeposit       bool
	UpdateTime       time.Time
	AccountType      string
	Balances         map[string]Balance
	Permissions      []string
}

AccountInformation is the response of an AccountInformation request from binance

func (*AccountInformation) UnmarshalJSON

func (t *AccountInformation) UnmarshalJSON(bs []byte) error

type Balance

type Balance struct {
	// Asset is the symbol of the asset in question
	Asset string
	// Free is the amount of that asset that is currently available for trading
	Free *big.Float
	// Locked is the amount of that asset that is not available, due to being associated
	// with other open orders.
	Locked *big.Float
}

Balance represents the amount of funds associated with a particular asset in this binance account

type CancelSpotOrderOption

type CancelSpotOrderOption func(*cancelSpotOrderInput)

CancelSpotOrderOption is a function that applies optional parameters / overrides to a cancel order operation

func CancelSpotClientOrderID

func CancelSpotClientOrderID(id string) CancelSpotOrderOption

CancelSpotClientOrderID is a CancelSpotOrderOption which sets the NewClientOrderID value of a request to cancel a spot order to `id`.

*Note*: This does not cause an existing order of this ID to be cancelled. For that, use Client.CancelOrderByClientOrderID

func CancelSpotOrderRecvWindow

func CancelSpotOrderRecvWindow(d time.Duration) CancelSpotOrderOption

CancelSpotOrderRecvWindow overrides the recvWindow for a cancel spot order request

type CancelSpotOrderResult

type CancelSpotOrderResult struct {
	Symbol                string      `json:"symbol"`
	OriginalClientOrderID string      `json:"origClientOrderId"`
	OrderID               int64       `json:"orderId"`
	OrderListID           int64       `json:"orderListId"`
	ClientOrderID         string      `json:"clientOrderId"`
	Price                 *big.Float  `json:"price"`
	OriginalQty           *big.Float  `json:"origQty"`
	ExecutedQty           *big.Float  `json:"executedQty"`
	CumulativeQuoteQty    *big.Float  `json:"cummulativeQuoteQty"` // note misspelling is intentional
	Status                OrderStatus `json:"status"`
	TimeInForce           TimeInForce `json:"timeInForce"`
	Type                  OrderType   `json:"type"`
	Side                  OrderSide   `json:"side"`
}

CancelSpotOrderResult holds the data returned by binance in response to a request to cancel an order

type Client

type Client struct {
	// HTTPApiURL is the scheme and domain portion of the Binance HTTP API
	// this is usually `https://api.binance.com`
	HTTPApiURL *url.URL
	// WebsocketApiURL is the scheme and domain portion of the Binance Websockets API
	// this is usually `wss://stream.binance.com:9443`
	WebsocketApiURL *url.URL
	// UserAgent is passed in HTTP requests as the `User-Agent` header
	UserAgent string
	// APIKey is the API key to use in authenticated requests to the binance API
	APIKey string
	// RecvWindow is the maximum duration allowed between the client making a request
	// and binance receiving it.  Requests that take longer than this duration are rejected
	// by binance. When this value is 0, binance's default value is used (see their official
	// docs for information)
	RecvWindow time.Duration
	// Signer provides a method for signing requests before sending them to binance
	Signer Signer
	// Doer provides a method for performing HTTP requests
	Doer Doer
	// DialContexter provides a method for making websocket connections
	DialContexter DialContexter
	// Now returns the current time
	Now func() time.Time
}

Client provides methods for interacting with the binance API

func (*Client) AccountInformation

func (c *Client) AccountInformation(ctx context.Context) (AccountInformation, error)

AccountInformation fetches data about the account associated with the API Key provided to the client, or an error in the event of connection issues or a non-200 response from binance.

func (*Client) AllOpenSpotOrders

func (c *Client) AllOpenSpotOrders(ctx context.Context, opts ...OpenOrdersOptions) ([]SpotOrder, error)

AllOpenSpotOrders fetches all open spot orders on this account, regardless of symbol.

Note that this is an expensive operation, call it sparingly.

func (*Client) CancelOrderByClientOrderID

func (c *Client) CancelOrderByClientOrderID(ctx context.Context, symbol string, clientOrderID string, opts ...CancelSpotOrderOption) (CancelSpotOrderResult, error)

CancelOrderByClientOrderID cancels an order with the given client order ID, a client-generated ID optionally passed to the exchage when creating the order

func (*Client) CancelOrderByOrderID

func (c *Client) CancelOrderByOrderID(ctx context.Context, symbol string, orderID int64, opts ...CancelSpotOrderOption) (CancelSpotOrderResult, error)

CancelOrderByID cancels an order with the given orderID assigned by the exchange when originally placing the order.

func (*Client) OpenSpotOrdersForSymbol

func (c *Client) OpenSpotOrdersForSymbol(ctx context.Context, symbol string, opts ...OpenOrdersOptions) ([]SpotOrder, error)

OpenSpotOrdersForSymbol fetches the open orders on the specified symbol

func (*Client) PlaceLimitMakerOrder

func (c *Client) PlaceLimitMakerOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, price *big.Float, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceLimitMakerOrder places a limit order on the spot market which is immediately rejected if it would not be executed as a maker order.

AKA a post-only order.

func (*Client) PlaceLimitOrder

func (c *Client) PlaceLimitOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, price *big.Float, tif TimeInForce, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceLimitOrder places limit order on the spot market.

func (*Client) PlaceSpotMarketOrder

func (c *Client) PlaceSpotMarketOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, asset QuantityAsset, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceSpotMarketOrder places a market order on the spot market.

When asset is QuantityAssetBase, the qty parameter specifies the amount of the base asset to buy or sell at the market price. When asset is QuantityAssetQuote, the qty parameter specifies the amount you'd like to spend or earn, at the current market price. The quantity of the base asset is then calculated based on the current market price.

func (*Client) PlaceStopLossLimitOrder

func (c *Client) PlaceStopLossLimitOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, stopPrice *big.Float, limitPrice *big.Float, tif TimeInForce, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceStopLossLimitOrder places a stop-loss-limit order on the spot market.

A limit order will be placed once the stop price is reached.

func (*Client) PlaceStopLossOrder

func (c *Client) PlaceStopLossOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, stopPrice *big.Float, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceStopLossOrder places a stop-loss order on the spot market.

The order will execute once the `stopPrice` is reached.

func (*Client) PlaceTakeProfitLimitOrder

func (c *Client) PlaceTakeProfitLimitOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, stopPrice *big.Float, limitPrice *big.Float, tif TimeInForce, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceTakeProfitLimitOrder places a take-profit-limit order on the spot market.

A limit order will be placed once the stop price is reached.

func (*Client) PlaceTakeProfitOrder

func (c *Client) PlaceTakeProfitOrder(ctx context.Context, symbol string, side OrderSide, qty *big.Float, stopPrice *big.Float, opts ...SpotOrderOption) (SpotOrderResult, error)

PlaceTakeProfitOrder places a take-profit order on the spot market.

The order will execute once the stopPrice is reached.

func (*Client) QueryOrderByClientID

func (c *Client) QueryOrderByClientID(ctx context.Context, symbol string, clientOrderID string, opts ...QueryOrderOption) (SpotOrder, error)

QueryOrderByClientID fetches the order whose ID as assigned by the client is clientOrderID

func (*Client) QueryOrderByID

func (c *Client) QueryOrderByID(ctx context.Context, symbol string, orderID int64, opts ...QueryOrderOption) (SpotOrder, error)

QueryOrderByID fetches the order whose ID as assigned by the exchange is orderID

func (*Client) Trades

func (c *Client) Trades(ctx context.Context, symbol string) <-chan TradeEventOrError

Trades initiates a websocket connection to binance and returns a channel from which live trades can be streamed from binance. The channel is closed when the underlying context is cancelled, or upon a connection error or the server closing the connection.

type DialContexter

type DialContexter interface {
	DialContext(ctx context.Context, url string, hdr http.Header) (NextReaderCloser, *http.Response, error)
}

DialContexter provides methods for initiating a websocket stream

type Doer

type Doer interface {
	Do(r *http.Request) (*http.Response, error)
}

Doer provides a Do method to perform an HTTP request

type Fill

type Fill struct {
	Price           *big.Float
	Qty             *big.Float
	Commission      *big.Float
	CommissionAsset string
}

type HMACSigner

type HMACSigner struct {
	Secret string
}

HMACSigner provides a method for signing data using a secret key.

func (*HMACSigner) Sign

func (h *HMACSigner) Sign(input string) string

Sign generates an HMAC SHA256 signature of the `input` parameter given the `Secret` key in the HMACSigner

type HttpError

type HttpError struct {
	HttpStatus int
	// contains filtered or unexported fields
}

HttpError is an error type returned when a non-200 response is received from the binance API

func (*HttpError) Error

func (h *HttpError) Error() string

Error implements the error interface and returns a human-readable description of the error

func (*HttpError) ErrorCode

func (h *HttpError) ErrorCode() int

ErrorCode returns the value of the `code` field in binance's error response.

func (*HttpError) StatusCode

func (h *HttpError) StatusCode() int

StatusCode returns the HTTP status code received from binance that triggered the error

type NextReaderCloser

type NextReaderCloser interface {
	NextReader() (int, io.Reader, error)
	Close() error
}

NextReaderCloser provides a method for reading messages from a WebSocket connection and closing that connection when finished

type OpenOrdersOptions

type OpenOrdersOptions func(input *openOrderInput)

OpenOrdersOptions is a function that applies optional parameters or overrides to a function to query fetch orders

func OpenOrdersRecvWindow

func OpenOrdersRecvWindow(d time.Duration) OpenOrdersOptions

OpenOrdersRecvWindow overrides the receive window for an OpenOrder call. See Client.ReceiveWindow for more information

type OrderResponseType

type OrderResponseType string

OrderResponseType is an enumeration of possible responses that can be returned for new orders

const (
	OrderResponseTypeAck    OrderResponseType = "ACK"
	OrderResponseTypeResult OrderResponseType = "RESULT"
	OrderResponseTypeFull   OrderResponseType = "FULL"
)

func (OrderResponseType) Validate

func (t OrderResponseType) Validate() error

Validate returns nil if the value is a valid OrderResponseType, or an error if not.

type OrderSide

type OrderSide string

OrderSide indicates the direction of a trade

const (
	// OrderSideBuy indicates the order is a 'buy'
	OrderSideBuy OrderSide = "BUY"
	// OrderSideSell indicates the order is a 'sell'
	OrderSideSell OrderSide = "SELL"
)

func (OrderSide) Validate

func (e OrderSide) Validate() error

Validate returns nil if the value is a valid OrderSide, or an error if not.

type OrderStatus

type OrderStatus string

OrderStatus is an enumeration of possible order statuses

const (
	// OrderStatusNew indicates the order has been accepted by the engine
	OrderStatusNew OrderStatus = "NEW"
	// OrderStatusPartiallyFilled indicates a part of the order has been filled.
	OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED"
	// OrderStatusFilled indicates the order has been completed.
	OrderStatusFilled OrderStatus = "FILLED"
	// OrderStatusCanceled indicates the order has been canceled by the user.
	OrderStatusCanceled OrderStatus = "CANCELED"
	// OrderStatusRejected indicates the order was not accepted by the engine and not processed.
	OrderStatusRejected OrderStatus = "REJECTED"
	// OrderStatusExpired indicates the order was canceled according to the order type's rules (e.g. LIMIT FOK orders with no
	// fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during
	// liquidation, orders canceled during maintenance)
	OrderStatusExpired OrderStatus = "EXPIRED"
)

func (OrderStatus) Validate

func (s OrderStatus) Validate() error

Validate returns nil if the value is a valid OrderStatus, or an error if not.

type OrderType

type OrderType string

OrderType is an enumeration of the possible types of orders that can be placed

const (
	// OrderTypeLimit indicates a limit order
	OrderTypeLimit OrderType = "LIMIT"
	// OrderTypeMarket indicates a market order
	OrderTypeMarket OrderType = "MARKET"
	// OrderTypeStopLoss indicates a stop loss order
	OrderTypeStopLoss OrderType = "STOP_LOSS"
	// OrderTypeStopLossLimit indicates a stop loss limit order
	OrderTypeStopLossLimit OrderType = "STOP_LOSS_LIMIT"
	// OrderTypeTakeProfit indicates a take profit order
	OrderTypeTakeProfit OrderType = "TAKE_PROFIT"
	// OrderTypeTakeProfitLimit indicates a take profit limit order
	OrderTypeTakeProfitLimit OrderType = "TAKE_PROFIT_LIMIT"
	// OrderTypeLimitMaker indicates a limit maker order
	OrderTypeLimitMaker OrderType = "LIMIT_MAKER"
)

func (OrderType) Validate

func (t OrderType) Validate() error

Validate returns nil if the value is a valid OrderType, or an error if not.

type QuantityAsset

type QuantityAsset string

QuantityAsset is an enumeration of possible assets a quantity is related to in a trade

type QueryOrderOption

type QueryOrderOption func(input *queryOrderInput)

QueryOrderOption is a function that applies optional parameters / overrides to a query order operation

func QueryOrderRecvWindow

func QueryOrderRecvWindow(d time.Duration) QueryOrderOption

QueryOrderRecvWindow overrides the default receive window for a query order operation

type Signer

type Signer interface {
	Sign(input string) string
}

Signer provides a method to return an HMAC SHA256 hashed version of the input string encoded as a hexadecimal string

type SpotOrder

type SpotOrder struct {
	Symbol                string
	OrderID               int64
	OrderListID           int64
	ClientOrderID         string
	Price                 *big.Float
	OriginalQty           *big.Float
	ExecutedQty           *big.Float
	CumulativeQuoteQty    *big.Float
	Status                OrderStatus
	TimeInForce           TimeInForce
	Type                  OrderType
	Side                  OrderSide
	StopPrice             *big.Float
	IcebergQty            *big.Float
	Time                  time.Time
	UpdateTime            time.Time
	IsWorking             bool
	OriginalQuoteOrderQty *big.Float
}

SpotOrder holds the data returned by binance in response to a query order call

func (*SpotOrder) UnmarshalJSON

func (r *SpotOrder) UnmarshalJSON(bs []byte) error

type SpotOrderOption

type SpotOrderOption func(s *spotOrderInput)

SpotOrderOption is a function that applies optional values / overrides to a spot order

func SpotClientOrderID

func SpotClientOrderID(id string) SpotOrderOption

SpotClientOrderID is a SpotOrderOption which sets the NewClientOrderID value of a spot order to `id`.

func SpotOrderRecvWindow

func SpotOrderRecvWindow(d time.Duration) SpotOrderOption

SpotOrderRecvWindow overrides the default receive window for a request to place a spot order

type SpotOrderResult

type SpotOrderResult struct {
	Symbol             string
	OrderID            int
	OrderListID        int
	ClientOrderID      string
	TransactTime       time.Time
	Price              *big.Float
	OrigQty            *big.Float
	ExecutedQty        *big.Float
	CumulativeQuoteQty *big.Float
	Status             OrderStatus
	TimeInForce        TimeInForce
	Type               OrderType
	Side               OrderSide
	Fills              []Fill
}

func (*SpotOrderResult) UnmarshalJSON

func (s *SpotOrderResult) UnmarshalJSON(bs []byte) error

type TimeInForce

type TimeInForce string

TimeInForce is an enumeration of possible expiration behaviours of an order

const (
	// TimeInForceGoodTilCanceled indicates an order will be on the book unless the order is canceled
	TimeInForceGoodTilCanceled TimeInForce = "GTC"
	// TimeInForceImmediateOrCancel indicates an order will try to fill the order as much as it can before the order expires
	TimeInForceImmediateOrCancel TimeInForce = "IOC"
	// TimeInForceFillOrKill indicates an order will expire if the full order cannot be filled upon execution
	TimeInForceFillOrKill TimeInForce = "FOK"
)

func (TimeInForce) Validate

func (e TimeInForce) Validate() error

Validate returns nil if the value is a valid TimeInForce, or an error if not.

type TradeEvent

type TradeEvent struct {
	Event         string
	Time          time.Time
	Symbol        string
	TradeID       int64
	Price         *big.Float
	Quantity      *big.Float
	BuyerOrderID  int64
	SellerOrderID int64
	TradeTime     time.Time
	IsBuyerMaker  bool
}

TradeEvent define websocket trade event

func (*TradeEvent) UnmarshalJSON

func (t *TradeEvent) UnmarshalJSON(bs []byte) error

UnmarshalJSON provides custom unmarshalling for TradeEvents.

type TradeEventOrError

type TradeEventOrError struct {
	TradeEvent
	Err error
}

TradeEventOrError is a union of TradeEvent or error

Directories

Path Synopsis
Package mock_gobinance is a generated GoMock package.
Package mock_gobinance is a generated GoMock package.

Jump to

Keyboard shortcuts

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