binance

package module
v0.0.0-...-7018f4a Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2019 License: MIT Imports: 12 Imported by: 0

README

Golang Binance API

binance-api is a lightweight Golang implementation for Binance API, providing complete API coverage, and supports both REST API and websockets API

This project is designed to help you interact with the Binance API, streaming candlestick charts data, market depth, or use other advanced features binance exposes via API.

Installation

go get github.com/eranyanay/binance-api

Getting started

// Generate default client
client := binance.NewBinanceClient("API-KEY", "SECRET")

// Generate client with custom window size
client := binance.NewBinanceClientWindow("API-KEY", "SECRET", 5000)

Examples

REST API usage examples

Get depth for symbol
depth, err := client.Depth(&binance.DepthOpts{Symbol: "ETHBTC"})
Get candlesticks for symbol
klines, err := client.Klines(&binance.KlinesOpts{
		Symbol: "ETHBTC",
		Interval: binance.KlineInterval15m,
})
Get 24 hour price change statistics for symbol
stats, err := client.Ticker(&binance.TickerOpts{Symbol: "ETHBTC"})
Get latest prices for all symbols
prices, err := client.Prices()
Create new order for ETHBTC, purchase 1 quantity at price 0.05BTC
order, err := client.NewOrder(&binance.NewOrderOpts{
		Symbol: "ETHBTC",
		Type: binance.OrderTypeLimit,
		Price: "0.05",
		Quantity: "1",
		Side: binance.OrderSideBuy,
		TimeInForce: binance.TimeInForceGTC,
	})
Test new order options
order, err := client.NewOrderTest(&binance.NewOrderOpts{
		Symbol: "ETHBTC",
		Type: binance.OrderTypeLimit,
		Price: "0.05",
		Quantity: "1",
		Side: binance.OrderSideBuy,
		TimeInForce: binance.TimeInForceGTC,
	})
Create stop loss order
order, err := client.NewOrder(&binance.NewOrderOpts{
		Symbol: "ETHBTC",
		Type: binance.OrderTypeLimit,
		Price: "0.05",
		StopPrice: "0.049",
		Quantity: "1",
		Side: binance.OrderSideBuy,
		TimeInForce: binance.TimeInForceGTC,
	})
Query order status

Orders are assigned with order ID when issued and can later be queried using it

query, err := client.QueryOrder(&binance.QueryOrderOpts{Symbol:"ETHBTC", OrderID:order.OrderID})
Cancel an open order
cancel, err := client.CancelOrder(&binance.CancelOrderOpts{Symbol:"ETHBTC", OrderID:order.OrderID})
Open orders for a symbol
orders, err := client.OpenOrders(&binance.OpenOrdersOpts{Symbol:"ETHBTC"})
Get all account orders for symbol ETHBTC, with ID greater than 5
orders, err := client.AllOrders(&binance.AllOrdersOpts{Symbol:"ETHBTC", OrderID: 5})
Get account information
info, err := client.Account()
Get account trades for symbol
trades, err := client.Trades(&binance.TradesOpts{Symbol:"ETHBTC"})
Get aggreagated trades for symbol
trades, err := client.AggregatedTrades(&binance.AggregatedTradeOpts{Symbol:"ETHBTC"})
Get best tickers for all symbols
tickers, err := client.AllBookTickers()
Create a new datastream key
key, err := client.DataStream()
Set datastream key keep-alive to prevent from it to timeout
err := client.DataStreamKeepAlive(key)
Close datastream
err := client.DataStreamClose(key)

Websockets API usage examples

Depth for symbol
conn, err := client.DepthWS("ETHBTC")
if err != nil {
	// Handle error
}
defer conn.Close()
for {
	update, err := conn.Read()
	if err != nil {
		// Handle error
	}
	fmt.Printf("Depth update: %v", update)
}
Klines for symbol with interval of 15 minutes per candlestick
conn, err := client.Klines("ETHBTC", binance.KlineInterval15m)
if err != nil {
	// Handle error
}
defer conn.Close()
for {
	update, err := conn.Read()
	if err != nil {
		// Handle error
	}
	fmt.Printf("Klines update: %v", update)
}
Trades for symbol
conn, err := client.Trades("ETHBTC")
if err != nil {
	// Handle error
}
defer conn.Close()
for {
	update, err := conn.Read()
	if err != nil {
		// Handle error
	}
	fmt.Printf("Trades update: %v", update)
}
Account info updates
// Retrieve new datastream key
key, err := client.DataStream()
if err != nil {
	// Handle error
}
defer client.DataStreamClose(key)
conn, err := client.AccountInfoWS(key)
if err != nil {
	// Handle error
}
defer conn.Close()
for {
	accountUpdate, orderUpdate, err := conn.Read()
	if err != nil {
		// Handle error
	}
	fmt.Printf("Account info update: %v %v", accountUpdate, orderUpdate)
}

