binance

package
v0.0.0-...-1ca2487 Latest Latest
Warning

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

Go to latest
Published: May 29, 2020 License: MIT Imports: 31 Imported by: 0

README

GoCryptoTrader package Binance

Build Status Software License GoDoc Coverage Status Go Report Card

This binance package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Binance Exchange

Current Features
  • REST Support
  • Websocket Support
How to enable
  // Exchanges will be abstracted out in further updates and examples will be
  // supplied then
How to do REST public/private calls
  • If enabled via "configuration".json file the exchange will be added to the IBotExchange array in the go var bot Bot and you will only be able to use the wrapper interface functions for accessing exchange data. View routines.go for an example of integration usage with GoCryptoTrader. Rudimentary example below:

main.go

var b exchange.IBotExchange

for i := range bot.Exchanges {
  if bot.Exchanges[i].GetName() == "Binance" {
    b = bot.Exchanges[i]
  }
}

// Public calls - wrapper functions

// Fetches current ticker information
tick, err := b.FetchTicker()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := b.FetchOrderbook()
if err != nil {
  // Handle error
}

// Private calls - wrapper functions - make sure your APIKEY and APISECRET are
// set and AuthenticatedAPISupport is set to true

// Fetches current account information
accountInfo, err := b.GetAccountInfo()
if err != nil {
  // Handle error
}
  • If enabled via individually importing package, rudimentary example below:
// Public calls

// Fetches current ticker information
ticker, err := b.GetTicker()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := b.GetOrderBook()
if err != nil {
  // Handle error
}

// Private calls - make sure your APIKEY and APISECRET are set and
// AuthenticatedAPISupport is set to true

// GetUserInfo returns account info
accountInfo, err := b.GetUserInfo(...)
if err != nil {
  // Handle error
}

// Submits an order and the exchange and returns its tradeID
tradeID, err := b.Trade(...)
if err != nil {
  // Handle error
}
How to do Websocket public/private calls
  // Exchanges will be abstracted out in further updates and examples will be
  // supplied then
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// BinanceRequestParamsTimeGTC GTC
	BinanceRequestParamsTimeGTC = RequestParamsTimeForceType("GTC")

	// BinanceRequestParamsTimeIOC IOC
	BinanceRequestParamsTimeIOC = RequestParamsTimeForceType("IOC")

	// BinanceRequestParamsTimeFOK FOK
	BinanceRequestParamsTimeFOK = RequestParamsTimeForceType("FOK")
)
View Source
var (
	// BinanceRequestParamsOrderLimit Limit order
	BinanceRequestParamsOrderLimit = RequestParamsOrderType("LIMIT")

	// BinanceRequestParamsOrderMarket Market order
	BinanceRequestParamsOrderMarket = RequestParamsOrderType("MARKET")

	// BinanceRequestParamsOrderStopLoss STOP_LOSS
	BinanceRequestParamsOrderStopLoss = RequestParamsOrderType("STOP_LOSS")

	// BinanceRequestParamsOrderStopLossLimit STOP_LOSS_LIMIT
	BinanceRequestParamsOrderStopLossLimit = RequestParamsOrderType("STOP_LOSS_LIMIT")

	// BinanceRequestParamsOrderTakeProfit TAKE_PROFIT
	BinanceRequestParamsOrderTakeProfit = RequestParamsOrderType("TAKE_PROFIT")

	// BinanceRequestParamsOrderTakeProfitLimit TAKE_PROFIT_LIMIT
	BinanceRequestParamsOrderTakeProfitLimit = RequestParamsOrderType("TAKE_PROFIT_LIMIT")

	// BinanceRequestParamsOrderLimitMarker LIMIT_MAKER
	BinanceRequestParamsOrderLimitMarker = RequestParamsOrderType("LIMIT_MAKER")
)
View Source
var (
	TimeIntervalMinute         = TimeInterval("1m")
	TimeIntervalThreeMinutes   = TimeInterval("3m")
	TimeIntervalFiveMinutes    = TimeInterval("5m")
	TimeIntervalFifteenMinutes = TimeInterval("15m")
	TimeIntervalThirtyMinutes  = TimeInterval("30m")
	TimeIntervalHour           = TimeInterval("1h")
	TimeIntervalTwoHours       = TimeInterval("2h")
	TimeIntervalFourHours      = TimeInterval("4h")
	TimeIntervalSixHours       = TimeInterval("6h")
	TimeIntervalEightHours     = TimeInterval("8h")
	TimeIntervalTwelveHours    = TimeInterval("12h")
	TimeIntervalDay            = TimeInterval("1d")
	TimeIntervalThreeDays      = TimeInterval("3d")
	TimeIntervalWeek           = TimeInterval("1w")
	TimeIntervalMonth          = TimeInterval("1M")
)

