binance

package
Version: v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2021 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

account.go

Account (Signed) Endpoints for Binance Exchange API

binance.go

Wrapper for the Binance Exchange API

Authors:

Pat DePippo  <patrick.depippo@dcrypt.io>
Matthew Woop <matthew.woop@dcrypt.io>

To Do:

client.go

Wrapper for the Binance Exchange API

market.go

Market Data Endpoints for the Binance Exchange API

Util Functions for Binance Api Wrapper

Index

Constants

View Source
const (
	BaseUrl = "https://api.binance.com"
)

Variables

View Source
var IntervalEnum = map[string]bool{
	"1m":  true,
	"3m":  true,
	"5m":  true,
	"15m": true,
	"30m": true,
	"1h":  true,
	"2h":  true,
	"4h":  true,
	"6h":  true,
	"8h":  true,
	"12h": true,
	"1d":  true,
	"3d":  true,
	"1w":  true,
	"1M":  true,
}
View Source
var OrderSideEnum = map[string]bool{
	"BUY":  true,
	"SELL": true,
}
View Source
var OrderTIFEnum = map[string]bool{
	"GTC": true,
	"IOC": true,
	"FOK": true,
}
View Source
var OrderTypeEnum = map[string]bool{
	"LIMIT":  true,
	"MARKET": true,
}

Functions

This section is empty.

Types

type Account

type Account struct {
	MakerCommission  int64     `json:"makerCommission"`
	TakerCommission  int64     `json:"takerCommission"`
	BuyerCommission  int64     `json:"buyerCommission"`
	SellerCommission int64     `json:"sellerCommission"`
	CanTrade         bool      `json:"canTrade"`
	CanWithdraw      bool      `json:"canWithdraw"`
	CanDeposit       bool      `json:"canDeposit"`
	Balances         []Balance `json:"balances"`
}

Result from: GET /api/v3/account

type AggTrade

type AggTrade struct {
	TradeId      int64   `json:"a"`
	Price        float64 `json:"p,string"`
	Quantity     float64 `json:"q,string"`
	FirstTradeId int64   `json:"f"`
	LastTradeId  int64   `json:"l"`
	Timestamp    int64   `json:"T"`
	Maker        bool    `json:"m"`
	BestMatch    bool    `json:"M"`
}

Result from: GET /api/v1/aggTrade

type AllOrdersQuery

type AllOrdersQuery struct {
	Symbol     string
	OrderId    int64
	Limit      int64
	RecvWindow int64
}

Input for: GET /api/v3/allOrders

func (*AllOrdersQuery) ValidateAllOrdersQuery

func (q *AllOrdersQuery) ValidateAllOrdersQuery() error

type AssetDetail

type AssetDetail struct {
	MinWithdrawAmount decimal.Decimal `json:"minWithdrawAmount"`
	WithdrawFee       decimal.Decimal `json:"withdrawFee"`
	DepositStatus     bool            `json:"depositStatus"`
	WithdrawStatus    bool            `json:"withdrawStatus"`
	DepositTip        string          `json:"depositTip"`
}

type AssetDetailList

type AssetDetailList struct {
	AssetDetail map[string]AssetDetail `json:"assetDetail"`
}

type BadRequest

type BadRequest struct {
	Code int64  `json:"code"`
	Msg  string `json:"msg"`
}

type Balance

type Balance struct {
	Asset  string
	Free   decimal.Decimal
	Locked decimal.Decimal
}

type Binance

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

func New

func New(key, secret string) *Binance

func handleErr(r jsonResponse) error {

if !r.Success {
    return errors.New(r.Message)
}

return nil

}

func (*Binance) CancelOrder

func (b *Binance) CancelOrder(query OrderQuery) (order CanceledOrder, err error)

Cancel an Order

func (*Binance) CheckOrder

func (b *Binance) CheckOrder(query OrderQuery) (status OrderStatus, err error)

Check the Status of an Order

func (*Binance) Get24Hr

func (b *Binance) Get24Hr(q SymbolQuery) (changeStats ChangeStats, err error)

24 hour price change statistics.

