binance

package module
v0.0.0-...-551d485 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2018 License: MIT Imports: 13 Imported by: 0

README

Binance-Go

Build Status codecov

An open source sdk for Binance exchange written in Golang. There are endpoints/streams that are not implemented yet. Feel free to collaborate with me if you need them now :)

THIS LIBRARY IS NOT READY FOR PRODUCTION YET

Installation

After you've configured your local Go package:

go get github.com/opencrypter/binance-go

Usage

This SDK is based on the official binance api docs

You only have to call the constructor function in order to use it:

import "github.com/opencrypter/binance-go"

sdk := binance.New("Your-api-key", "Your secret api-key")

exchangeInfo, err := sdk.ExchangeInfo()

Available api endpoints

ExchangeInfo

Current exchange trading rules and symbol information

Official doc: exchange-information

Example
exchangeInfo, err := sdk.ExchangeInfo()
Order book

Order depth for a specific symbol

Official doc: Order book

Example
// Example with limit by default
query := binance.NewDepthQuery("ETHBTC")
depth, err := sdk.Depth(query)

// Example with limit parameter
query := binance.NewDepthQuery("ETHBTC").Limit(5)
depth, err := sdk.Depth(query)
Historical trades list

Get historical trades for a specific symbol

Official doc: Recent trades list

Example
// Example to retrieve last trades with the limit by default
query := binance.NewTradesQuery("ETHBTC")
response, err := sdk.Trades(query)

// Example to retrieve historical trades from the given id and a result limit
query := binance.NewTradesQuery("ETHBTC").Limit(350).FromId(3500)
trades, err := sdk.Trades(query)
Compressed/Aggregate trades list

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

Official doc: Compressed/Aggregate trades list

Example
// Example with parameters by default
query := binance.NewCompressedTradesQuery("ETHBTC")
response, err := sdk.CompressedTrades(query)

// Example with all parameters. Keep in mind that you cannot use all parameters at the same time (read the official doc)
query := binance.NewCompressedTradesQuery("ETHBTC").Limit(10).FromId(1).StartTime(1498793709153).EndTime(1498793709163)
trades, err := sdk.CompressedTrades(query)
Kline/Candlestick data

Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.

Official doc: Kline/Candlestick data

Example
// Example with parameters by default
query := binance.NewKLinesQuery("ETHBTC", binance.Interval12h)
response, err := sdk.KLines(query)

// Example with all parameters.
query := NewKLinesQuery("ETHBTC", Interval1m).Limit(10).StartTime(1498793709153).EndTime(1498793709163)
trades, err := sdk.KLines(query)
Symbol price ticker

Latest price for a symbol.

Official doc: Symbol price ticker

Example
query := binance.NewSymbolPriceTickerQuery("ETHBTC")
response, err := sdk.SymbolPriceTicker(query)
All symbol price tickers

Latest price for all symbols.

Official doc: Symbol price ticker

Example
response, err := sdk.AllSymbolPriceTickers()
Symbol order book ticker

Best price/qty on the order book for a symbol.

Official doc: Symbol order book ticker

Example
query := binance.NewSymbolOrderBookTickerQuery("ETHBTC")
response, err := sdk.SymbolOrderBookTicker(query)
All symbol order book tickers

Best price/qty on the order book for all symbols.

Official doc: Symbol order book ticker

Example
response, err := sdk.AllSymbolOrderBookTickers()
New order (TRADE)

Send a new order.

Official doc: New order (TRADE)

Example
request := binance.NewOrderRequest("BTCUSDT", "SELL", "MARKET", 10)
response, err := sdk.NewOrder(request)

// With all optional parameters (See official doc)
request := NewOrderRequest("BTCUSDT", "SELL", "MARKET", 10).
	TimeInForce("GTC").
	Price(0.1).
	NewClientOrderId("6gCrw2kRUAF9CvJDGP16IP").
	StopPrice(0.1).
	IcebergQuantity(0.1).
	NewOrderResponseType("ACK").
	RecvWindow(2)
response, err := sdk.NewOrder(request)
Query order (USER_DATA)

Get order detail.

Official doc: Query order (USER_DATA)

Example
query := binance.NewGetOrderQuery("LTCBTC")
response, err := sdk.GetOrder(query)

// With all optional parameters (See official doc)
query := binance.NewGetOrderQuery("LTCBTC").
	OrderId(1).
	OrigClientOrderId("myOrder1").
	RecvWindow(2)
response, err := sdk.GetOrder(query)
Cancel order (TRADE)

Cancel an active order.

Official doc: Cancel order (TRADE)

Example
request := binance.NewCancelOrderRequest("LTCBTC")
response, err := sdk.CancelOrder(request)