Vars related to time intervals

View Source
var WithdrawalFees = map[currency.Code]float64{}/* 164 elements not displayed */

WithdrawalFees the large list of predefined withdrawal fees Prone to change

Functions

This section is empty.

Types

type Account

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

Account holds the account data

type AggregatedTrade

type AggregatedTrade struct {
	ATradeID       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"`
	BestMatchPrice bool    `json:"M"`
}

AggregatedTrade holds aggregated trade information

type AveragePrice

type AveragePrice struct {
	Mins  int64   `json:"mins"`
	Price float64 `json:"price,string"`
}

AveragePrice holds current average symbol price

type Balance

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

Balance holds query order data

type BestPrice

type BestPrice struct {
	Symbol   string  `json:"symbol"`
	BidPrice float64 `json:"bidPrice,string"`
	BidQty   float64 `json:"bidQty,string"`
	AskPrice float64 `json:"askPrice,string"`
	AskQty   float64 `json:"askQty,string"`
}

BestPrice holds best price data

type Binance

type Binance struct {
	exchange.Base
	WebsocketConn *wshandler.WebsocketConnection
	// contains filtered or unexported fields
}

Binance is the overarching type across the Bithumb package

func (*Binance) AllOrders

func (b *Binance) AllOrders(symbol, orderID, limit string) ([]QueryOrderData, error)

AllOrders Get all account orders; active, canceled, or filled. orderId optional param limit optional param, default 500; max 500

func (*Binance) AuthenticateWebsocket

func (b *Binance) AuthenticateWebsocket() error

AuthenticateWebsocket sends an authentication message to the websocket

func (*Binance) CancelAllOrders

func (b *Binance) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, error)

CancelAllOrders cancels all orders associated with a currency pair

func (*Binance) CancelExistingOrder

func (b *Binance) CancelExistingOrder(symbol string, orderID int64, origClientOrderID string) (CancelOrderResponse, error)

CancelExistingOrder sends a cancel order to Binance

func (*Binance) CancelOrder

func (b *Binance) CancelOrder(order *order.Cancel) error

CancelOrder cancels an order by its corresponding ID number

func (*Binance) CheckIntervals

func (b *Binance) CheckIntervals(interval string) error

CheckIntervals checks value against a variable list

func (*Binance) CheckLimit

func (b *Binance) CheckLimit(limit int) error

CheckLimit checks value against a variable list

func (*Binance) CheckSymbol

func (b *Binance) CheckSymbol(symbol string, assetType asset.Item) error

CheckSymbol checks value against a variable list

func (*Binance) FetchAccountInfo

func (b *Binance) FetchAccountInfo() (account.Holdings, error)

FetchAccountInfo retrieves balances for all enabled currencies

func (*Binance) FetchOrderbook

func (b *Binance) FetchOrderbook(p currency.Pair, assetType asset.Item) (*orderbook.Base, error)

FetchOrderbook returns orderbook base on the currency pair

func (*Binance) FetchTicker

func (b *Binance) FetchTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error)

FetchTicker returns the ticker for a currency pair

func (*Binance) FetchTradablePairs

func (b *Binance) FetchTradablePairs(asset asset.Item) ([]string, error)

FetchTradablePairs returns a list of the exchanges tradable pairs

func (*Binance) GetAccount

func (b *Binance) GetAccount() (*Account, error)

GetAccount returns binance user accounts

func (*Binance) GetActiveOrders

func (b *Binance) GetActiveOrders(req *order.GetOrdersRequest) ([]order.Detail, error)

GetActiveOrders retrieves any orders that are active/open

func (*Binance) GetAggregatedTrades

func (b *Binance) GetAggregatedTrades(symbol string, limit int) ([]AggregatedTrade, error)

GetAggregatedTrades returns aggregated trade activity

symbol: string of currency pair limit: Optional. Default 500; max 1000.