func (*Binance) GetAccountInfo

func (b *Binance) GetAccountInfo() (account Account, err error)

Get Basic Account Information

func (*Binance) GetAggTrades

func (b *Binance) GetAggTrades(q SymbolQuery) (trades []AggTrade, err error)

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

func (*Binance) GetAllOpenOrders

func (b *Binance) GetAllOpenOrders() (orders []OrderStatus, err error)

Retrieve All Open Orders

func (*Binance) GetAllOrders

func (b *Binance) GetAllOrders(query AllOrdersQuery) (orders []OrderStatus, err error)

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

func (*Binance) GetAllPrices

func (b *Binance) GetAllPrices() (prices []TickerPrice, err error)

Latest price for all symbols.

func (*Binance) GetAssetDetail

func (b *Binance) GetAssetDetail() (assetDetail AssetDetailList, err error)

Retrieves all asset details

func (*Binance) GetBookTickers

func (b *Binance) GetBookTickers() (booktickers []BookTicker, err error)

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

func (*Binance) GetDepositHistory

func (b *Binance) GetDepositHistory() (deposits DepositList, err error)

Retrieves all deposits

func (*Binance) GetExchangeInfo

func (b *Binance) GetExchangeInfo() (exchangeinfo ExchangeInfo, err error)

Exchange filters for all symbols

func (*Binance) GetKlines

func (b *Binance) GetKlines(q KlineQuery) (klines []Kline, err error)

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

func (*Binance) GetLastPrice

func (b *Binance) GetLastPrice(q SymbolQuery) (price TickerPrice, err error)

Latest price for an individual symbol

func (*Binance) GetOpenOrders

func (b *Binance) GetOpenOrders(query OpenOrdersQuery) (orders []OrderStatus, err error)

Retrieve All Open Orders for a given symbol

func (*Binance) GetOrderBook

func (b *Binance) GetOrderBook(q OrderBookQuery) (book OrderBook, err error)

Get order book

func (*Binance) GetPositions

func (b *Binance) GetPositions() (positions []*Balance, err error)

Filter Basic Account Information To Retrieve Current Holdings

func (*Binance) GetTrades

func (b *Binance) GetTrades(symbol string) (trades []Trade, err error)

Retrieves all trades

func (*Binance) GetWithdrawHistory

func (b *Binance) GetWithdrawHistory() (withdraws WithdrawList, err error)

Retrieves all withdrawals

func (*Binance) GetWithdrawalSystemStatus

func (b *Binance) GetWithdrawalSystemStatus() (withdrawalSystemStatus WithdrawalSystemStatus, err error)

Ping Withdrawal API. Status is returned in response.

func (*Binance) NewUserWSChannel

func (c *Binance) NewUserWSChannel() (err error,
	accountUpdate chan *WSAccountUpdate,
	orderUpdate chan *WSOrderUpdate,
	done *DoneChannel)

NewUserWSChannel POST /api/v1/userDataStream

func (*Binance) Ping

func (b *Binance) Ping() (pingResponse PingResponse, err error)

Ping Rest API. If no error is returned, API is up and running.

func (*Binance) PlaceLimitOrder

func (b *Binance) PlaceLimitOrder(l LimitOrder) (res PlacedOrder, err error)

Place a Limit Order

func (*Binance) PlaceMarketOrder

func (b *Binance) PlaceMarketOrder(m MarketOrder) (res PlacedOrder, err error)

Place a Market Order

func (*Binance) StopUserWSChannel

func (c *Binance) StopUserWSChannel() error

StopUserWSChannel DELETE /api/v1/userDataStream

func (*Binance) UpdateUserWSChannel

func (c *Binance) UpdateUserWSChannel(done *DoneChannel)

UpdateUserWSChannel PUT /api/v1/userDataStream

type BookTicker

type BookTicker struct {
	Symbol      string          `json:"symbol"`
	BidPrice    decimal.Decimal `json:"bidPrice,string"`
	BidQuantity decimal.Decimal `json:"bidQty,string"`
	AskPrice    decimal.Decimal `json:"askPrice,string"`
	AskQuantity decimal.Decimal `json:"askQty,string"`
}