License

This project is licensed under the MIT License. See the LICENSE file for more info.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountInfo

type AccountInfo 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"`
	Balances         []*Balance `json:"balances"`
}

type AccountInfoWS

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

AccountInfoWS is a wrapper for account info websocket

func (*AccountInfoWS) Close

func (w *AccountInfoWS) Close() error

func (*AccountInfoWS) Read

func (d *AccountInfoWS) Read() (*AccountUpdate, *OrderUpdate, error)

Read reads a account info update message from the account info websocket Remark: The websocket is used to update two different structs, which both are flat, hence every call to this function will return either one of the types initialized and the other one will be set to nil

type AccountUpdate

type AccountUpdate struct {
	EventType        UpdateType `json:"e"` // EventType represents the update type
	Time             uint64     `json:"E"` // Time represents the event time
	MakerCommission  int        `json:"m"` // MakerCommission is the maker commission for the account
	TakerCommission  int        `json:"t"` // TakerCommission is the taker commission for the account
	BuyerCommission  int        `json:"b"` // BuyerCommission is the buyer commission for the account
	SellerCommission int        `json:"s"` // SellerCommission is the seller commission for the account
	CanTrade         bool       `json:"T"`
	CanWithdraw      bool       `json:"W"`
	CanDeposit       bool       `json:"D"`
	Balances         []*struct {
		Asset  string `json:"a"`
		Free   string `json:"f"`
		Locked string `json:"l"`
	} `json:"B"`
}

AccountUpdate represents the incoming messages for account info websocket updates

type AggregatedTrade

type AggregatedTrade struct {
	TradeID      int    `json:"a"` // TradeID is the aggregate trade ID
	Price        string `json:"p"` // Price is the trade price
	Quantity     string `json:"q"` // Quantity is the trade quantity
	FirstTradeID int    `json:"f"`
	LastTradeID  int    `json:"l"`
	Time         uint64 `json:"T"`
	Maker        bool   `json:"m"` // Maker indicates if the buyer is the maker
	BestMatch    bool   `json:"M"` // BestMatch indicates if the trade was at the best price match
}

type AggregatedTradeOpts

type AggregatedTradeOpts struct {
	Symbol    string `url:"symbol"` // Symbol is the symbol to fetch data for
	FromID    int    `url:"fromId"` // Interval is the interval for each kline/candlestick
	Limit     int    `url:"limit"`  // Limit is the maximal number of elements to receive. Max 500
	StartTime uint64 `url:"startTime,omitempty"`
	EndTime   uint64 `url:"endTime,omitempty"`
}

type AllMarketTickerUpdate

type AllMarketTickerUpdate []IndivTickerUpdate

AllMarketTickerUpdate represents incoming ticker websocket feed for all tickers

type AllMarketTickerWS

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

AllMarketTickerWS is a wrapper for all market tickers websocket

func (*AllMarketTickerWS) Close

func (w *AllMarketTickerWS) Close() error

func (*AllMarketTickerWS) Read

Read reads a depth update message from the depth level websocket

type AllOrdersOpts

type AllOrdersOpts struct {
	Symbol  string `url:"symbol"`  // Symbol is the symbol to fetch orders for
	OrderID int    `url:"orderId"` // OrderID, if set, will filter all recent orders newer from the given ID
	Limit   int    `url:"limit"`   // Limit is the maximal number of elements to receive. Max 500
}

AllOrdersOpts represents the opts used for querying orders of the given symbol Remark: If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned

type AllPrices

type AllPrices struct {
	Prices []*SymbolPrice
}

type Balance

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

type BinanceClient

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

func NewBinanceClient

func NewBinanceClient(apikey, secret string) *BinanceClient

func NewBinanceClientWindow

func NewBinanceClientWindow(apikey, secret string, window int) (*BinanceClient, error)