func (*Binance) GetAveragePrice

func (b *Binance) GetAveragePrice(symbol string) (AveragePrice, error)

GetAveragePrice returns current average price for a symbol.

symbol: string of currency pair

func (*Binance) GetBestPrice

func (b *Binance) GetBestPrice(symbol string) (BestPrice, error)

GetBestPrice returns the latest best price for symbol

symbol: string of currency pair

func (*Binance) GetCoinConfig

func (b *Binance) GetCoinConfig() ([]CoinConfig, error)

GetCoinConfig ...

func (*Binance) GetDefaultConfig

func (b *Binance) GetDefaultConfig() (*config.ExchangeConfig, error)

GetDefaultConfig returns a default exchange config

func (*Binance) GetDepositAddress

func (b *Binance) GetDepositAddress(cryptocurrency currency.Code, _ string) (string, error)

GetDepositAddress returns a deposit address for a specified currency

func (*Binance) GetDepositAddressForCurrency

func (b *Binance) GetDepositAddressForCurrency(currency string) (DepositAddress, error)

GetDepositAddressForCurrency retrieves the wallet address for a given currency

func (*Binance) GetDepositAddressForCurrencyNetwork

func (b *Binance) GetDepositAddressForCurrencyNetwork(currency, network string) (DepositAddress, error)

GetDepositAddressForCurrencyNetwork retrieves the wallet address for a given currency

func (*Binance) GetDepositAddressObj

func (b *Binance) GetDepositAddressObj(cryptocurrency currency.Code, _ string) (DepositAddress, error)

GetDepositAddressObj returns a deposit address for a specified currency

func (*Binance) GetDepositHistory

func (b *Binance) GetDepositHistory(asset string, startTimestamp int64) ([]DepositHistory, error)

GetDepositHistory get deposit history

func (*Binance) GetExchangeHistory

func (b *Binance) GetExchangeHistory(p currency.Pair, assetType asset.Item) ([]exchange.TradeHistory, error)

GetExchangeHistory returns historic trade data since exchange opening.

func (*Binance) GetExchangeInfo

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

GetExchangeInfo returns exchange information. Check binance_types for more information

func (*Binance) GetFee

func (b *Binance) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error)

GetFee returns an estimate of fee based on type of transaction

func (*Binance) GetFeeByType

func (b *Binance) GetFeeByType(feeBuilder *exchange.FeeBuilder) (float64, error)

GetFeeByType returns an estimate of fee based on type of transaction

func (*Binance) GetFundingHistory

func (b *Binance) GetFundingHistory() ([]exchange.FundHistory, error)

GetFundingHistory returns funding history, deposits and withdrawals

func (*Binance) GetHistoricCandles

func (b *Binance) GetHistoricCandles(pair currency.Pair, a asset.Item, start, end time.Time, interval time.Duration) (kline.Item, error)

GetHistoricCandles returns candles between a time period for a set time interval

func (*Binance) GetHistoricalTrades

func (b *Binance) GetHistoricalTrades(symbol string, limit int, fromID int64) ([]HistoricalTrade, error)

GetHistoricalTrades returns historical trade activity

symbol: string of currency pair limit: Optional. Default 500; max 1000. fromID:

func (*Binance) GetLatestSpotPrice

func (b *Binance) GetLatestSpotPrice(symbol string) (SymbolPrice, error)

GetLatestSpotPrice returns latest spot price of symbol

symbol: string of currency pair

func (*Binance) GetOrderBook

func (b *Binance) GetOrderBook(obd OrderBookDataRequestParams) (OrderBook, error)

GetOrderBook returns full orderbook information

OrderBookDataRequestParams contains the following members symbol: string of currency pair limit: returned limit amount

func (*Binance) GetOrderHistory

func (b *Binance) GetOrderHistory(req *order.GetOrdersRequest) ([]order.Detail, error)

GetOrderHistory retrieves account order information Can Limit response to specific order status

func (*Binance) GetOrderInfo

func (b *Binance) GetOrderInfo(orderID string) (order.Detail, error)

GetOrderInfo returns information on a current open order

func (*Binance) GetPriceChangeStats

func (b *Binance) GetPriceChangeStats(symbol string) (PriceChangeStats, error)

GetPriceChangeStats returns price change statistics for the last 24 hours

symbol: string of currency pair