Result from: GET /api/v1/allBookTickers

type CanceledOrder

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

Result from: DELETE /api/v3/order

type ChangeStats

type ChangeStats struct {
	PriceChange        float64 `json:"priceChange,string"`
	PriceChangePercent float64 `json:"priceChangePercent,string"`
	WeightedAvgPrice   float64 `json:"weightedAvgPrice,string"`
	PrevClosePrice     float64 `json:"prevClosePrice,string"`
	LastPrice          float64 `json:"lastPrice,string"`
	BidPrice           float64 `json:"bidPrice,string"`
	AskPrice           float64 `json:"askPrice,string"`
	OpenPrice          float64 `json:"openPrice,string"`
	HighPrice          float64 `json:"highPrice,string"`
	LowPrice           float64 `json:"lowPrice,string"`
	Volume             float64 `json:"volume,string"`
	OpenTime           int64   `json:"openTime"`
	CloseTime          int64   `json:"closeTime"`
	FirstId            int64   `json:"firstId"`
	LastId             int64   `json:"lastId"`
	Count              int64   `json:"count"`
}

Result from: GET /api/v1/ticker/24hr

type Client

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

func NewClient

func NewClient(key, secret string) (c *Client)

Creates a new Binance HTTP Client

type Deposit

type Deposit struct {
	InsertTime int64   `json:"insertTime"`
	Amount     float64 `json:"amount"`
	Asset      string  `json:"asset"`
	Address    string  `json:"address"`
	TxId       string  `json:"txId"`
	Status     int64   `json:"status"`
}

Result from: GET /api/v3/depositHistory

type DepositList

type DepositList struct {
	Deposits []Deposit `json:"depositList"`
}

type DoneChannel

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

func NewDoneChannel

func NewDoneChannel() *DoneChannel

func (*DoneChannel) Close

func (d *DoneChannel) Close()

func (DoneChannel) IsClosed

func (d DoneChannel) IsClosed() bool

func (DoneChannel) Read

func (d DoneChannel) Read() <-chan interface{}

func (DoneChannel) Write

func (d DoneChannel) Write(data interface{}) bool

type ExchangeInfo

type ExchangeInfo struct {
	ExchangeFilters []string     `json:"ExchangeFilters"`
	RateLimits      []RateLimit  `json:"rateLimits"`
	ServerTime      int64        `json:"serverTime"`
	Symbols         []SymbolInfo `json:"symbols"`
	TimeZone        string       `json:"timezone"`
}

type Kline

type Kline struct {
	OpenTime         int64
	Open             float64
	High             float64
	Low              float64
	Close            float64
	Volume           float64
	CloseTime        int64
	QuoteVolume      float64
	NumTrades        int64
	TakerBaseVolume  float64
	TakerQuoteVolume float64
}

func (*Kline) UnmarshalJSON

func (k *Kline) UnmarshalJSON(b []byte) error

Custom Unmarshal function to handle response data format

type KlineQuery

type KlineQuery struct {
	Symbol   string
	Interval string
	Limit    int64
}

Input for: Get /api/v1/klines

func (*KlineQuery) ValidateKlineQuery

func (q *KlineQuery) ValidateKlineQuery() error

type LimitOrder

type LimitOrder struct {
	Symbol      string
	Side        string
	Type        string
	TimeInForce string
	Quantity    decimal.Decimal
	Price       decimal.Decimal
	RecvWindow  int64
}

Input for: POST /api/v3/order

func (*LimitOrder) ValidateLimitOrder

func (l *LimitOrder) ValidateLimitOrder() error

Validating a Limit Order

type MarketOrder

type MarketOrder struct {
	Symbol     string
	Side       string
	Type       string
	Quantity   float64
	RecvWindow int64
}

func (*MarketOrder) ValidateMarketOrder

func (m *MarketOrder) ValidateMarketOrder() error

type OpenOrdersQuery

type OpenOrdersQuery struct {
	Symbol     string
	RecvWindow int64
}