// With all optional parameters (See official doc)
request := binance.NewCancelOrderRequest("LTCBTC").
    OrderId(1).
    OrigClientOrderId("myOrder1").
    RecvWindow(2000)
response, err := sdk.CancelOrder(request)
Current open orders (USER_DATA)

Get all open orders on a symbol.

Official doc: Current open orders (USER_DATA)

Example
query := binance.NewGetOpenOrdersQuery("LTCBTC")
response, err := sdk.GetOpenOrders(query)

// With all optional parameters (See official doc)
query := binance.NewGetOpenOrdersQuery("LTCBTC").RecvWindow(2)
response, err := sdk.GetOpenOrders(query)
All orders (USER_DATA)

Get all account orders; active, canceled, or filled.

Official doc: All orders (USER_DATA)

Example
query := binance.NewGetAllOrdersQuery("LTCBTC")
response, _ := sdk.GetAllOrders(query)

// With all optional parameters (See official doc)
query := binance.NewGetAllOrdersQuery("LTCBTC").
    OrderId(1).
    Limit(200).
    RecvWindow(2000)
response, _ := sdk.GetAllOrders(query)
Account information (USER_DATA)

Get current account information.

Official doc: Account information (USER_DATA)

Example
query := binance.NewAccountQuery()
response, _ := sdk.Account(query)

// With all optional parameters (See official doc)
query := binance.NewAccountQuery().RecvWindow(2000)
response, _ := sdk.Account(query)
Account trade list (USER_DATA)

Get trades for a specific account and symbol.

Official doc: Account trade list (USER_DATA)

Example
query := binance.NewMyTradesQuery("ETHBTC")
response, _ := sdk.MyTrades(query)

// With all optional parameters (See official doc)
query := binance.NewMyTradesQuery("ETHBTC").Limit(10).RecvWindow(2).FromId(200)
response, _ := sdk.MyTrades(query)

Available web socket streams:

Not available yet.

Tests

All is covered 100%. You can run all tests as normally you do it:

go test -test.v

License

MIT licensed. See the LICENSE file for details.

Documentation

Overview

Package binance is a generated GoMock package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewAccountQuery

func NewAccountQuery() *accountQuery

func NewCancelOrderRequest

func NewCancelOrderRequest(symbol string) *cancelOrderRequest

func NewCompressedTradesQuery

func NewCompressedTradesQuery(symbol string) *compressedTradesQuery

Returns the required query for the Trades endpoint.

func NewDepthQuery

func NewDepthQuery(symbol string) *depthQuery

Returns the required query for the Depth endpoint.

func NewGetAllOrdersQuery

func NewGetAllOrdersQuery(symbol string) *getAllOrdersQuery

func NewGetOpenOrdersQuery

func NewGetOpenOrdersQuery(symbol string) *getOpenOrdersQuery

func NewGetOrderQuery

func NewGetOrderQuery(symbol string) *getOrderQuery

func NewKLinesQuery

func NewKLinesQuery(symbol string, interval Interval) *kLinesQuery

func NewMyTradesQuery

func NewMyTradesQuery(symbol string) *myTradesQuery

func NewOrderRequest

func NewOrderRequest(symbol string, side string, orderType string, quantity float64) *newOrderRequest

func NewSymbolOrderBookTickerQuery

func NewSymbolOrderBookTickerQuery(symbol string) *symbolOrderBookTickerQuery

func NewSymbolPriceTickerQuery

func NewSymbolPriceTickerQuery(symbol string) *symbolPriceTickerQuery

Required query for SymbolPriceTicker.

func NewTradesQuery

func NewTradesQuery(symbol string) *tradesQuery

Returns the required query for the Trades endpoint.

Types

type Account

type Account struct {
	MakerCommission  int64
	TakerCommission  int64
	BuyerCommission  int64
	SellerCommission int64
	CanTrade         bool
	CanWithdraw      bool
	CanDeposit       bool
	UpdateTime       int64
	Balances         []Balance
}

type AccountTrade

type AccountTrade struct {
	Id              int64   `json:"id"`
	OrderId         int64   `json:"orderId"`
	Price           float64 `json:"price,string"`
	Quantity        float64 `json:"qty,string"`
	Commission      float64 `json:"commission,string"`
	CommissionAsset string  `json:"commissionAsset"`
	Time            int64   `json:"time"`
	IsBuyer         bool    `json:"isBuyer"`
	IsMaker         bool    `json:"isMaker"`
	IsBestMatch     bool    `json:"isBestMatch"`
}

type Balance

type Balance struct {
	Asset  string
	Free   float64 `json:"free,string"`
	Locked float64 `json:"locked,string"`
}

type CancelledOrder