func (*Binance) GetRecentTrades

func (b *Binance) GetRecentTrades(rtr RecentTradeRequestParams) ([]RecentTrade, error)

GetRecentTrades returns recent trade activity limit: Up to 500 results returned

func (*Binance) GetSpotKline

func (b *Binance) GetSpotKline(arg KlinesRequestParams) ([]CandleStick, error)

GetSpotKline returns kline data

KlinesRequestParams supports 5 parameters symbol: the symbol to get the kline data for limit: optinal interval: the interval time for the data startTime: startTime filter for kline data endTime: endTime filter for the kline data

func (*Binance) GetSubscriptions

func (b *Binance) GetSubscriptions() ([]wshandler.WebsocketChannelSubscription, error)

GetSubscriptions returns a copied list of subscriptions

func (*Binance) GetTickers

func (b *Binance) GetTickers() ([]PriceChangeStats, error)

GetTickers returns the ticker data for the last 24 hrs

func (*Binance) GetWebsocket

func (b *Binance) GetWebsocket() (*wshandler.Websocket, error)

GetWebsocket returns a pointer to the exchange websocket

func (*Binance) GetWithdrawalHistory

func (b *Binance) GetWithdrawalHistory(asset string, startTimestamp int64) ([]WithdrawalHistory, error)

GetWithdrawalHistory get withdrawal history

func (*Binance) GetWsAuthStreamKey

func (b *Binance) GetWsAuthStreamKey() (string, error)

GetWsAuthStreamKey will retrieve a key to use for authorised WS streaming

func (*Binance) KeepAuthKeyAlive

func (b *Binance) KeepAuthKeyAlive()

KeepAuthKeyAlive will continuously send messages to keep the WS auth key active

func (*Binance) MaintainWsAuthStreamKey

func (b *Binance) MaintainWsAuthStreamKey() error

MaintainWsAuthStreamKey will keep the key alive

func (*Binance) ModifyOrder

func (b *Binance) ModifyOrder(action *order.Modify) (string, error)

ModifyOrder will allow of changing orderbook placement and limit to market conversion

func (*Binance) NewOrder

func (b *Binance) NewOrder(o *NewOrderRequest) (NewOrderResponse, error)

NewOrder sends a new order to Binance

func (*Binance) OpenOrders

func (b *Binance) OpenOrders(symbol string) ([]QueryOrderData, error)

OpenOrders Current open orders. Get all open orders on a symbol. Careful when accessing this with no symbol: The number of requests counted against the rate limiter is significantly higher

func (*Binance) QueryOrder

func (b *Binance) QueryOrder(symbol, origClientOrderID string, orderID int64) (QueryOrderData, error)

QueryOrder returns information on a past order

func (*Binance) Run

func (b *Binance) Run()

Run implements the Binance wrapper

func (*Binance) SeedLocalCache

func (b *Binance) SeedLocalCache(p currency.Pair) error

SeedLocalCache seeds depth data

func (*Binance) SendAuthHTTPRequest

func (b *Binance) SendAuthHTTPRequest(method, path string, params url.Values, f request.EndpointLimit, result interface{}) error

SendAuthHTTPRequest sends an authenticated HTTP request

func (*Binance) SendHTTPRequest

func (b *Binance) SendHTTPRequest(path string, f request.EndpointLimit, result interface{}) error

SendHTTPRequest sends an unauthenticated request

func (*Binance) SetDefaults

func (b *Binance) SetDefaults()

SetDefaults sets the basic defaults for Binance

func (*Binance) SetValues

func (b *Binance) SetValues()

SetValues sets the default valid values

func (*Binance) Setup

func (b *Binance) Setup(exch *config.ExchangeConfig) error

Setup takes in the supplied exchange configuration details and sets params

func (*Binance) Start

func (b *Binance) Start(wg *sync.WaitGroup)

Start starts the Binance go routine

func (*Binance) SubmitOrder

func (b *Binance) SubmitOrder(s *order.Submit) (order.SubmitResponse, error)

SubmitOrder submits a new order

func (*Binance) SubscribeToWebsocketChannels

func (b *Binance) SubscribeToWebsocketChannels(channels []wshandler.WebsocketChannelSubscription) error

SubscribeToWebsocketChannels appends to ChannelsToSubscribe which lets websocket.manageSubscriptions handle subscribing

