binance

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

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

Go to latest
Published: May 8, 2020 License: MIT Imports: 16 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.

Getting started

var logger log.Logger
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
logger = log.With(logger, "time", log.DefaultTimestampUTC, "caller", log.DefaultCaller)

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://www.binance.com",
    "API key",
    hmacSigner,
    logger,
    ctx,
)
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

This section is empty.

Variables

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")
	FOK = TimeInForce("FOK")
)
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")
)

Functions

This section is empty.

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
	Account
}

type AccountRequest

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

AccountRequest represents Account request data.

type Address

type Address struct {
	Address    string  `json:"address"`
	Amount     float64 `json:"amount"`
	AddressTag string  `json:"addressTag"`
	Success    bool    `json:"success"`
	Msg        string  `json:"msg,omitempty"`
}

Address represents deposit address data.

type AddressRequest

type AddressRequest struct {
	Asset      string
	Status     *int
	RecvWindow time.Duration
	Timestamp  time.Time
}

AddressRequest ...

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 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 {
	// 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)
	// 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)
	// DepositAddress get deposit address data.
	DepositAddress(ar AddressRequest) (*Address, error)
	// WithdrawHistory lists withdraw data.
	WithdrawHistory(hr HistoryRequest) ([]*Withdrawal, error)
	// TradeFee lists of fees.
	TradeFee(tfr TradeFeeRequest) (*TradeFee, 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)
	UserDataWebsocket(udwr UserDataWebsocketRequest) (chan *AccountEvent, chan struct{}, error)
}

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
	Address    *string
	TxID       *string
}

Deposit represents Deposit data.

type DepthEvent

type DepthEvent struct {
	WSEvent
	UpdateID int
	OrderBook
}

type DepthWebsocketRequest

type DepthWebsocketRequest struct {
	Symbol string
}

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 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 Fees

type Fees struct {
	Symbol string  `json:"symbol"`
	Taker  float64 `json:"taker"`
	Maker  float64 `json:"maker"`
}

Fees represents trades fees.

type HistoryRequest

type HistoryRequest struct {
	Asset      string
	Status     *int
	StartTime  time.Time
	EndTime    time.Time
	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 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 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
	Price               float64
	OrigQty             float64
	ExecutedQty         float64
	CummulativeQuoteQty float64
	Status              OrderStatus
	TimeInForce         TimeInForce
	Type                OrderType
	Side                OrderSide
	Fills               []ProcessedOrderFill
}

ProcessedOrder represents data from processed order.

type ProcessedOrderFill

type ProcessedOrderFill struct {
	Price           float64
	Qty             float64
	Commission      float64
	CommissionAsset string
}

ProcessedOrderFill represents order trade item.

type QueryOrderRequest

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

QueryOrderRequest represents QueryOrder request data.

type Service

type Service interface {
	Ping() error
	Time() (time.Time, error)
	OrderBook(obr OrderBookRequest) (*OrderBook, error)
	AggTrades(atr AggTradesRequest) ([]*AggTrade, error)
	Klines(kr KlinesRequest) ([]*Kline, error)
	Ticker24(tr TickerRequest) (*Ticker24, error)
	TickerAllPrices() ([]*PriceTicker, error)
	TickerAllBooks() ([]*BookTicker, error)

	NewOrder(or NewOrderRequest) (*ProcessedOrder, error)
	NewOrderTest(or NewOrderRequest) error
	QueryOrder(qor QueryOrderRequest) (*ExecutedOrder, error)
	CancelOrder(cor CancelOrderRequest) (*CanceledOrder, error)
	OpenOrders(oor OpenOrdersRequest) ([]*ExecutedOrder, error)
	AllOrders(aor AllOrdersRequest) ([]*ExecutedOrder, error)

	Account(ar AccountRequest) (*Account, error)
	MyTrades(mtr MyTradesRequest) ([]*Trade, error)
	Withdraw(wr WithdrawRequest) (*WithdrawResult, error)
	DepositHistory(hr HistoryRequest) ([]*Deposit, error)
	DepositAddress(ar AddressRequest) (*Address, error)
	WithdrawHistory(hr HistoryRequest) ([]*Withdrawal, error)
	TradeFee(tfr TradeFeeRequest) (*TradeFee, error)

	StartUserDataStream() (*Stream, error)
	KeepAliveUserDataStream(s *Stream) error
	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)
	UserDataWebsocket(udwr UserDataWebsocketRequest) (chan *AccountEvent, chan struct{}, 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 log.Logger, 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 Ticker24

type Ticker24 struct {
	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
	QuoteQty        float64
	Commission      float64
	CommissionAsset string
	Time            time.Time
	IsBuyer         bool
	IsMaker         bool
	IsBestMatch     bool
}

Trade represents data about trade.

type TradeFee

type TradeFee struct {
	Fees    []Fees `json:"tradeFee"`
	Success bool   `json:"success"`
	Msg     string `json:"msg,omitempty"`
}

TradeFee represents trades fees response.

type TradeFeeRequest

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

TradeFeeRequest represents history-related calls request data.

type TradeWebsocketRequest

type TradeWebsocketRequest struct {
	Symbol string
}

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
	ID      string
}

WithdrawResult represents Withdraw result.

type Withdrawal

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

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