func (*BinanceClient) Account

func (b *BinanceClient) Account() (*AccountInfo, error)

Account get current account information

func (*BinanceClient) AccountInfoWS

func (b *BinanceClient) AccountInfoWS(listenKey string) (*AccountInfoWS, error)

AccountInfoWS opens websocket with account info updates

func (*BinanceClient) AggregatedTrades

func (b *BinanceClient) AggregatedTrades(opts *AggregatedTradeOpts) ([]*AggregatedTrade, error)

AggregatedTrades gets compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated Remark: If both startTime and endTime are sent, limit should not be sent AND the distance between startTime and endTime must be less than 24 hours. Remark: If frondId, startTime, and endTime are not sent, the most recent aggregate trades will be returned.

func (*BinanceClient) AllBookTickers

func (b *BinanceClient) AllBookTickers() ([]*BookTicker, error)

AllBookTickers returns best price/qty on the order book for all symbols

func (*BinanceClient) AllMarketTickerWS

func (b *BinanceClient) AllMarketTickerWS() (*AllMarketTickerWS, error)

AllMarketTickerWS opens websocket with with single depth summary for all tickers

func (*BinanceClient) AllOrders

func (b *BinanceClient) AllOrders(opts *AllOrdersOpts) ([]*QueryOrder, error)

AllOrders get all account orders; active, canceled, or filled

func (*BinanceClient) CancelOrder

func (b *BinanceClient) CancelOrder(opts *CancelOrderOpts) (*CancelOrder, error)

CancelOrder cancel an active order

func (*BinanceClient) DataStream

func (b *BinanceClient) DataStream() (string, error)

Datastream starts a new user datastream

func (*BinanceClient) DataStreamClose

func (b *BinanceClient) DataStreamClose(listenKey string) error

DataStreamClose closes the datastream key

func (*BinanceClient) DataStreamKeepAlive

func (b *BinanceClient) DataStreamKeepAlive(listenKey string) error

DataStreamKeepAlive pings the datastream key to prevent timeout

func (*BinanceClient) Depth

func (b *BinanceClient) Depth(opts *DepthOpts) (*Depth, error)

Market Data endpoints Depth retrieves the order book for the given symbol

func (*BinanceClient) DepthLevelWS

func (b *BinanceClient) DepthLevelWS(symbol, level, frequency string) (*DepthLevelWS, error)

DepthLevelWS opens websocket with depth updates for the given symbol (eg @100ms frequency)

func (*BinanceClient) DepthWS

func (b *BinanceClient) DepthWS(symbol, frequency string) (*DepthWS, error)

DepthWS opens websocket with depth updates for the given symbol (eg @100ms frequency)

func (*BinanceClient) ExchangeInfo

func (b *BinanceClient) ExchangeInfo() (*ExchangeInfo, error)

func (*BinanceClient) IndivTickerWS

func (b *BinanceClient) IndivTickerWS(symbol string) (*IndivTickerWS, error)

IndivTickerWS opens websocket with with single depth summary for all tickers

func (*BinanceClient) Klines

func (b *BinanceClient) Klines(opts *KlinesOpts) ([]*Klines, error)

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

func (*BinanceClient) KlinesWS

func (b *BinanceClient) KlinesWS(symbol string, interval KlineInterval) (*KlinesWS, error)

KlinesWS opens websocket with klines updates for the given symbol with the given interval

func (*BinanceClient) NewOrder

func (b *BinanceClient) NewOrder(opts *NewOrderOpts) (*NewOrder, error)

NewOrder sends in a new order

func (*BinanceClient) NewOrderTest

func (b *BinanceClient) NewOrderTest(opts *NewOrderOpts) error

NewOrderTest tests new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine

func (*BinanceClient) OpenOrders

func (b *BinanceClient) OpenOrders(opts *OpenOrdersOpts) ([]*QueryOrder, error)

OpenOrders get all open orders on a symbol

func (*BinanceClient) Ping

func (b *BinanceClient) Ping() error

Ping tests connectivity to the Rest API

func (*BinanceClient) Prices

func (b *BinanceClient) Prices() ([]*SymbolPrice, error)

Prices calculates the latest price for all symbols

func (*BinanceClient) QueryOrder

func (b *BinanceClient) QueryOrder(opts *QueryOrderOpts) (*QueryOrder, error)