func (*Binance) UnsubscribeToWebsocketChannels

func (b *Binance) UnsubscribeToWebsocketChannels(channels []wshandler.WebsocketChannelSubscription) error

UnsubscribeToWebsocketChannels removes from ChannelsToSubscribe which lets websocket.manageSubscriptions handle unsubscribing

func (*Binance) UpdateAccountInfo

func (b *Binance) UpdateAccountInfo() (account.Holdings, error)

UpdateAccountInfo retrieves balances for all enabled currencies for the Bithumb exchange

func (*Binance) UpdateLocalCache

func (b *Binance) UpdateLocalCache(wsdp *WebsocketDepthStream) error

UpdateLocalCache updates and returns the most recent iteration of the orderbook

func (*Binance) UpdateOrderbook

func (b *Binance) UpdateOrderbook(p currency.Pair, assetType asset.Item) (*orderbook.Base, error)

UpdateOrderbook updates and returns the orderbook for a currency pair

func (*Binance) UpdateTicker

func (b *Binance) UpdateTicker(p currency.Pair, assetType asset.Item) (*ticker.Price, error)

UpdateTicker updates and returns the ticker for a currency pair

func (*Binance) UpdateTradablePairs

func (b *Binance) UpdateTradablePairs(forceUpdate bool) error

UpdateTradablePairs updates the exchanges available pairs and stores them in the exchanges config

func (*Binance) ValidateCredentials

func (b *Binance) ValidateCredentials() error

ValidateCredentials validates current credentials used for wrapper functionality

func (*Binance) WithdrawCrypto

func (b *Binance) WithdrawCrypto(asset, address, addressTag, name, amount string) (string, error)

WithdrawCrypto sends cryptocurrency to the address of your choosing

func (*Binance) WithdrawCryptoWithNetwork

func (b *Binance) WithdrawCryptoWithNetwork(asset, address, addressTag, name, amount, network, orderID string) (string, error)

WithdrawCryptoWithNetwork sends cryptocurrency to the address of your choosing

func (*Binance) WithdrawCryptocurrencyFunds

func (b *Binance) WithdrawCryptocurrencyFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error)

WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is submitted

func (*Binance) WithdrawFiatFunds

func (b *Binance) WithdrawFiatFunds(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error)

WithdrawFiatFunds returns a withdrawal ID when a withdrawal is submitted

func (*Binance) WithdrawFiatFundsToInternationalBank

func (b *Binance) WithdrawFiatFundsToInternationalBank(withdrawRequest *withdraw.Request) (*withdraw.ExchangeResponse, error)

WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a withdrawal is submitted

func (*Binance) WsConnect

func (b *Binance) WsConnect() error

WsConnect intiates a websocket connection

type CancelOrderResponse

type CancelOrderResponse struct {
	Symbol            string `json:"symbol"`
	OrigClientOrderID string `json:"origClientOrderId"`
	OrderID           int64  `json:"orderId"`
	ClientOrderID     string `json:"clientOrderId"`
}

CancelOrderResponse is the return structured response from the exchange

type CandleStick

type CandleStick struct {
	OpenTime                 time.Time
	Open                     float64
	High                     float64
	Low                      float64
	Close                    float64
	Volume                   float64
	CloseTime                time.Time
	QuoteAssetVolume         float64
	TradeCount               float64
	TakerBuyAssetVolume      float64
	TakerBuyQuoteAssetVolume float64
}

CandleStick holds kline data

type CoinConfig

type CoinConfig struct {
	Coin        string        `json:"coin"`
	Name        string        `json:"name"`
	NetworkList []CoinNetwork `json:"networkList"`
}

CoinConfig ...

type CoinNetwork

type CoinNetwork struct {
	Coin           string `json:"coin"`
	Name           string `json:"name"`
	Network        string `json:"network"`
	WithdrawEnable bool   `json:"withdrawEnable"`
	DepositEnable  bool   `json:"depositEnable"`
	WithdrawFee    string `json:"withdrawFee"`
	WithdrawMin    string `json:"withdrawMin"`
}

CoinNetwork ...

type DepositAddress

type DepositAddress struct {
	Address    string `json:"address"`
	Success    bool   `json:"success"`
	AddressTag string `json:"tag"`
}

DepositAddress ...

type DepositHistory

type DepositHistory struct {
	Amount     float64 `json:"amount"`
	Address    string  `json:"address"`
	AddressTag string  `json:"addressTag"`
	Asset      string  `json:"asset"`
	TxID       string  `json:"txId"`
	Status     int     `json:"status"`
	InsertTime int64   `json:"insertTime"`
}

DepositHistory ...

type DepositHistoryResponse

type DepositHistoryResponse struct {
	Success     bool             `json:"success"`
	Msg         string           `json:"msg"`
	DepositList []DepositHistory `json:"depositList"`
}

DepositHistoryResponse ...

type DepthUpdateParams

type DepthUpdateParams []struct {
	PriceLevel float64
	Quantity   float64
	// contains filtered or unexported fields
}

DepthUpdateParams is used as an embedded type for WebsocketDepthStream

type ExchangeInfo

type ExchangeInfo struct {
	Code       int    `json:"code"`
	Msg        string `json:"msg"`
	Timezone   string `json:"timezone"`
	Servertime int64  `json:"serverTime"`
	RateLimits []struct {
		RateLimitType string `json:"rateLimitType"`
		Interval      string `json:"interval"`
		Limit         int    `json:"limit"`
	} `json:"rateLimits"`
	ExchangeFilters interface{} `json:"exchangeFilters"`
	Symbols         []struct {
		Symbol             string   `json:"symbol"`
		Status             string   `json:"status"`
		BaseAsset          string   `json:"baseAsset"`
		BaseAssetPrecision int      `json:"baseAssetPrecision"`
		QuoteAsset         string   `json:"quoteAsset"`
		QuotePrecision     int      `json:"quotePrecision"`
		OrderTypes         []string `json:"orderTypes"`
		IcebergAllowed     bool     `json:"icebergAllowed"`
		Filters            []struct {
			FilterType          string  `json:"filterType"`
			MinPrice            float64 `json:"minPrice,string"`
			MaxPrice            float64 `json:"maxPrice,string"`
			TickSize            float64 `json:"tickSize,string"`
			MultiplierUp        float64 `json:"multiplierUp,string"`
			MultiplierDown      float64 `json:"multiplierDown,string"`
			AvgPriceMins        int64   `json:"avgPriceMins"`
			MinQty              float64 `json:"minQty,string"`
			MaxQty              float64 `json:"maxQty,string"`
			StepSize            float64 `json:"stepSize,string"`
			MinNotional         float64 `json:"minNotional,string"`
			ApplyToMarket       bool    `json:"applyToMarket"`
			Limit               int64   `json:"limit"`
			MaxNumAlgoOrders    int64   `json:"maxNumAlgoOrders"`
			MaxNumIcebergOrders int64   `json:"maxNumIcebergOrders"`
		} `json:"filters"`
	} `json:"symbols"`
}

ExchangeInfo holds the full exchange information type

type HistoricalTrade

type HistoricalTrade struct {
	Code         int     `json:"code"`
	Msg          string  `json:"msg"`
	ID           int64   `json:"id"`
	Price        float64 `json:"price,string"`
	Quantity     float64 `json:"qty,string"`
	Time         int64   `json:"time"`
	IsBuyerMaker bool    `json:"isBuyerMaker"`
	IsBestMatch  bool    `json:"isBestMatch"`
}

HistoricalTrade holds recent trade data

type KlineStream

type KlineStream struct {
	EventType string `json:"e"`
	EventTime int64  `json:"E"`
	Symbol    string `json:"s"`
	Kline     struct {
		StartTime                int64   `json:"t"`
		CloseTime                int64   `json:"T"`
		Symbol                   string  `json:"s"`
		Interval                 string  `json:"i"`
		FirstTradeID             int64   `json:"f"`
		LastTradeID              int64   `json:"L"`
		OpenPrice                float64 `json:"o,string"`
		ClosePrice               float64 `json:"c,string"`
		HighPrice                float64 `json:"h,string"`
		LowPrice                 float64 `json:"l,string"`
		Volume                   float64 `json:"v,string"`
		NumberOfTrades           int64   `json:"n"`
		KlineClosed              bool    `json:"x"`
		Quote                    float64 `json:"q,string"`
		TakerBuyBaseAssetVolume  float64 `json:"V,string"`
		TakerBuyQuoteAssetVolume float64 `json:"Q,string"`
	} `json:"k"`
}