Input for: GET /api/v3/openOrders

func (*OpenOrdersQuery) ValidateOpenOrdersQuery

func (q *OpenOrdersQuery) ValidateOpenOrdersQuery() error

type Order

type Order struct {
	Price    float64 `json:",string"`
	Quantity float64 `json:",string"`
}

func (*Order) UnmarshalJSON

func (o *Order) UnmarshalJSON(b []byte) error

Custom Unmarshal function to handle response data format

type OrderBook

type OrderBook struct {
	LastUpdatedId int64   `json:"lastUpdatedId"`
	Bids          []Order `json:"bids"`
	Asks          []Order `json:"asks"`
}

Result from: GET /api/v1/depth

type OrderBookQuery

type OrderBookQuery struct {
	Symbol string
	Limit  int64
}

Input for: GET /api/v1/depth

func (*OrderBookQuery) ValidateOrderBookQuery

func (q *OrderBookQuery) ValidateOrderBookQuery() error

type OrderQuery

type OrderQuery struct {
	Symbol     string
	OrderId    string
	RecvWindow int64
}

Input for: GET & DELETE /api/v3/order

func (*OrderQuery) ValidateOrderQuery

func (q *OrderQuery) ValidateOrderQuery() error

type OrderStatus

type OrderStatus struct {
	Symbol        string  `json:"symbol"`
	OrderId       int64   `json:"orderId"`
	ClientOrderId string  `json:"clientOrderId"`
	Price         float64 `json:"price,string"`
	OrigQty       float64 `json:"origQty,string"`
	ExecutedQty   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"`
	IcebergQty    float64 `json:"icebergQty,string"`
	Time          int64   `json:"time"`
}

Result from: GET /api/v3/order

type PingResponse

type PingResponse struct{}

type PlacedOrder

type PlacedOrder struct {
	Symbol        string `json:"symbol"`
	OrderId       int64  `json:"orderId"`
	ClientOrderId string `json:"clientOrderId"`
	TransactTime  int64  `json:"transactTime"`
	Status        string `json:"status"` // EXPIRED ...
}

Result from: POST /api/v3/order

type RateLimit

type RateLimit struct {
	Limit         int64  `json:"limit"`
	Interval      string `json:"interval"`
	RateLimitType string `json:"rateLimitType"`
}

type SymbolFilter

type SymbolFilter struct {
	Type        string  `json:"filterType"`
	MinPrice    float64 `json:"minPrice,string"`
	MaxPrice    float64 `json:"maxPrice,string"`
	TickSize    float64 `json:"tickSize,string"`
	StepSize    float64 `json:"stepSize,string"`
	MinQty      float64 `json:"minQty,string"`
	MaxQty      float64 `json:"maxQty,string"`
	MinNotional float64 `json:"minNotional,string"`
}

type SymbolInfo

type SymbolInfo struct {
	Symbol             string         `json:"symbol"`
	BaseAsset          string         `json:"baseAsset"`
	QuotePrecision     int64          `json:"quotePrecision"`
	BaseAssetPrecision int64          `json:"baseAssetPrecision"`
	Status             string         `json:"status"`
	OrderTypes         []string       `json:"orderTypes"`
	Filters            []SymbolFilter `json:"filters"`
	QuoteAsset         string         `json:"quoteAsset"`
	IceBergAllowed     bool           `json:"icebergAllowed"`
}

type SymbolQuery

type SymbolQuery struct {
	Symbol string
}

Input for: GET /api/v1/24hr & /api/v1/aggTrades

func (*SymbolQuery) ValidateSymbolQuery

func (q *SymbolQuery) ValidateSymbolQuery() error

type SystemStatus

type SystemStatus int64
const (
	SystemStatusNormal      SystemStatus = 0
	SystemStatusMaintenance SystemStatus = 1
)

type TickerPrice

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

Result from: GET /api/v1/allPrices

type Trade

type Trade struct {
	Id              int64   `json:"id"`
	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"`
}

Result from: GET /api/v3/myTrades

type WSAccountUpdate