type CancelledOrder struct {
	Symbol            string `json:"symbol"`
	OrigClientOrderId string `json:"origClientOrderId"`
	OrderId           int64  `json:"orderId"`
	ClientOrderId     string `json:"clientOrderId"`
}

type Client

type Client interface {
	Do(request *request) ([]byte, error)
}

type Clock

type Clock interface {
	Now() *int64
}

type CompressedTrade

type CompressedTrade struct {
	Id           int     `json:"a"`
	Price        float64 `json:"p,string"`
	Quantity     float64 `json:"q,string"`
	FirstTradeId int     `json:"f"`
	LastTradeId  int     `json:"l"`
	Time         int     `json:"T"`
	IsBuyerMaker bool    `json:"m"`
	IsBestMatch  bool    `json:"M"`
}

type Depth

type Depth struct {
	LastUpdateId int
	Bids         []DepthOrder
	Asks         []DepthOrder
}

type DepthOrder

type DepthOrder struct {
	Price    float64
	Quantity float64
}

type ExchangeInfo

type ExchangeInfo struct {
	Timezone        string
	ServerTime      time.Duration
	RateLimits      []RateLimits
	ExchangeFilters []string
	Symbols         []Symbol
}

type Filter

type Filter struct {
	FilterType  string
	MinPrice    float64 `json:",omitempty,string"`
	MaxPrice    float64 `json:",omitempty,string"`
	TickSize    float64 `json:",omitempty,string"`
	MinQuantity float64 `json:"minQty,omitempty,string"`
	MaxQuantity float64 `json:"maxQty,omitempty,string"`
	StepSize    float64 `json:",omitempty,string"`
	MinNotional float64 `json:",omitempty,string"`
}

type FullOrder

type FullOrder struct {
	Symbol           string      `json:"symbol"`
	OrderId          int         `json:"orderId"`
	ClientOrderId    string      `json:"clientOrderId"`
	TransactionTime  int         `json:"transactTime"`
	Price            float64     `json:"price,string"`
	OriginalQuantity float64     `json:"origQty,string"`
	ExecutedQuantity float64     `json:"executedQty,string"`
	Status           string      `json:"status"`
	TimeInForce      string      `json:"timeInForce"`
	Type             string      `json:"type"`
	Side             string      `json:"side"`
	Fills            []OrderFill `json:"fills"`
}

type Interval

type Interval string
const (
	Interval1m  Interval = "1m"
	Interval3m  Interval = "3m"
	Interval5m  Interval = "5m"
	Interval15m Interval = "15m"
	Interval30m Interval = "30m"
	Interval1h  Interval = "1h"
	Interval2h  Interval = "2h"
	Interval4h  Interval = "4h"
	Interval8h  Interval = "8h"
	Interval12h Interval = "12h"
	Interval1d  Interval = "1d"
	Interval3d  Interval = "3d"
	Interval1w  Interval = "1w"
	Interval1M  Interval = "1M"
)

type KLine

type KLine struct {
	OpenTime            int
	Open                float64
	High                float64
	Low                 float64
	Close               float64
	Volume              float64
	CloseTime           int
	QuoteAssetVolume    float64
	TradesNumber        int
	TakerBuyBaseVolume  float64
	TakerBuyQuoteVolume float64
}

type MockClient

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

MockClient is a mock of Client interface

func NewMockClient

func NewMockClient(ctrl *gomock.Controller) *MockClient

NewMockClient creates a new mock instance

func (*MockClient) Do

func (m *MockClient) Do(request *request) ([]byte, error)

Do mocks base method

func (*MockClient) EXPECT

func (m *MockClient) EXPECT() *MockClientMockRecorder

EXPECT returns an object that allows the caller to indicate expected use

type MockClientMockRecorder

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

MockClientMockRecorder is the mock recorder for MockClient

func (*MockClientMockRecorder) Do

func (mr *MockClientMockRecorder) Do(request interface{}) *gomock.Call

Do indicates an expected call of Do

type MockClock

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

MockClock is a mock of Clock interface

func NewMockClock

func NewMockClock(ctrl *gomock.Controller) *MockClock

NewMockClock creates a new mock instance

func (*MockClock) EXPECT

func (m *MockClock) EXPECT() *MockClockMockRecorder

EXPECT returns an object that allows the caller to indicate expected use

func (*MockClock) Now

func (m *MockClock) Now() *int64

Now mocks base method

type MockClockMockRecorder

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

MockClockMockRecorder is the mock recorder for MockClock

func (*MockClockMockRecorder) Now

func (mr *MockClockMockRecorder) Now() *gomock.Call

Now indicates an expected call of Now

type Order

type Order struct {
	Symbol           string  `json:"symbol"`
	OrderId          int64   `json:"orderId"`
	ClientOrderId    string  `json:"clientOrderId"`
	Price            float64 `json:"price,string"`
	OriginalQuantity float64 `json:"origQty,string"`
	ExecutedQuantity float64 `json:"executedQty,string"`
	Status           string  `json:"status"`
	TimeInForce      string  `json:"timeInForce"`
	Type             string  `json:"type"`
	Side             string  `json:"side"`
	StopPrice        float64 `json:"stopPrice,string"`
	IcebergQuantity  float64 `json:"icebergQty,string"`
	Time             int64   `json:"time"`
	IsWorking        bool    `json:"isWorking"`
}

type OrderBookTicker

type OrderBookTicker struct {
	Symbol      string  `json:"symbol"`
	BidPrice    float64 `json:"bidPrice,string"`
	BidQuantity float64 `json:"bidQty,string"`
	AskPrice    float64 `json:"askPrice,string"`
	AskQuantity float64 `json:"askQty,string"`
}

type OrderFill

type OrderFill struct {
	Price           float64 `json:"price,string"`
	Quantity        float64 `json:"qty,string"`
	Commission      float64 `json:"commission,string"`
	CommissionAsset string  `json:"commissionAsset"`
}

type RateLimits

type RateLimits struct {
	RateLimitType string
	Interval      string
	Limit         int
}

type Sdk

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

func New

func New(apiKey string, apiSecret string) Sdk

func (Sdk) Account

func (sdk Sdk) Account(query *accountQuery) (*Account, error)

func (Sdk) AllSymbolOrderBookTickers

func (sdk Sdk) AllSymbolOrderBookTickers() ([]OrderBookTicker, error)

func (Sdk) AllSymbolPriceTickers

func (sdk Sdk) AllSymbolPriceTickers() ([]SymbolPrice, error)

Latest price for all symbols.

func (Sdk) CancelOrder

func (sdk Sdk) CancelOrder(request *cancelOrderRequest) (*CancelledOrder, error)

func (*Sdk) CompressedTrades

func (sdk *Sdk) CompressedTrades(query *compressedTradesQuery) ([]CompressedTrade, error)

func (Sdk) Depth

func (sdk Sdk) Depth(query *depthQuery) (*Depth, error)

Market depth for a specific symbol. An example of a symbol is "ETHBTC"

The query is optional and it specifies the depth limit. Accepted values for the limit: [5, 10, 20, 50, 100 (default), 500, 1000]

Caution: setting limit=0 can return a lot of data.

func (Sdk) ExchangeInfo

func (sdk Sdk) ExchangeInfo() (*ExchangeInfo, error)

func (Sdk) GetAllOrders

func (sdk Sdk) GetAllOrders(query *getAllOrdersQuery) ([]Order, error)

func (Sdk) GetOpenOrders

func (sdk Sdk) GetOpenOrders(query *getOpenOrdersQuery) ([]Order, error)

func (Sdk) GetOrder

func (sdk Sdk) GetOrder(query *getOrderQuery) (*Order, error)

func (*Sdk) KLines

func (sdk *Sdk) KLines(query *kLinesQuery) ([]KLine, error)

func (Sdk) MyTrades

func (sdk Sdk) MyTrades(query *myTradesQuery) ([]AccountTrade, error)

func (Sdk) NewOrder

func (sdk Sdk) NewOrder(request *newOrderRequest) (*FullOrder, error)

func (Sdk) SymbolOrderBookTicker

func (sdk Sdk) SymbolOrderBookTicker(query *symbolOrderBookTickerQuery) (*OrderBookTicker, error)

func (Sdk) SymbolPriceTicker

func (sdk Sdk) SymbolPriceTicker(query *symbolPriceTickerQuery) (*SymbolPrice, error)

Latest price for a symbol.

func (*Sdk) Trades

func (sdk *Sdk) Trades(query *tradesQuery) ([]Trade, error)

type Symbol

type Symbol struct {
	Symbol             string
	Status             string
	BaseAsset          string
	BaseAssetPrecision int
	QuoteAsset         string
	QuotePrecision     int
	OrderTypes         []string
	IcebergAllowed     bool
	Filters            []Filter
}

type SymbolPrice

type SymbolPrice struct {
	Symbol string
	Price  float64 `json:"price,string"`
}

Symbol price ticker data transfer object (DTO)

type Trade

type Trade struct {
	Id           int
	Price        float64 `json:"price,string"`
	Quantity     float64 `json:"qty,string"`
	Time         int     `json:"time"`
	IsBuyerMaker bool    `json:"isBuyerMaker"`
	IsBestMatch  bool    `json:"isBestMatch"`
}

Jump to

Keyboard shortcuts

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