KlineStream holds the kline stream data

type KlinesRequestParams

type KlinesRequestParams struct {
	Symbol    string       // Required field; example LTCBTC, BTCUSDT
	Interval  TimeInterval // Time interval period
	Limit     int          // Default 500; max 500.
	StartTime int64
	EndTime   int64
}

KlinesRequestParams represents Klines request data.

type NewOrderRequest

type NewOrderRequest struct {
	// Symbol (currency pair to trade)
	Symbol string
	// Side Buy or Sell
	Side string
	// TradeType (market or limit order)
	TradeType RequestParamsOrderType
	// TimeInForce specifies how long the order remains in effect.
	// Examples are (Good Till Cancel (GTC), Immediate or Cancel (IOC) and Fill Or Kill (FOK))
	TimeInForce RequestParamsTimeForceType
	// Quantity
	Quantity         float64
	Price            float64
	NewClientOrderID string
	StopPrice        float64 // Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
	IcebergQty       float64 // Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
	NewOrderRespType string
}

NewOrderRequest request type

type NewOrderResponse

type NewOrderResponse struct {
	Code            int     `json:"code"`
	Msg             string  `json:"msg"`
	Symbol          string  `json:"symbol"`
	OrderID         int64   `json:"orderId"`
	ClientOrderID   string  `json:"clientOrderId"`
	TransactionTime int64   `json:"transactTime"`
	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"`
	Fills           []struct {
		Price           float64 `json:"price,string"`
		Qty             float64 `json:"qty,string"`
		Commission      float64 `json:"commission,string"`
		CommissionAsset string  `json:"commissionAsset"`
	} `json:"fills"`
}

NewOrderResponse is the return structured response from the exchange

type OrderBook

type OrderBook struct {
	LastUpdateID int64
	Code         int
	Msg          string
	Bids         []OrderbookItem
	Asks         []OrderbookItem
}

OrderBook actual structured data that can be used for orderbook

type OrderBookData

type OrderBookData struct {
	Code         int         `json:"code"`
	Msg          string      `json:"msg"`
	LastUpdateID int64       `json:"lastUpdateId"`
	Bids         [][2]string `json:"bids"`
	Asks         [][2]string `json:"asks"`
}

OrderBookData is resp data from orderbook endpoint

type OrderBookDataRequestParams

type OrderBookDataRequestParams struct {
	Symbol string `json:"symbol"` // Required field; example LTCBTC,BTCUSDT
	Limit  int    `json:"limit"`  // Default 100; max 1000. Valid limits:[5, 10, 20, 50, 100, 500, 1000]
}

OrderBookDataRequestParams represents Klines request data.

type OrderbookItem

type OrderbookItem struct {
	Price    float64
	Quantity float64
}

OrderbookItem stores an individual orderbook item

type PriceChangeStats

type PriceChangeStats struct {
	Symbol             string  `json:"symbol"`
	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"`
	LastQty            float64 `json:"lastQty,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"`
	QuoteVolume        float64 `json:"quoteVolume,string"`
	OpenTime           int64   `json:"openTime"`
	CloseTime          int64   `json:"closeTime"`
	FirstID            int64   `json:"firstId"`
	LastID             int64   `json:"lastId"`
	Count              int64   `json:"count"`
}

PriceChangeStats contains statistics for the last 24 hours trade

type QueryOrderData

type QueryOrderData struct {
	Code          int     `json:"code"`
	Msg           string  `json:"msg"`
	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          float64 `json:"time"`
	IsWorking     bool    `json:"isWorking"`
}

QueryOrderData holds query order data

type RateLimit

type RateLimit struct {
	GlobalRate *rate.Limiter
	Orders     *rate.Limiter
}

RateLimit implements the request.Limiter interface

func SetRateLimit

func SetRateLimit() *RateLimit

SetRateLimit returns the rate limit for the exchange

func (*RateLimit) Limit

func (r *RateLimit) Limit(f request.EndpointLimit) error

Limit executes rate limiting functionality for Binance

type RecentTrade

type RecentTrade struct {
	ID           int64   `json:"id"`
	Price        float64 `json:"price,string"`
	Quantity     float64 `json:"qty,string"`
	Time         float64 `json:"time"`
	IsBuyerMaker bool    `json:"isBuyerMaker"`
	IsBestMatch  bool    `json:"isBestMatch"`
}