type WSAccountUpdate struct {
	//EventType            string       `json:"e"` // Event type
	//EventTime            int64        `json:"E"` // Event time
	//MakerCommissionRate  int64        `json:"m"` // Maker commission rate (bips)
	//TakerCommissionRate  int64        `json:"t"` // Taker commission rate (bips)
	//BuyerCommissionRate  int64        `json:"b"` // Buyer commission rate (bips)
	//SellerCommissionRate int64        `json:"s"` // Seller commission rate (bips)
	//CanTrad              bool         `json:"T"` // Can trade?
	//CanWithdraw          bool         `json:"W"` // Can withdraw?
	//CanDeposit           bool         `json:"D"` // Can deposit?
	//LastAccountUpdate    int64      `json:"u"` // Time of last account update
	Balance []*Balance `json:"B"`
}

type WSOrderUpdate

type WSOrderUpdate struct {
	EventType string `json:"e"` // Event type
	EventTime int64  `json:"E"` // Event time
	Symbol    string `json:"s"` // Symbol
	//ClientOrderID                          string          `json:"c"` // Client order ID
	Side            string          `json:"S"` // Side
	OrderType       string          `json:"o"` // Order type
	TimeInForce     string          `json:"f"` // Time in force
	OrderQuantity   decimal.Decimal `json:"q"` // Order quantity
	Q               decimal.Decimal `json:"Q"`
	OrderPrice      decimal.Decimal `json:"p"` // Order price
	StopPrice       decimal.Decimal `json:"P"` // Stop price
	IcebergQuantity decimal.Decimal `json:"F"` // Iceberg quantity
	//Ignore1                                int64            `json:"g"` // Ignore // TODO: maybe int32 ??
	//OriginalClientOrderID                  string          `json:"C"` // Original client order ID; This is the ID of the order being canceled
	CurrentExecutionType string `json:"x"` // Current execution type
	// CurrentExecutionType:
	// NEW
	// CANCELED
	// REPLACED (currently unused)
	// REJECTED
	// TRADE
	// EXPIRED
	CurrentOrderStatus string `json:"X"` // Current order status
	//OrderRejectReason                      string          `json:"r"` // Order reject reason; will be an error code.
	OrderID                  int64           `json:"i"` // Order ID
	LastExecutedQuantity     decimal.Decimal `json:"l"` // Last executed quantity
	CumulativeFilledQuantity decimal.Decimal `json:"z"` // Cumulative filled quantity
	LastExecutedPrice        decimal.Decimal `json:"L"` // Last executed price
	CommissionAmount         decimal.Decimal `json:"n"` // Commission amount
	CommissionAsset          *string         `json:"N"` // Commission asset
	TransactionTime          int64           `json:"T"` // Transaction time
	TradeID                  int64           `json:"t"` // Trade ID
	Ignore2                  int64           `json:"I"` // Ignore
	IsOrderWorking           bool            `json:"w"` // Is the order working? Stops will have
	//IsTradeMakerSide                       bool            `json:"m"` // Is this trade the maker side?
	//Ignore3                                bool            `json:"M"` // Ignore
	OrderCreationTime                      int64           `json:"O"` // Order creation time
	CumulativeQuoteAssetTransactedQuantity decimal.Decimal `json:"Z"` // Cumulative quote asset transacted quantity
	LastQuoteAssetTransactedQuantity       decimal.Decimal `json:"Y"` // Last quote asset transacted quantity (i.e. lastPrice * lastQty)
}

type Withdraw

type Withdraw struct {
	Id        string  `json:"id"`
	Amount    float64 `json:"amount"`
	Address   string  `json:"address"`
	Asset     string  `json:"asset"`
	TxId      string  `json:"txId"`
	ApplyTime int64   `json:"applyTime"`
	Status    int64   `json:"status"`
}

Result from: GET /api/v3/withdrawHistory

type WithdrawList

type WithdrawList struct {
	Withdraws []Withdraw `json:"withdrawList"`
}

type WithdrawalSystemStatus

type WithdrawalSystemStatus struct {
	Status SystemStatus `json:"status"`
	Msg    string       `json:"msg"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL