binance

package module
v0.0.0-...-256cf57 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2020 License: MIT Imports: 14 Imported by: 0

README

Binance API

To read full documentation, specs and find out which request params are required/optional, please visit the official documentation page.

Supported API endpoints

https://github.com/filinvadim/go-binance/blob/master/service_def.go#L17-L76

Getting started

hmacSigner := &binance.HmacSigner{
    Key: []byte("API secret"),
}
ctx, _ := context.WithCancel(context.Background())
// use second return value for cancelling request when shutting down the app

binanceService := binance.NewAPIService(
    "https://api.binance.com/",
    "API key",
    hmacSigner,
    nil,
    nil,
)
b := binance.NewBinance(binanceService)

Examples

Following provides list of main usages of library. See example package for testing application with more examples.

Each call has its own Request structure with data that can be provided. The library is not responsible for validating the input and if non-zero value is used, the param is sent to the API server.

In case of an standard error, instance of binance.Error is returned with additional info.

NewOrder
newOrder, err := b.NewOrder(binance.NewOrderRequest{
    Symbol:      "BNBETH",
    Quantity:    1,
    Price:       999,
    Side:        binance.SideSell,
    TimeInForce: binance.GTC,
    Type:        binance.TypeLimit,
    Timestamp:   time.Now(),
})
if err != nil {
    panic(err)
}
fmt.Println(newOrder)
CancelOrder
canceledOrder, err := b.CancelOrder(binance.CancelOrderRequest{
    Symbol:    "BNBETH",
    OrderID:   newOrder.OrderID,
    Timestamp: time.Now(),
})
if err != nil {
    panic(err)
}
fmt.Printf("%#v\n", canceledOrder)
Klines
kl, err := b.Klines(binance.KlinesRequest{
    Symbol:   "BNBETH",
    Interval: binance.Hour,
})
if err != nil {
    panic(err)
}
fmt.Printf("%#v\n", kl)
Trade Websocket
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)

kech, done, err := b.TradeWebsocket(binance.TradeWebsocketRequest{
    Symbol: "ETHBTC",
})
if err != nil {
    panic(err)
}
go func() {
    for {
        select {
        case ke := <-kech:
            fmt.Printf("%#v\n", ke)
        case <-done:
            break
        }
    }
}()

fmt.Println("waiting for interrupt")
<-interrupt
fmt.Println("canceling context")
cancelCtx()
fmt.Println("waiting for signal")
<-done
fmt.Println("exit")
return

Known issues

  • Websocket error handling is not perfect and occasionally attempts to read from closed connection.

Documentation

Index

Constants

View Source
const (
	LimitCode = -1003
)
View Source
const OperateTimeFormat = "2006-01-02 15:04:05"
View Source
const SubscriptionSuccess = `"result":null`

Variables

View Source
var (
	RequestsWeight = RateLimitType("REQUESTS_WEIGHT")
	Orders         = RateLimitType("ORDERS")
	RawRequests    = RateLimitType("RAW_REQUESTS")
)
View Source
var (
	PreTrading   = PairStatus("PRE_TRADING")
	Trading      = PairStatus("TRADING")
	PostTrading  = PairStatus("POST_TRADING")
	EndOfDay     = PairStatus("END_OF_DAY")
	Halt         = PairStatus("HALT")
	AuctionMatch = PairStatus("AUCTION_MATCH")
	Break        = PairStatus("BREAK")
)
View Source
var (
	Minute         = Interval("1m")
	ThreeMinutes   = Interval("3m")
	FiveMinutes    = Interval("5m")
	FifteenMinutes = Interval("15m")
	ThirtyMinutes  = Interval("30m")
	Hour           = Interval("1h")
	TwoHours       = Interval("2h")
	FourHours      = Interval("4h")
	SixHours       = Interval("6h")
	EightHours     = Interval("8h")
	TwelveHours    = Interval("12h")
	Day            = Interval("1d")
	ThreeDays      = Interval("3d")
	Week           = Interval("1w")
	Month          = Interval("1M")
)
View Source
var (
	GTC = TimeInForce("GTC")
	IOC = TimeInForce("IOC")
)
View Source
var (
	StatusNew             = OrderStatus("NEW")
	StatusPartiallyFilled = OrderStatus("PARTIALLY_FILLED")
	StatusFilled          = OrderStatus("FILLED")
	StatusCancelled       = OrderStatus("CANCELED")
	StatusPendingCancel   = OrderStatus("PENDING_CANCEL")
	StatusRejected        = OrderStatus("REJECTED")
	StatusExpired         = OrderStatus("EXPIRED")

	TypeLimit  = OrderType("LIMIT")
	TypeMarket = OrderType("MARKET")

	SideBuy  = OrderSide("BUY")
	SideSell = OrderSide("SELL")
)
View Source
var DepositCodeStatus = map[int]string{
	0: "pending",
	1: "success",
	6: "success",
}
View Source
var WithdrawStatusCode = map[int]string{
	0: "pending",
	1: "fail",
	2: "pending",
	3: "fail",
	4: "pending",
	5: "fail",
	6: "success",
}

Functions

func IsCloseError

func IsCloseError(err error) bool

Types

type Account

type Account struct {
	MakerCommision  int64
	TakerCommision  int64
	BuyerCommision  int64
	SellerCommision int64
	CanTrade        bool
	CanWithdraw     bool
	CanDeposit      bool
	Balances        []*Balance
}

Account represents user's account information.

type AccountEvent

type AccountEvent struct {
	WSEvent
	Payload interface{}
}

type AccountMargin

type AccountMargin struct {
	BorrowEnabled       bool
	MarginLevel         float64
	TotalAssetOfBtc     float64
	TotalLiabilityOfBtc float64
	TotalNetAssetOfBtc  float64
	TradeEnabled        bool
	TransferEnabled     bool
	UserAssets          []UserAsset
}

type AccountRequest

type AccountRequest struct {
	RecvWindow time.Duration
	Timestamp  time.Time
}

AccountRequest represents Account request data.

type AggTrade

type AggTrade struct {
	ID             int
	Price          float64
	Quantity       float64
	FirstTradeID   int
	LastTradeID    int
	Timestamp      time.Time
	BuyerMaker     bool
	BestPriceMatch bool
}

AggTrade represents aggregated trade.

type AggTradeEvent

type AggTradeEvent struct {
	WSEvent
	AggTrade
}

type AggTradeEvents

type AggTradeEvents []AggTradeEvent

type AggTradesRequest

type AggTradesRequest struct {
	Symbol    string
	FromID    int64
	StartTime int64
	EndTime   int64
	Limit     int
}

AggTradesRequest represents AggTrades request data.

type AllOrdersRequest

type AllOrdersRequest struct {
	Symbol     string
	OrderID    int64
	Limit      int
	RecvWindow time.Duration
	Timestamp  time.Time
}

AllOrdersRequest represents AllOrders request data.

type Balance

type Balance struct {
	Asset  string
	Free   float64
	Locked float64
}

Balance groups balance-related information.

type Binance

type Binance interface {
	Service
}

Binance is wrapper for Binance API.

Read web documentation for more endpoints descriptions and list of mandatory and optional params. Wrapper is not responsible for client-side validation and only sends requests further.

For each API-defined enum there's a special type and list of defined enum values to be used.

func NewBinance

func NewBinance(service Service) Binance

NewBinance returns Binance instance.

type BookTicker

type BookTicker struct {
	Symbol   string
	BidPrice float64
	BidQty   float64
	AskPrice float64
	AskQty   float64
}

BookTicker represents book ticker data.

type CancelOrderRequest

type CancelOrderRequest struct {
	Symbol            string
	OrderID           int64
	OrigClientOrderID string
	NewClientOrderID  string
	RecvWindow        time.Duration
	Timestamp         time.Time
}

CancelOrderRequest represents CancelOrder request data.

type CanceledOrder

type CanceledOrder struct {
	Symbol            string
	OrigClientOrderID string
	OrderID           int64
	ClientOrderID     string
}

CanceledOrder represents data about canceled order.

type Deposit

type Deposit struct {
	InsertTime time.Time
	Amount     float64
	Asset      string
	Status     int
	TxID       string
	Address    string
}

Deposit represents Deposit data.

type DepthEvent