RecentTrade holds recent trade data

type RecentTradeRequestParams

type RecentTradeRequestParams struct {
	Symbol string `json:"symbol"` // Required field. example LTCBTC, BTCUSDT
	Limit  int    `json:"limit"`  // Default 500; max 500.
}

RecentTradeRequestParams represents Klines request data.

type RequestParamsOrderType

type RequestParamsOrderType string

RequestParamsOrderType trade order type

type RequestParamsTimeForceType

type RequestParamsTimeForceType string

RequestParamsTimeForceType Time in force

type Response

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

Response holds basic binance api response data

type SymbolPrice

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

SymbolPrice holds basic symbol price

type TickerStream

type TickerStream struct {
	EventType              string  `json:"e"`
	EventTime              int64   `json:"E"`
	Symbol                 string  `json:"s"`
	PriceChange            float64 `json:"p,string"`
	PriceChangePercent     float64 `json:"P,string"`
	WeightedAvgPrice       float64 `json:"w,string"`
	ClosePrice             float64 `json:"x,string"`
	LastPrice              float64 `json:"c,string"`
	LastPriceQuantity      float64 `json:"Q,string"`
	BestBidPrice           float64 `json:"b,string"`
	BestBidQuantity        float64 `json:"B,string"`
	BestAskPrice           float64 `json:"a,string"`
	BestAskQuantity        float64 `json:"A,string"`
	OpenPrice              float64 `json:"o,string"`
	HighPrice              float64 `json:"h,string"`
	LowPrice               float64 `json:"l,string"`
	TotalTradedVolume      float64 `json:"v,string"`
	TotalTradedQuoteVolume float64 `json:"q,string"`
	OpenTime               int64   `json:"O"`
	CloseTime              int64   `json:"C"`
	FirstTradeID           int64   `json:"F"`
	LastTradeID            int64   `json:"L"`
	NumberOfTrades         int64   `json:"n"`
}

TickerStream holds the ticker stream data

type TimeInterval

type TimeInterval string

TimeInterval represents interval enum.

type TradeStream

type TradeStream struct {
	EventType      string `json:"e"`
	EventTime      int64  `json:"E"`
	Symbol         string `json:"s"`
	TradeID        int64  `json:"t"`
	Price          string `json:"p"`
	Quantity       string `json:"q"`
	BuyerOrderID   int64  `json:"b"`
	SellerOrderID  int64  `json:"a"`
	TimeStamp      int64  `json:"T"`
	Maker          bool   `json:"m"`
	BestMatchPrice bool   `json:"M"`
}

TradeStream holds the trade stream data

type UserAccountStream

type UserAccountStream struct {
	ListenKey string `json:"listenKey"`
}

UserAccountStream contains a key to maintain an authorised websocket connection

type WebsocketDepthStream

type WebsocketDepthStream struct {
	Event         string          `json:"e"`
	Timestamp     int64           `json:"E"`
	Pair          string          `json:"s"`
	FirstUpdateID int64           `json:"U"`
	LastUpdateID  int64           `json:"u"`
	UpdateBids    [][]interface{} `json:"b"`
	UpdateAsks    [][]interface{} `json:"a"`
}

WebsocketDepthStream is the difference for the update depth stream

type WithdrawResponse

type WithdrawResponse struct {
	Success bool   `json:"success"`
	Msg     string `json:"msg"`
	ID      string `json:"id"`
}

WithdrawResponse contains status of withdrawal request

type WithdrawalHistory

type WithdrawalHistory struct {
	ID              string  `json:"ID"`
	WithdrawOrderID string  `json:"withdrawOrderId"`
	Amount          float64 `json:"amount"`
	TransactionFee  float64 `json:"transactionFee"`
	Address         string  `json:"address"`
	AddressTag      string  `json:"addressTag"`
	Asset           string  `json:"asset"`
	TxID            string  `json:"txId"`
	Status          int     `json:"status"`
	ApplyTime       int64   `json:"applyTime"`
}

WithdrawalHistory ...

type WithdrawalHistoryResponse

type WithdrawalHistoryResponse struct {
	Success      bool                `json:"success"`
	Msg          string              `json:"msg"`
	WithdrawList []WithdrawalHistory `json:"withdrawList"`
}

WithdrawalHistoryResponse ...

Jump to

Keyboard shortcuts

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