QueryOrder checks an order's status

func (*BinanceClient) Ticker

func (b *BinanceClient) Ticker(opts *TickerOpts) (*TickerStats, error)

Ticker returns 24 hour price change statistics

func (*BinanceClient) Time

func (b *BinanceClient) Time() (*ServerTime, error)

Time tests connectivity to the Rest API and get the current server time

func (*BinanceClient) Trades

func (b *BinanceClient) Trades(opts *TradesOpts) (*Trades, error)

Trades get trades for a specific account and symbol

func (*BinanceClient) TradesWS

func (b *BinanceClient) TradesWS(symbol string) (*TradesWS, error)

TradesWS opens websocket with trades updates for the given symbol

type BookTicker

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

type CancelOrder

type CancelOrder struct {
	Symbol            string `json:"symbol"`
	OrderID           int    `json:"orderId"`
	OrigClientOrderId string `json:"origClientOrderId"`
	ClientOrderId     string `json:"clientOrderId"`
}

type CancelOrderOpts

type CancelOrderOpts struct {
	Symbol            string `url:"symbol"`
	OrderID           int    `url:"orderId"`
	OrigClientOrderId string `url:"origClientOrderId,omitempty"`
	NewClientOrderId  string `url:"newClientOrderId,omitempty"`
}

Remark: Either OrderID or OrigOrderiD must be set

type Datastream

type Datastream struct {
	ListenKey string `json:"listenKey" url:"listenKey"`
}

type Depth

type Depth struct {
	LastUpdateID int         `json:"lastUpdateId"`
	Bids         []DepthElem `json:"bids"`
	Asks         []DepthElem `json:"asks"`
}

type DepthElem

type DepthElem struct {
	Quantity string `json:"quantity"`
	Price    string `json:"price"`
}

DepthElem represents a specific order in the order book

func (*DepthElem) UnmarshalJSON

func (b *DepthElem) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshal the given depth raw data and converts to depth struct

type DepthLevelUpdate

type DepthLevelUpdate struct {
	LastUpdateID uint64      `json:"lastUpdateId"` // EventType represents the update type
	Bids         []DepthElem `json:"bids"`         // Bids is a list of bids for symbol
	Asks         []DepthElem `json:"asks"`         // Asks is a list of asks for symbol
}

DepthLevelUpdate represents the incoming messages for depth level websocket updates

type DepthLevelWS

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

DepthLevelWS is a wrapper for depth level websocket

func (*DepthLevelWS) Close

func (w *DepthLevelWS) Close() error

func (*DepthLevelWS) Read

func (d *DepthLevelWS) Read() (*DepthLevelUpdate, error)

Read reads a depth update message from the depth level websocket

type DepthOpts

type DepthOpts struct {
	Symbol string `url:"symbol"` // Symbol is the symbol to fetch data for
	Limit  int    `url:"limit"`  // Limit is the number of order book items to retrieve. Max 100
}

DepthOpts are used to specify symbol to retrieve order book for

type DepthUpdate

type DepthUpdate struct {
	EventType UpdateType  `json:"e"` // EventType represents the update type
	Time      uint64      `json:"E"` // Time represents the event time
	Symbol    string      `json:"s"` // Symbol represents the symbol related to the update
	UpdateID  int         `json:"u"` // UpdateID to sync up with updateid in /api/v1/depth
	Bids      []DepthElem `json:"b"` // Bids is a list of bids for symbol
	Asks      []DepthElem `json:"a"` // Asks is a list of asks for symbol
}

DepthUpdate represents the incoming messages for depth websocket updates

type DepthWS

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

DepthWS is a wrapper for depth websocket

func (*DepthWS) Close

func (w *DepthWS) Close() error

func (*DepthWS) Read

func (d *DepthWS) Read() (*DepthUpdate, error)

Read reads a depth update message from the depth websocket

type ExchangeInfo

type ExchangeInfo struct {
	Symbols []SymbolInfo
}

type FilterType

type FilterType string
const (
	FilterTypePrice       FilterType = "PRICE_FILTER"
	FilterTypeLotSize     FilterType = "LOT_SIZE"
	FilterTypeMinNotional FilterType = "MIN_NOTIONAL"
)

type IndivTickerUpdate

type IndivTickerUpdate struct {
	EventType     UpdateType `json:"e"` // EventType represents the update type
	Time          uint64     `json:"E"` // Time represents the event time
	Symbol        string     `json:"s"` // Symbol represents the symbol related to the update
	Price         string     `json:"p"` // Price is the order price
	PricePercent  string     `json:"P"` // Price percent change
	WeightedPrice string     `json:"w"` // Weighted average price
	FirstTrade    string     `json:"x"` // First trade(F)-1 price (first trade before the 24hr rolling window)
	LastPrice     string     `json:"c"` // Last price
	LastQty       string     `json:"Q"` // Last quantity
	BestBidPrice  string     `json:"b"` // Best bid price
	BestBidQty    string     `json:"B"` // Best bid quantity
	BestAskPrice  string     `json:"a"` // Best ask price
	BestAskQty    string     `json:"A"` // Best ask quantity
	OpenPrice     string     `json:"o"` // Open price
	HighPrice     string     `json:"h"` // High price
	LowPrice      string     `json:"l"` // Low price
	VolumeBase    string     `json:"v"` // Total traded base asset volume
	VolumeQuote   string     `json:"q"` // Total traded quote asset volume
	StatisticOT   uint64     `json:"O"` // Statistics open time
	StatisticsCT  uint64     `json:"C"` // Statistics close time
	FirstTradeID  int        `json:"F"` // First trade ID
	LastTradeID   int        `json:"L"` // Last trade ID
	TotalTrades   int        `json:"n"` // Total number of trades
}

IndivTickerUpdate represents incoming ticker websocket feed

type IndivTickerWS

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

IndivTickerWS is a wrapper for an individual ticker websocket

func (*IndivTickerWS) Close

func (w *IndivTickerWS) Close() error

func (*IndivTickerWS) Read

func (d *IndivTickerWS) Read() (*IndivTickerUpdate, error)

Read reads a depth update message from the depth level websocket

type KlineInterval

type KlineInterval string
const (
	KlineInterval1m  KlineInterval = "1m"
	KlineInterval3m  KlineInterval = "3m"
	KlineInterval5m  KlineInterval = "5m"
	KlineInterval15m KlineInterval = "15m"
	KlineInterval30m KlineInterval = "30m"
	KlineInterval1h  KlineInterval = "1h"
	KlineInterval2h  KlineInterval = "2h"
	KlineInterval4h  KlineInterval = "4h"
	KlineInterval6h  KlineInterval = "6h"
	KlineInterval8h  KlineInterval = "8h"
	KlineInterval12h KlineInterval = "12h"
	KlineInterval1d  KlineInterval = "1d"
	KlineInterval3d  KlineInterval = "3d"
	KlineInterval1w  KlineInterval = "1w"
	KlineInterval1M  KlineInterval = "1M"
)

type Klines

type Klines struct {
	OpenTime                 uint64
	OpenPrice                string
	High                     string
	Low                      string
	ClosePrice               string
	Volume                   string
	CloseTime                uint64
	QuoteAssetVolume         string
	Trades                   int
	TakerBuyBaseAssetVolume  string
	TakerBuyQuoteAssetVolume string
}

func (*Klines) UnmarshalJSON

func (b *Klines) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshal the given depth raw data and converts to depth struct

type KlinesOpts

type KlinesOpts struct {
	Symbol    string        `url:"symbol"`   // Symbol is the symbol to fetch data for
	Interval  KlineInterval `url:"interval"` // Interval is the interval for each kline/candlestick
	Limit     int           `url:"limit"`    // Limit is the maximal number of elements to receive. Max 500
	StartTime uint64        `url:"startTime,omitempty"`
	EndTime   uint64        `url:"endTime,omitempty"`
}

type KlinesUpdate

type KlinesUpdate struct {
	EventType UpdateType `json:"e"` // EventType represents the update type
	Time      uint64     `json:"E"` // Time represents the event time
	Symbol    string     `json:"s"` // Symbol represents the symbol related to the update
	Kline     struct {
		StartTime    uint64        `json:"t"` // StartTime is the start time of this bar
		EndTime      uint64        `json:"T"` // EndTime is the end time of this bar
		Symbol       string        `json:"s"` // Symbol represents the symbol related to this kline
		Interval     KlineInterval `json:"i"` // Interval is the kline interval
		FirstTradeID int           `json:"f"` // FirstTradeID is the first trade ID
		LastTradeID  int           `json:"L"` // LastTradeID is the first trade ID

		OpenPrice            string `json:"o"` // OpenPrice represents the open price for this bar
		ClosePrice           string `json:"c"` // ClosePrice represents the close price for this bar
		High                 string `json:"h"` // High represents the highest price for this bar
		Low                  string `json:"l"` // Low represents the lowest price for this bar
		Volume               string `json:"v"` // Volume is the trades volume for this bar
		Trades               int    `json:"n"` // Trades is the number of conducted trades
		Final                bool   `json:"x"` // Final indicates whether this bar is final or yet may receive updates
		VolumeQuote          string `json:"q"` // VolumeQuote indicates the quote volume for the symbol
		VolumeActiveBuy      string `json:"V"` // VolumeActiveBuy represents the volume of active buy
		VolumeQuoteActiveBuy string `json:"Q"` // VolumeQuoteActiveBuy represents the quote volume of active buy
	} `json:"k"` // Kline is the kline update
}

KlinesUpdate represents the incoming messages for klines websocket updates

type KlinesWS

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

KlinesWS is a wrapper for klines websocket

func (*KlinesWS) Close

func (w *KlinesWS) Close() error

func (*KlinesWS) Read

func (d *KlinesWS) Read() (*KlinesUpdate, error)

Read reads a klines update message from the klines websocket

type NewOrder

type NewOrder struct {
	Symbol            string `json:"symbol"`
	OrderID           int    `json:"orderId"`
	OrigClientOrderID string `json:"origClientOrderId"`
	TransactTime      uint64 `json:"transactTime"`
}

type NewOrderOpts

type NewOrderOpts struct {
	Symbol           string      `url:"symbol"`
	Side             OrderSide   `url:"side"`
	Type             OrderType   `url:"type"`
	TimeInForce      TimeInForce `url:"timeInForce"`
	Quantity         string      `url:"quantity"`
	Price            string      `url:"price"`
	NewClientOrderId string      `url:"newClientOrderId,omitempty"`
	StopPrice        string      `url:"stopPrice,omitempty"`
	IcebergQty       string      `url:"icebergQty,omitempty"`
}

type OpenOrdersOpts

type OpenOrdersOpts struct {
	Symbol string `url:"symbol"`
}

type OrderFailure

type OrderFailure string
const (
	OrderFailureNone              OrderFailure = "NONE"
	OrderFailureUnknownInstrument OrderFailure = "UNKNOWN_INSTRUMENT"
	OrderFailureMarketClosed      OrderFailure = "MARKET_CLOSED"
	OrderFailurePriceExceed       OrderFailure = "PRICE_QTY_EXCEED_HARD_LIMITS"
	OrderFailureUnknownOrder      OrderFailure = "UNKNOWN_ORDER"
	OrderFailureDuplicate         OrderFailure = "DUPLICATE_ORDER"
	OrderFailureUnknownAccount    OrderFailure = "UNKNOWN_ACCOUNT"
	OrderFailureInsufficientFunds OrderFailure = "INSUFFICIENT_BALANCE"
	OrderFailureAccountInaactive  OrderFailure = "ACCOUNT_INACTIVE"
	OrderFailureAccountSettle     OrderFailure = "ACCOUNT_CANNOT_SETTLE"
)

type OrderSide

type OrderSide string
const (
	OrderSideBuy  OrderSide = "BUY"
	OrderSideSell OrderSide = "SELL"
)

type OrderStatus

type OrderStatus string
const (
	OrderStatusNew      OrderStatus = "NEW"
	OrderStatusPartial  OrderStatus = "PARTIALLY_FILLED"
	OrderStatusFilled   OrderStatus = "FILLED"
	OrderStatusCanceled OrderStatus = "CANCELED"
	OrderStatusPending  OrderStatus = "PENDING_CANCEL"
	OrderStatusRejected OrderStatus = "REJECTED"
	OrderStatusExpired  OrderStatus = "EXPIRED"
	OrderStatusReplaced OrderStatus = "REPLACED"
	OrderStatusTrade    OrderStatus = "TRADE"
)

type OrderType

type OrderType string

OrderType represents the order type