type DepthEvent struct {
	WSEvent
	UpdateID int
	OrderBook
}

type DepthWebsocketRequest

type DepthWebsocketRequest struct {
	Symbol string
}

type Dividend

type Dividend struct {
	Amount  float64
	DivTime time.Time
	EnInfo  string
	TranID  int64
	Asset   string
}

type Dividends

type Dividends []Dividend

type DustRow

type DustRow struct {
	TransferedTotal    float64
	ServiceChargeTotal float64
	TranId             int64
	Logs               []Log
	OperateTime        time.Time
}

type DustRows

type DustRows []DustRow

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"msg"`
}

Error represents Binance error structure with error code and message.

func (Error) Error

func (e Error) Error() string

Error returns formatted error message.

type ExchangeInfo

type ExchangeInfo struct {
	Timezone   string
	ServerTime time.Time
	RateLimits []*RateLimit
	Symbols    []*Pair
}

func (*ExchangeInfo) UnmarshalJSON

func (ex *ExchangeInfo) UnmarshalJSON(b []byte) error

type ExecutedOrder

type ExecutedOrder struct {
	Symbol        string
	OrderID       int
	ClientOrderID string
	Price         float64
	OrigQty       float64
	ExecutedQty   float64
	Status        OrderStatus
	TimeInForce   TimeInForce
	Type          OrderType
	Side          OrderSide
	StopPrice     float64
	IcebergQty    float64
	Time          time.Time
}

ExecutedOrder represents data about executed order.

type ExecutionReport

type ExecutionReport struct {
	ClientOrderID         string
	Side                  string
	OrderType             string
	TimeInForce           string
	OrderQuantity         float64
	OrderPrice            float64
	StopPrice             float64
	IcebergQuantity       float64
	OrderListID           int64
	OriginalClientOrderID *string
	ExecutionType         string
	OrderStatus           string
	OrderRejectReason     string
	OrderID               int64
	LastQuantity          float64
	CumQuality            float64
	LastPrice             float64
	CommisionAmount       float64
	CommisionAsset        *string
	TxTime                time.Time
	TradeID               int64
	IsOrderOnBook         bool
	IsMaker               bool
	OrderCreated          time.Time
	CumQuoteAsset         float64
	LastQuoteAsset        float64
	QuoteOrderQty         float64
}

type FutureAccount

type FutureAccount struct {
	TotalOpenOrderInitialMargin float64
	TotalMaintMargin            float64
	TotalPositionInitialMargin  float64
	FeeTier                     int
	TotalInitialMargin          float64
	CanWithdraw                 bool
	UpdateTime                  time.Time
	TotalCrossWalletBalance     float64
	TotalMarginBalance          float64
	TotalUnrealizedProfit       float64
	TotalCrossUnPNL             float64
	TotalWalletBalance          float64
	CanDeposit                  bool
	CanTrade                    bool
	AvailableBalance            float64
	MaxWithdrawAmount           float64
	Positions                   FuturePositions
	Assets                      FutureAssets
}

type FutureAsset

type FutureAsset struct {
	MaxWithdrawAmount      float64
	MaintMargin            float64
	OpenOrderInitialMargin float64
	WalletBalance          float64
	CrossWalletBalance     float64
	PositionInitialMargin  float64
	CrossUnPNL             float64
	UnrealizedProfit       float64
	Asset                  string
	MarginBalance          float64
	InitialMargin          float64
	AvailableBalance       float64
}

type FutureAssets

type FutureAssets []FutureAsset

type FuturePosition

type FuturePosition struct {
	EntryPrice             float64
	Symbol                 string
	Leverage               float64
	MaxNotional            float64
	Maintmargin            float64
	OpenOrderInitialMargin float64
	PositionInitialMargin  float64
	PositionSide           string
	Isolated               bool
	UnrealizedProfit       float64
	InitialMargin          float64
}

type FuturePositions

type FuturePositions []FuturePosition

type FutureTrade

type FutureTrade struct {
	QuoteQty     float64
	Price        float64
	Qty          float64
	ID           int64
	Time         time.Time
	IsBuyerMaker bool
}

type FutureTrades

type FutureTrades []FutureTrade

type FuturesBalance

type FuturesBalance struct {
	AccountAlias       string
	MaxWithdrawAmount  float64
	Balance            float64
	CrossWalletBalance float64
	CrossUnPNL         float64
	Asset              string
	AvailableBalance   float64
}

type FuturesBalances

type FuturesBalances []FuturesBalance

type HistoryRequest

type HistoryRequest struct {
	Asset      string
	Status     *int
	StartTime  time.Time
	EndTime    time.Time
	Limit      int64
	RecvWindow time.Duration
	Timestamp  time.Time
}

HistoryRequest represents history-related calls request data.

type HmacSigner

type HmacSigner struct {
	Key []byte
}

HmacSigner uses HMAC SHA256 for signing payloads.

func (*HmacSigner) Sign

func (hs *HmacSigner) Sign(payload []byte) string

Sign signs provided payload and returns encoded string sum.

type Interval

type Interval string

Interval represents interval enum.

type Kline

type Kline struct {
	OpenTime                 time.Time
	Open                     float64
	High                     float64
	Low                      float64
	Close                    float64
	Volume                   float64
	CloseTime                time.Time
	QuoteAssetVolume         float64
	NumberOfTrades           int
	TakerBuyBaseAssetVolume  float64
	TakerBuyQuoteAssetVolume float64
}

Kline represents single Kline information.

type KlineEvent

type KlineEvent struct {
	WSEvent
	Interval     Interval
	FirstTradeID int64
	LastTradeID  int64
	Final        bool
	Kline
}

type KlineWebsocketRequest

type KlineWebsocketRequest struct {
	Symbol   string
	Interval Interval
}

type KlinesRequest

type KlinesRequest struct {
	Symbol    string
	Interval  Interval
	Limit     int
	StartTime int64
	EndTime   int64
}

KlinesRequest represents Klines request data.

type Log

type Log struct {
	TranId              int64
	ServiceChargeAmount float64
	Uid                 int64
	Amount              float64
	OperateTime         time.Time
	TransferedAmount    float64
	FromAsset           string
}

type MyTradesRequest

type MyTradesRequest struct {
	Symbol     string
	Limit      int
	FromID     int64
	RecvWindow time.Duration
	Timestamp  time.Time
}

MyTradesRequest represents MyTrades request data.

type NewOrderRequest

type NewOrderRequest struct {
	Symbol           string
	Side             OrderSide
	Type             OrderType
	TimeInForce      TimeInForce
	Quantity         float64
	Price            float64
	NewClientOrderID string
	StopPrice        float64
	IcebergQty       float64
	Timestamp        time.Time
}

NewOrderRequest represents NewOrder request data.

type OpenOrdersRequest

type OpenOrdersRequest struct {
	Symbol     string
	RecvWindow time.Duration
	Timestamp  time.Time
}

OpenOrdersRequest represents OpenOrders request data.

type Order

type Order struct {
	Price    float64
	Quantity float64
}

Order represents single order information.

type OrderBook

type OrderBook struct {
	LastUpdateID int `json:"lastUpdateId"`
	Bids         []*Order
	Asks         []*Order
}

OrderBook represents Bids and Asks.

type OrderBookRequest

type OrderBookRequest struct {
	Symbol string
	Limit  int
}

OrderBookRequest represents OrderBook request data.

type OrderSide

type OrderSide string

OrderSide represents order side enum.

type OrderStatus

type OrderStatus string

OrderStatus represents order status enum.

type OrderType

type OrderType string

OrderType represents order type enum.

type Pair

type Pair struct {
	Symbol             string
	Status             PairStatus
	BaseAsset          string
	BaseAssetPrecision int
	QuoteAsset         string
	QuotePrecision     int
	OrderTypes         []OrderType
	IcebergAllowed     bool
}

type PairStatus

type PairStatus string

type PriceTicker

type PriceTicker struct {
	Symbol string
	Price  float64
}

PriceTicker represents ticker data for price.

type ProcessedOrder

type ProcessedOrder struct {
	Symbol        string
	OrderID       int64
	ClientOrderID string
	TransactTime  time.Time
}

ProcessedOrder represents data from processed order.

type QueryOrderRequest

type QueryOrderRequest struct {
	Symbol            string
	OrderID           int64
	OrigClientOrderID string
	RecvWindow        time.Duration
	Timestamp         time.Time
}

QueryOrderRequest represents QueryOrder request data.

type RateLimit

type RateLimit struct {
	RateLimitType RateLimitType
	Interval      Interval
	IntervalNum   int
	Limit         int
}

type RateLimitType

type RateLimitType string

type RiskFuture

type RiskFuture struct {
	EntryPrice       float64
	Leverage         float64
	PositionAmt      float64
	Symbol           string
	IsAutoAddMargin  bool
	MarkPrice        float64
	UnrealizedProfit float64
	IsolatedMargin   float64
	MarginType       string
	PositionSide     string
	LiquidationPrice float64
	MaxNotionalValue float64
}

type RiskFutures

type RiskFutures []RiskFuture

type RiskFuturesRequest

type RiskFuturesRequest struct {
	Symbol     string
	RecvWindow time.Duration
	Timestamp  time.Time
}

type Service

type Service interface {
	// Ping tests connectivity.
	Ping() error
	// Time returns server time.
	Time() (time.Time, error)
	// OrderBook returns list of orders.
	OrderBook(obr OrderBookRequest) (*OrderBook, error)
	// AggTrades returns compressed/aggregate list of trades.
	AggTrades(atr AggTradesRequest) ([]*AggTrade, error)
	// Klines returns klines/candlestick data.
	Klines(kr KlinesRequest) ([]*Kline, error)
	Tickers() ([]Ticker24, error)
	// Ticker24 returns 24hr price change statistics.
	Ticker24(tr TickerRequest) (*Ticker24, error)
	// TickerAllPrices returns ticker data for symbols.
	TickerAllPrices() ([]*PriceTicker, error)
	// TickerAllBooks returns tickers for all books.
	TickerAllBooks() ([]*BookTicker, error)

	// NewOrder places new order and returns ProcessedOrder.
	NewOrder(nor NewOrderRequest) (*ProcessedOrder, error)
	// NewOrder places testing order.
	NewOrderTest(nor NewOrderRequest) error
	// QueryOrder returns data about existing order.
	QueryOrder(qor QueryOrderRequest) (*ExecutedOrder, error)
	// CancelOrder cancels order.
	CancelOrder(cor CancelOrderRequest) (*CanceledOrder, error)
	// OpenOrders returns list of open orders.
	OpenOrders(oor OpenOrdersRequest) ([]*ExecutedOrder, error)
	// AllOrders returns list of all previous orders.
	AllOrders(aor AllOrdersRequest) ([]*ExecutedOrder, error)

	// Account returns account data.
	Account(ar AccountRequest) (*Account, error)
	// MyTrades list user's trades.
	MyTrades(mtr MyTradesRequest) ([]*Trade, error)
	// Withdraw executes withdrawal.
	Withdraw(wr WithdrawRequest) (*WithdrawResult, error)
	// DepositHistory lists deposit data.
	DepositHistory(hr HistoryRequest) ([]*Deposit, error)
	// WithdrawHistory lists withdraw data.
	WithdrawHistory(hr HistoryRequest) ([]*Withdrawal, error)
	// ExchangeInfo displays exchange metadata
	ExchangeInfo() (*ExchangeInfo, error)
	SubAccountList(sar SubAccountRequest) (SubAccounts, error)
	SubAccountTransferHistory(sar SubAccountRequest) (Transfers, error)
	AssetDividend(hr HistoryRequest) (Dividends, error)
	DustLogs(ar AccountRequest) (DustRows, error)
	MarginAccount(ar AccountRequest) (*AccountMargin, error)
	PositionRiskFutures(r RiskFuturesRequest) (RiskFutures, error)
	FuturesAccountBalance(ar AccountRequest) (FuturesBalances, error)
	FutureAccount(ar AccountRequest) (*FutureAccount, error)
	FutureTrades(tr TradesRequest) (FutureTrades, error)
	// StartUserDataStream starts stream and returns Stream with ListenKey.
	StartUserDataStream() (*Stream, error)
	// KeepAliveUserDataStream prolongs stream livespan.
	KeepAliveUserDataStream(s *Stream) error
	// CloseUserDataStream closes opened stream.
	CloseUserDataStream(s *Stream) error

	DepthWebsocket(dwr DepthWebsocketRequest) (chan *DepthEvent, chan struct{}, error)
	KlineWebsocket(kwr KlineWebsocketRequest) (chan *KlineEvent, chan struct{}, error)
	TradeWebsocket(twr TradeWebsocketRequest) (chan *AggTradeEvent, chan struct{}, error)
	TradeWebsocketBatch(twr TradesRequest) (chan AggTradeEvents, chan error, error)
	UserDataWebsocket(urwr UserDataWebsocketRequest) (chan *AccountEvent, chan error, error)
}

Service represents service layer for Binance API.

The main purpose for this layer is to be replaced with dummy implementation if necessary without need to replace Binance instance.

func NewAPIService

func NewAPIService(url, apiKey string, signer Signer, logger logln, ctx context.Context) Service

NewAPIService creates instance of Service.

If logger or ctx are not provided, NopLogger and Background context are used as default. You can use context for one-time request cancel (e.g. when shutting down the app).

type Signer

type Signer interface {
	// Sign signs provided payload and returns encoded string sum.
	Sign(payload []byte) string
}

Signer signs provided payloads.

type Stream

type Stream struct {
	ListenKey string
}

Stream represents stream information.

Read web docs to get more information about using streams.

type SubAccount

type SubAccount struct {
	Email      string
	Status     string
	Activated  bool
	Mobile     string
	GAuth      bool
	CreateTime time.Time
}

type SubAccountRequest

type SubAccountRequest struct {
	Email      string
	Status     string
	Page       int64
	Limit      int64
	StartTime  time.Time
	EndTime    time.Time
	RecvWindow time.Duration
	Timestamp  time.Time
}

type SubAccounts

type SubAccounts []SubAccount

type Ticker24

type Ticker24 struct {
	Symbol             string
	VolumeQuote        string
	PriceChange        float64
	PriceChangePercent float64
	WeightedAvgPrice   float64
	PrevClosePrice     float64
	LastPrice          float64
	BidPrice           float64
	AskPrice           float64
	OpenPrice          float64
	HighPrice          float64
	LowPrice           float64
	Volume             float64
	OpenTime           time.Time
	CloseTime          time.Time
	FirstID            int
	LastID             int
	Count              int
}

Ticker24 represents data for 24hr ticker.

type TickerRequest

type TickerRequest struct {
	Symbol string
}

TickerRequest represents Ticker request data.

type TimeInForce

type TimeInForce string

TimeInForce represents timeInForce enum.

type Trade

type Trade struct {
	ID              int64
	OrderID         int64
	Price           float64
	Qty             float64
	Commission      float64
	CommissionAsset string
	Time            time.Time
	IsBuyer         bool
	IsMaker         bool
	IsBestMatch     bool
}

Trade represents data about trade.

type TradeWebsocketRequest

type TradeWebsocketRequest struct {
	Symbol string
}

type TradesRequest

type TradesRequest struct {
	Symbol string
	Limit  int
}

type Transfer

type Transfer struct {
	From  string
	To    string
	Asset string
	Qty   float64
	Time  time.Time
}

type Transfers

type Transfers []Transfer

type UserAsset

type UserAsset struct {
	Asset    string
	Borrowed float64
	Interest float64
	Locked   float64
	NetAsset float64
	Free     float64
}

type UserDataWebsocketRequest

type UserDataWebsocketRequest struct {
	ListenKey string
}

type WSEvent

type WSEvent struct {
	Type   string
	Time   time.Time
	Symbol string
}

type WithdrawRequest

type WithdrawRequest struct {
	Asset      string
	Address    string
	Amount     float64
	Name       string
	RecvWindow time.Duration
	Timestamp  time.Time
}

WithdrawRequest represents Withdraw request data.

type WithdrawResult

type WithdrawResult struct {
	Success bool
	Msg     string
}

WithdrawResult represents Withdraw result.

type Withdrawal

type Withdrawal struct {
	Amount         float64
	Address        string
	TxID           string
	ID             string
	Asset          string
	ApplyTime      time.Time
	Status         int
	TransactionFee float64
}

Withdrawal represents withdrawal data.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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