const (
	OrderTypeMarket          OrderType = "MARKET"
	OrderTypeLimit           OrderType = "LIMIT"
	OrderTypeStopLoss        OrderType = "STOP_LOSS"
	OrderTypeStopLossLimit   OrderType = "STOP_LOSS_LIMIT"
	OrderTypeTakeProfit      OrderType = "TAKE_PROFIT"
	OrderTypeTakeProfitLimit OrderType = "TAKE_PROFIT_LIMIT"
	OrderTypeLimitMaker      OrderType = "LIMIT_MAKER"
)

type OrderUpdate

type OrderUpdate struct {
	EventType        UpdateType   `json:"e"` // EventType represents the update type
	Time             uint64       `json:"E"` // Time represents the event time
	Symbol           string       `json:"s"` // Symbol represents the symbol related to the update
	NewClientOrderID string       `json:"c"` // NewClientOrderID is the new client order ID
	Side             OrderSide    `json:"S"` // Side is the order side
	OrderType        OrderType    `json:"o"` // OrderType represents the order type
	TimeInForce      TimeInForce  `json:"f"` // TimeInForce represents the order TIF type
	OrigQty          string       `json:"q"` // OrigQty represents the order original quantity
	Price            string       `json:"p"` // Price is the order price
	ExecutionType    OrderStatus  `json:"x"` // ExecutionType represents the execution type for the order
	Status           OrderStatus  `json:"X"` // Status represents the order status for the order
	Error            OrderFailure `json:"r"` // Error represents an order rejection reason
	OrderID          int          `json:"i"` // OrderID represents the order ID
	OrderTime        uint64       `json:"T"` // OrderTime represents the order time
	FilledQty        string       `json:"l"` // FilledQty represents the quantity of the last filled trade
	FilledPrice      string       `json:"L"` // FilledPrice is the price of last filled trade
	TotalFilledQty   string       `json:"z"` // TotalFilledQty is the accumulated quantity of filled trades on this order
	Commission       string       `json:"n"` // Commission is the commission for the trade
	CommissionAsset  string       `json:"N"` // CommissionAsset is the asset on which commission is taken
	TradeTime        uint64       `json:"T"` // TradeTime is the trade time
	TradeID          int          `json:"t"` // TradeID represents the trade ID
	Maker            bool         `json:"m"` // Maker represents whether buyer is maker or not
}

OrderUpdate represents the incoming messages for account orders websocket updates

type QueryOrder

type QueryOrder struct {
	Symbol        string      `json:"symbol"`
	OrderID       int         `json:"orderId"`
	ClientOrderID string      `json:"clientOrderId"`
	Price         string      `json:"price"`
	OrigQty       string      `json:"origQty"`
	ExecutedQty   string      `json:"executedQty"`
	Status        OrderStatus `json:"status"`
	TimeInForce   TimeInForce `json:"timeInForce"`
	Type          OrderType   `json:"type"`
	Side          OrderSide   `json:"side"`
	StopPrice     string      `json:"stopPrice"`
	IcebergQty    string      `json:"IcebergQty"`
	Time          int64       `json:"time"`
}

type QueryOrderOpts

type QueryOrderOpts struct {
	Symbol            string `url:"symbol"`
	OrderID           int    `url:"orderId,omitempty"`
	OrigClientOrderId string `url:"origClientOrderId,omitempty"`
}

QueryOrderOpts represents the opts for querying an order Remark: Either OrderID or OrigOrderiD must be set

type ServerTime

type ServerTime struct {
	ServerTime uint64 `json:"serverTime"`
}

type SymbolInfo

type SymbolInfo struct {
	Symbol              string             `json:"symbol"`
	Status              SymbolStatus       `json:"status"`
	BaseAsset           string             `json:"baseAsset"`
	BaseAssetPrecision  int                `json:"baseAssetPrecision"`
	QuoteAsset          string             `json:"quoteAsset"`
	QuoteAssetPrecision int                `json:"quoteAssetPrecision"`
	OrderTypes          []OrderType        `json:"orderTypes"`
	Iceberg             bool               `json:"icebergAllowed"`
	Filters             []SymbolInfoFilter `json:"filters"`
}

type SymbolInfoFilter

type SymbolInfoFilter struct {
	Type FilterType `json:"filterType"`

	// PRICE_FILTER paramters
	MinPrice string `json:"minPrice"`
	MaxPrice string `json:"maxPrice"`
	TickSize string `json:"tickSize"`

	// LOT_SIZE parameters
	MinQty   string `json:"minQty"`
	MaxQty   string `json:"maxQty"`
	StepSize string `json:"stepSize"`

	// MIN_NOTIONAL paramters
	MinNotional string `json:"minNotional"`
}

type SymbolPrice

type SymbolPrice struct {
	Symbol string
	Price  string
}

type SymbolStatus

type SymbolStatus string
const (
	SymbolStatusTrading SymbolStatus = "TRADING"
)

type TickerOpts

type TickerOpts struct {
	Symbol string `url:"symbol"`
}

TickerOpts represents the opts for a specified ticker

type TickerStats

type TickerStats struct {
	PriceChange           string `json:"priceChange"`
	PriceChangePercentage string `json:"priceChangePercent"`
	WeightedAvgPrice      string `json:"weightedAvgPrice"`
	PrevClosePrice        string `json:"prevClosePrice"`
	LastPrice             string `json:"lastPrice"`
	BidPrice              string `json:"bidPrice"`
	AskPrice              string `json:"askPrice"`
	OpenPrice             string `json:"openPrice"`
	HighPrice             string `json:"highPrice"` // HighPrice is 24hr high price
	LowPrice              string `json:"lowPrice"`  // LowPrice is 24hr low price
	Volume                string `json:"volume"`
	OpenTime              uint64 `json:"openTime"`
	CloseTime             uint64 `json:"closeTime"`
	FirstID               int    `json:"fristId"`
	LastID                int    `json:"lastId"`
	Count                 int    `json:"count"`
}

TickerStats is the stats for a specific symbol

type TimeInForce

type TimeInForce string
const (
	TimeInForceGTC TimeInForce = "GTC" // Good Till Cancel
	TimeInForceIOC TimeInForce = "IOC" // Immediate or Cancel
	TimeInForceFOK TimeInForce = "FOK" // Fill or Kill
)

type Trades

type Trades struct {
	ID              int    `json:"id"`
	Price           string `json:"price"`
	Qty             string `json:"qty"`
	Commission      string `json:"commission"`
	CommissionAsset string `json:"commissionAsset"`
	Time            uint64 `json:"time"`
	Buyer           bool   `json:"isBuyer"`
	Maker           bool   `json:"isMaker"`
	BestMatch       bool   `json:"isBestMatch"`
}

type TradesOpts

type TradesOpts struct {
	Symbol string `url:"symbol"`
	Limit  int    `url:"limit"`  // Limit is the maximal number of elements to receive. Max 500
	FromID int    `url:"fromId"` // FromID is trade ID to fetch from. Default gets most recent trades
}

type TradesUpdate

type TradesUpdate struct {
	EventType             UpdateType `json:"e"` // EventType represents the update type
	Time                  uint64     `json:"E"` // Time represents the event time
	Symbol                string     `json:"s"` // Symbol represents the symbol related to the update
	TradeID               int        `json:"a"` // TradeID is the aggregated trade ID
	Price                 string     `json:"p"` // Price is the trade price
	Quantity              string     `json:"q"` // Quantity is the trade quantity
	FirstBreakDownTradeID int        `json:"f"` // FirstBreakDownTradeID is the first breakdown trade ID
	LastBreakDownTradeID  int        `json:"l"` // LastBreakDownTradeID is the last breakdown trade ID
	TradeTime             uint64     `json:"T"` // Time is the trade time
	Maker                 bool       `json:"m"` // Maker indicates whether buyer is a maker
}

TradesUpdate represents the incoming messages for aggregated trades websocket updates

type TradesWS

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

TradesWS is a wrapper for trades websocket

func (*TradesWS) Close

func (w *TradesWS) Close() error

func (*TradesWS) Read

func (d *TradesWS) Read() (*TradesUpdate, error)

Read reads a trades update message from the trades websocket

type UpdateType

type UpdateType string
const (
	UpdateTypeDepth       UpdateType = "depthUpdate"
	UpdateTypeIndivTicker UpdateType = "24hrTicker"
	UpdateTypeKline       UpdateType = "kline"
	UpdateTypeTrades      UpdateType = "aggTrade"

	UpdateTypeOutboundAccountInfo UpdateType = "outboundAccountInfo"
	UpdateTypeExecutionReport     UpdateType = "executionReport"
)

Jump to

Keyboard shortcuts

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