binance

package module
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2022 License: MIT Imports: 20 Imported by: 3

README

Golang Binance API

PkgGoDev Go Report Card Build Status codecov

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

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

Quickstart

package main

import (
    "log"

    "github.com/xenking/binance-api"
)

func main() {
    client := binance.NewClient("API-KEY", "SECRET")

    err := client.Ping()
    if err != nil {
        panic(err)
    }

    prices, err := client.Prices()
    if err != nil {
        panic(err)
    }

    for _, p := range prices {
        log.Printf("symbol: %s, price: %s", p.Symbol, p.Price)
    }
}

Installation

go get -u github.com/xenking/binance-api

Getting started

// Create default client
client := binance.NewClient("API-KEY", "SECRET")

// Send ping request
err := client.Ping()

// Create client with custom request window size
client := binance.NewClient("API-KEY", "SECRET").ReqWindow(5000)

// Create websocket client
wsClient := ws.NewClient()

// Connect to Klines websocket
ws, err := wsClient.Klines("ETHBTC", binance.KlineInterval1m)

// Read ws
msg, err := ws.Read()

Full documentation on pkg.go.dev

License

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

Documentation

Index

Constants

View Source
const (
	// BaseHostPort for binance addresses
	BaseHostPort     = "api.binance.com:443"
	BaseHost         = "api.binance.com"
	DefaultUserAgent = "Binance/client"
)
View Source
const (
	DefaultSchema  = "https"
	HeaderTypeJSON = "application/json"
	HeaderTypeForm = "application/x-www-form-urlencoded"
	HeaderAccept   = "Accept"
	HeaderAPIKey   = "X-MBX-APIKEY" //nolint:gosec
)
View Source
const (
	EndpointPing               = "/api/v3/ping"
	EndpointTime               = "/api/v3/time"
	EndpointExchangeInfo       = "/api/v3/exchangeInfo"
	EndpointDepth              = "/api/v3/depth"
	EndpointTrades             = "/api/v3/trades"
	EndpointHistoricalTrades   = "/api/v3/historicalTrades"
	EndpointAggTrades          = "/api/v3/aggTrades"
	EndpointKlines             = "/api/v3/klines"
	EndpointAvgPrice           = "/api/v3/avgPrice"
	EndpointTicker24h          = "/api/v3/ticker/24hr"
	EndpointTickerPrice        = "/api/v3/ticker/price"
	EndpointTickerBook         = "/api/v3/ticker/bookTicker"
	EndpointOrder              = "/api/v3/order"
	EndpointOrderTest          = "/api/v3/order/test"
	EndpointOpenOrders         = "/api/v3/openOrders"
	EndpointCancelReplaceOrder = "/api/v3/order/cancelReplace"
	EndpointOrdersAll          = "/api/v3/allOrders"
	EndpointAccount            = "/api/v3/account"
	EndpointAccountTrades      = "/api/v3/myTrades"
	EndpointRateLimit          = "/api/v3/rateLimit/order"
	EndpointDataStream         = "/api/v3/userDataStream"
)
View Source
const (
	OrderRespTypeAsk    = "ASK"
	OrderRespTypeResult = "RESULT"
	OrderRespTypeFull   = "FULL"
)
View Source
const (
	DefaultDepthLimit = 100
	MaxDepthLimit     = 5000
)
View Source
const (
	DefaultTradesLimit = 500
	MaxTradesLimit     = 1000
)
View Source
const (
	DefaultKlinesLimit = 500
	MaxKlinesLimit     = 1000
)
View Source
const (
	DefaultOrderLimit = 500
	MaxOrderLimit     = 1000
)
View Source
const DefaultResponseWindow = 5000
View Source
const MaxAccountTradesLimit = 500
View Source
const MinStrategyType = 1000000

Variables

View Source
var (
	HeaderUsedWeight = []byte("X-Mbx-Used-Weight-")
	HeaderOrderCount = []byte("X-Mbx-Order-Count-")
	HeaderRetryAfter = []byte("Retry-After")
)
View Source
var (
	ErrNilRequest      = errors.New("request is nil")
	ErrEmptySymbol     = errors.New("symbol are missing")
	ErrEmptyOrderID    = errors.New("order id must be set")
	ErrEmptyLimit      = errors.New("empty price or quantity")
	ErrMinStrategyType = errors.New("minimal strategy type can't be lower than 1000000")
	ErrEmptyMarket     = errors.New("quantity or quote quantity expected")
	ErrNilUnmarshal    = errors.New("UnmarshalJSON on nil pointer")
	ErrInvalidJSON     = errors.New("invalid json")
)

Functions

This section is empty.

Types

type APIError

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

func (*APIError) Error

func (e *APIError) Error() string

Error return error code and message

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"`
	AccountType      AccountType
	Balances         []*Balance    `json:"balances"`
	Permissions      []AccountType `json:"permissions"`
}

type AccountTrades

type AccountTrades struct {
	ID              int64  `json:"id"`
	OrderID         uint64 `json:"orderId"`
	OrderListID     int64  `json:"orderListId"`
	Symbol          string `json:"symbol"`
	QuoteQty        string `json:"quoteQty"`
	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 AccountTradesReq

type AccountTradesReq struct {
	Symbol    string `url:"symbol"`
	OrderID   string `url:"orderId,omitempty"` // OrderID can only be used in combination with symbol
	Limit     int    `url:"limit,omitempty"`   // Limit is the maximal number of elements to receive. Default 500; Max 1000
	FromID    int    `url:"fromId,omitempty"`  // FromID is trade ID to fetch from. Default gets most recent trades
	StartTime uint64 `url:"startTime,omitempty"`
	EndTime   uint64 `url:"endTime,omitempty"`
}

type AccountType added in v1.2.0

type AccountType string
const (
	AccountTypeSpot      AccountType = "SPOT"
	AccountTypeMargin    AccountType = "MARGIN"
	AccountTypeLeveraged AccountType = "LEVERAGED"
	AccountTypeGRP2      AccountType = "TRD_GRP_002"
	AccountTypeGRP3      AccountType = "TRD_GRP_003"
	AccountTypeGRP4      AccountType = "TRD_GRP_004"
	AccountTypeGRP5      AccountType = "TRD_GRP_005"
)

type AggregatedTrade

type AggregatedTrade struct {
	TradeID      int64  `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 AggregatedTradeReq

type AggregatedTradeReq struct {
	Symbol    string `url:"symbol"`              // Symbol is the symbol to fetch data for
	FromID    int    `url:"fromId"`              // FromID to get aggregate trades from INCLUSIVE.
	Limit     int    `url:"limit"`               // Limit is the maximal number of elements to receive. Default 500; Max 1000
	StartTime uint64 `url:"startTime,omitempty"` // StartTime timestamp in ms to get aggregate trades from INCLUSIVE.
	EndTime   uint64 `url:"endTime,omitempty"`   // EndTime timestamp in ms to get aggregate trades until INCLUSIVE.
}

type AllOrdersReq

type AllOrdersReq struct {
	Symbol    string `url:"symbol"`            // Symbol is the symbol to fetch orders for
	OrderID   uint64 `url:"orderId,omitempty"` // OrderID, if set, will filter all recent orders newer from the given ID
	Limit     int    `url:"limit,omitempty"`   // Limit is the maximal number of elements to receive. Default 500; Max 1000
	StartTime uint64 `url:"startTime,omitempty"`
	EndTime   uint64 `url:"endTime,omitempty"`
}

AllOrdersReq represents the request 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 AvgPrice

type AvgPrice struct {
	Mins  int    `json:"mins"`
	Price string `json:"price"`
}

type AvgPriceReq

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

type Balance

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

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 BookTickerReq

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

type CancelOpenOrdersReq

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

type CancelOrder

type CancelOrder struct {
	Symbol              string      `json:"symbol"`
	OrigClientOrderID   string      `json:"origClientOrderId"`
	OrderID             uint64      `json:"orderId"`
	OrderListID         int64       `json:"orderListId"`
	ClientOrderID       string      `json:"clientOrderId"`
	Price               string      `json:"price"`
	OrigQty             string      `json:"origQty"`
	ExecutedQty         string      `json:"executedQty"`
	CummulativeQuoteQty string      `json:"cummulativeQuoteQty"`
	Status              OrderStatus `json:"status"`
	TimeInForce         TimeInForce `json:"timeInForce"`
	Type                OrderType   `json:"type"`
	Side                OrderSide   `json:"side"`
	StrategyID          int         `json:"strategyId,omitempty"`
	StrategyType        int         `json:"strategyType,omitempty"`
}

type CancelOrderReq

type CancelOrderReq struct {
	Symbol            string `url:"symbol"`
	OrderID           uint64 `url:"orderId,omitempty"`
	OrigClientOrderID string `url:"origClientOrderId,omitempty"`
	NewClientOrderID  string `url:"newClientOrderId,omitempty"`
}

Remark: Either OrderID or OrigOrderID must be set

type CancelReplaceMode added in v1.7.0

type CancelReplaceMode string
const (
	CancelReplaceModeStopOnFailure CancelReplaceMode = "STOP_ON_FAILURE"
	CancelReplaceModeAllowFailure  CancelReplaceMode = "ALLOW_FAILURE"
)

type CancelReplaceOrder added in v1.7.0

type CancelReplaceOrder struct {
	CancelResponse   CancelOrder         `json:"cancelResponse"`
	NewOrderResponse *OrderRespFull      `json:"newOrderResponse,omitempty"`
	CancelStatus     CancelReplaceResult `json:"cancelResult"`
	NewOrderResult   CancelReplaceResult `json:"newOrderResult"`
}

type CancelReplaceOrderReq added in v1.7.0

type CancelReplaceOrderReq struct {
	OrderReq
	CancelReplaceMode       CancelReplaceMode `url:"cancelReplaceMode"`
	CancelOrderID           uint64            `url:"cancelOrderId,omitempty"`
	CancelOrigClientOrderID string            `url:"cancelOrigClientOrderId,omitempty"`
	CancelNewClientOrderID  string            `url:"cancelNewClientOrderId,omitempty"`
}

Note: Either CancelOrderID or CancelOrigClientOrderID must be set

type CancelReplaceResult added in v1.7.0

type CancelReplaceResult string
const (
	CancelReplaceResultSuccess      CancelReplaceResult = "SUCCESS"
	CancelReplaceResultFailure      CancelReplaceResult = "FAILURE"
	CancelReplaceResultNotAttempted CancelReplaceResult = "NOT_ATTEMPTED"
)

type Client

type Client struct {
	RestClient
}

func NewClient

func NewClient(apikey, secret string) *Client

NewClient creates a new binance client with key and secret

func NewClientHTTP2 added in v1.3.1

func NewClientHTTP2(apikey, secret string) (*Client, error)

NewClientHTTP2 creates a new binance client using HTTP/2 protocol with key and secret

func NewCustomClient added in v1.2.0

func NewCustomClient(restClient RestClient) *Client

func (*Client) Account

func (c *Client) Account() (*AccountInfo, error)

Account get current account information

func (*Client) AccountTrades

func (c *Client) AccountTrades(req *AccountTradesReq) (*AccountTrades, error)

AccountTrades get trades for a specific account and symbol

func (*Client) AggregatedTrades

func (c *Client) AggregatedTrades(req *AggregatedTradeReq) ([]*AggregatedTrade, error)

AggregatedTrades gets compressed, aggregate trades. AccountTrades 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 (*Client) AllOrders

func (c *Client) AllOrders(req *AllOrdersReq) ([]*QueryOrder, error)

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

func (*Client) AvgPrice

func (c *Client) AvgPrice(req *AvgPriceReq) (*AvgPrice, error)

AvgPrice returns 24 hour price change statistics

func (*Client) BookTicker

func (c *Client) BookTicker(req *BookTickerReq) (*BookTicker, error)

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

func (*Client) BookTickers

func (c *Client) BookTickers() ([]*BookTicker, error)

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

func (*Client) CancelOpenOrders

func (c *Client) CancelOpenOrders(req *CancelOpenOrdersReq) ([]*CancelOrder, error)

CancelOpenOrders cancel all open orders on a symbol

func (*Client) CancelOrder

func (c *Client) CancelOrder(req *CancelOrderReq) (*CancelOrder, error)

CancelOrder cancel an active order

func (*Client) CancelReplaceOrder added in v1.7.0

func (c *Client) CancelReplaceOrder(req *CancelReplaceOrderReq) (*CancelReplaceOrder, error)

CancelReplaceOrder cancels an existing order and places a new order on the same symbol

func (*Client) DataStream

func (c *Client) DataStream() (string, error)

DataStream starts a new user datastream

func (*Client) DataStreamClose

func (c *Client) DataStreamClose(listenKey string) error

DataStreamClose closes the datastream key

func (*Client) DataStreamKeepAlive

func (c *Client) DataStreamKeepAlive(listenKey string) error

DataStreamKeepAlive pings the datastream key to prevent timeout

func (*Client) Depth

func (c *Client) Depth(req *DepthReq) (*Depth, error)

Depth retrieves the order book for the given symbol

func (*Client) ExchangeInfo

func (c *Client) ExchangeInfo() (*ExchangeInfo, error)

ExchangeInfo get current exchange trading rules and symbols information

func (*Client) ExchangeInfoSymbol added in v1.2.0

func (c *Client) ExchangeInfoSymbol(req *ExchangeInfoReq) (*ExchangeInfo, error)

ExchangeInfoSymbol get current exchange trading rules and symbol information for a specific symbol

func (*Client) HistoricalTrades added in v1.2.0

func (c *Client) HistoricalTrades(req *HistoricalTradeReq) ([]*Trade, error)

HistoricalTrades get for a specific symbol started from order id

func (*Client) Klines

func (c *Client) Klines(req *KlinesReq) ([]*Klines, error)

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

func (*Client) NewOrder

func (c *Client) NewOrder(req *OrderReq) (*OrderRespAck, error)

NewOrder sends in a new order

func (*Client) NewOrderFull added in v1.1.0

func (c *Client) NewOrderFull(req *OrderReq) (*OrderRespFull, error)

NewOrderFull sends in a new order and return created full order info

func (*Client) NewOrderResult added in v1.1.0

func (c *Client) NewOrderResult(req *OrderReq) (*OrderRespResult, error)

NewOrderResult sends in a new order and return created order

func (*Client) NewOrderTest

func (c *Client) NewOrderTest(req *OrderReq) 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 (*Client) OpenOrders

func (c *Client) OpenOrders(req *OpenOrdersReq) ([]*QueryOrder, error)

OpenOrders get all open orders on a symbol

func (*Client) OrderRateLimit added in v1.8.3

func (c *Client) OrderRateLimit() ([]RateLimit, error)

OrderRateLimit get the user's current order count usage for all intervals.

func (*Client) Ping

func (c *Client) Ping() error

Ping tests connectivity to the Rest API

func (*Client) Price

func (c *Client) Price(req *TickerPriceReq) (*SymbolPrice, error)

Price calculates the latest price for a symbol

func (*Client) Prices

func (c *Client) Prices() ([]*SymbolPrice, error)

Prices calculates the latest price for all symbols

func (*Client) QueryOrder

func (c *Client) QueryOrder(req *QueryOrderReq) (*QueryOrder, error)

QueryOrder checks an order's status

func (*Client) ReqWindow

func (c *Client) ReqWindow(window int) *Client

func (*Client) Ticker

func (c *Client) Ticker(req *TickerReq) (*TickerStats, error)

Ticker returns 24 hour price change statistics

func (*Client) Tickers

func (c *Client) Tickers() ([]*TickerStats, error)

Tickers returns 24 hour price change statistics

func (*Client) Time

func (c *Client) Time() (*ServerTime, error)

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

func (*Client) Trades

func (c *Client) Trades(req *TradeReq) ([]*Trade, error)

Trades get for a specific account and symbol

type DatastreamReq

type DatastreamReq 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 decimal.Decimal `json:"quantity"`
	Price    decimal.Decimal `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 DepthReq

type DepthReq 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. Default 100; Max 5000
}

DepthReq are used to specify symbol to retrieve order book for

type ExchangeFilter added in v1.2.0

type ExchangeFilter struct {
	Type ExchangeFilterType `json:"filterType"`

	// EXCHANGE_MAX_NUM_ORDERS parameters
	MaxNumOrders int `json:"maxNumOrders"`

	// EXCHANGE_MAX_ALGO_ORDERS parameters
	MaxNumAlgoOrders int `json:"maxNumAlgoOrders"`
}

type ExchangeFilterType added in v1.2.0

type ExchangeFilterType string
const (
	ExchangeFilterTypeMaxNumOrders  ExchangeFilterType = "EXCHANGE_MAX_NUM_ORDERS"
	ExchangeFilterTypeMaxAlgoOrders ExchangeFilterType = "EXCHANGE_MAX_ALGO_ORDERS"
)

type ExchangeInfo

type ExchangeInfo struct {
	Timezone        string           `json:"timezone"`
	ServerTime      uint64           `json:"serverTime"`
	RateLimits      []RateLimit      `json:"rateLimits"`
	ExchangeFilters []ExchangeFilter `json:"exchangeFilters"`
	Symbols         []SymbolInfo     `json:"symbols"`
}

type ExchangeInfoReq added in v1.2.0

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

type FilterType

type FilterType string
const (
	FilterTypePrice               FilterType = "PRICE_FILTER"
	FilterTypePercentPrice        FilterType = "PERCENT_PRICE"
	FilterTypeLotSize             FilterType = "LOT_SIZE"
	FilterTypeMinNotional         FilterType = "MIN_NOTIONAL"
	FilterTypeIcebergParts        FilterType = "ICEBERG_PARTS"
	FilterTypeMarketLotSize       FilterType = "MARKET_LOT_SIZE"
	FilterTypeMaxNumOrders        FilterType = "MAX_NUM_ORDERS"
	FilterTypeMaxNumAlgoOrders    FilterType = "MAX_NUM_ALGO_ORDERS"
	FilterTypeMaxNumIcebergOrders FilterType = "MAX_NUM_ICEBERG_ORDERS"
	FilterTypeMaxPosition         FilterType = "MAX_POSITION"
)

type HistoricalTradeReq added in v1.2.0

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

HistoricalTradeReq are used to specify symbol to get older trades

type KlineInterval

type KlineInterval string
const (
	KlineInterval1sec   KlineInterval = "1s"
	KlineInterval1min   KlineInterval = "1m"
	KlineInterval3min   KlineInterval = "3m"
	KlineInterval5min   KlineInterval = "5m"
	KlineInterval15min  KlineInterval = "15m"
	KlineInterval30min  KlineInterval = "30m"
	KlineInterval1hour  KlineInterval = "1h"
	KlineInterval2hour  KlineInterval = "2h"
	KlineInterval4hour  KlineInterval = "4h"
	KlineInterval6hour  KlineInterval = "6h"
	KlineInterval8hour  KlineInterval = "8h"
	KlineInterval12hour KlineInterval = "12h"
	KlineInterval1day   KlineInterval = "1d"
	KlineInterval3day   KlineInterval = "3d"
	KlineInterval1week  KlineInterval = "1w"
	KlineInterval1month KlineInterval = "1M"
)

type Klines

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

func (*Klines) UnmarshalJSON

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

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

type KlinesReq

type KlinesReq 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. Default 500; Max 1000
	StartTime uint64        `url:"startTime,omitempty"`
	EndTime   uint64        `url:"endTime,omitempty"`
}

type OpenOrdersReq

type OpenOrdersReq 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 OrderReq

type OrderReq struct {
	Symbol           string        `url:"symbol"`
	Side             OrderSide     `url:"side"`
	Type             OrderType     `url:"type"`
	TimeInForce      TimeInForce   `url:"timeInForce,omitempty"`
	Quantity         string        `url:"quantity,omitempty"`
	QuoteQuantity    string        `url:"quoteOrderQty,omitempty"`
	Price            string        `url:"price,omitempty"`
	NewClientOrderID string        `url:"newClientOrderId,omitempty"`
	StrategyID       int           `url:"strategyId,omitempty"`
	StrategyType     int           `url:"strategyType,omitempty"` // Should be more than 1000000
	StopPrice        string        `url:"stopPrice,omitempty"`
	TrailingDelta    int64         `url:"trailingDelta,omitempty"` // Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.
	IcebergQty       string        `url:"icebergQty,omitempty"`
	OrderRespType    OrderRespType `url:"newOrderRespType,omitempty"`
}

type OrderRespAck

type OrderRespAck struct {
	Symbol        string `json:"symbol"`
	OrderID       uint64 `json:"orderId"`
	OrderListID   int64  `json:"orderListId"`
	ClientOrderID string `json:"clientOrderId"`
	TransactTime  uint64 `json:"transactTime"`
}

type OrderRespFull

type OrderRespFull struct {
	Symbol              string              `json:"symbol"`
	OrderID             uint64              `json:"orderId"`
	OrderListID         int64               `json:"orderListId"`
	ClientOrderID       string              `json:"clientOrderId"`
	TransactTime        uint64              `json:"transactTime"`
	Price               string              `json:"price"`
	OrigQty             string              `json:"origQty"`
	ExecutedQty         string              `json:"executedQty"`
	CummulativeQuoteQty string              `json:"cummulativeQuoteQty"`
	Status              OrderStatus         `json:"status"`
	TimeInForce         string              `json:"timeInForce"`
	Type                OrderType           `json:"type"`
	Side                OrderSide           `json:"side"`
	StrategyID          int                 `json:"strategyId,omitempty"`
	StrategyType        int                 `json:"strategyType,omitempty"`
	Fills               []OrderRespFullFill `json:"fills"`
}

type OrderRespFullFill

type OrderRespFullFill struct {
	Price           string `json:"price"`
	Qty             string `json:"qty"`
	Commission      string `json:"commission"`
	CommissionAsset string `json:"commissionAsset"`
}

type OrderRespResult

type OrderRespResult struct {
	Symbol              string      `json:"symbol"`
	OrderID             uint64      `json:"orderId"`
	OrderListID         int         `json:"orderListId"`
	ClientOrderID       string      `json:"clientOrderId"`
	TransactTime        uint64      `json:"transactTime"`
	Price               string      `json:"price"`
	OrigQty             string      `json:"origQty"`
	ExecutedQty         string      `json:"executedQty"`
	CummulativeQuoteQty string      `json:"cummulativeQuoteQty"`
	Status              OrderStatus `json:"status"`
	TimeInForce         string      `json:"timeInForce"`
	Type                OrderType   `json:"type"`
	Side                OrderSide   `json:"side"`
	StrategyID          int         `json:"strategyId,omitempty"`
	StrategyType        int         `json:"strategyType,omitempty"`
}

type OrderRespType

type OrderRespType string

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"
)

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 QueryOrder

type QueryOrder struct {
	Symbol              string      `json:"symbol"`
	OrderID             uint64      `json:"orderId"`
	OrderListID         int64       `json:"orderListId"`
	ClientOrderID       string      `json:"clientOrderId"`
	Price               string      `json:"price"`
	OrigQty             string      `json:"origQty"`
	ExecutedQty         string      `json:"executedQty"`
	CummulativeQuoteQty string      `json:"cummulativeQuoteQty"`
	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                uint64      `json:"time"`
	UpdateTime          uint64      `json:"updateTime"`
	OrigQuoteOrderQty   string      `json:"origQuoteOrderQty"`
	StrategyID          int         `json:"strategyId,omitempty"`
	StrategyType        int         `json:"strategyType,omitempty"`
}

type QueryOrderReq

type QueryOrderReq struct {
	Symbol            string `url:"symbol"`
	OrderID           uint64 `url:"orderId,omitempty"`
	OrigClientOrderID string `url:"origClientOrderId,omitempty"`
}

QueryOrderReq represents the request for querying an order Remark: Either OrderID or OrigOrderiD must be set

type RateLimit added in v1.2.0

type RateLimit struct {
	Type        RateLimitType     `json:"rateLimitType"`
	Interval    RateLimitInterval `json:"interval"`
	IntervalNum int               `json:"intervalNum"`
	Limit       int               `json:"limit"`
	Count       int               `json:"count,omitempty"`
}

type RateLimitInterval added in v1.2.0

type RateLimitInterval string
const (
	RateLimitIntervalSecond RateLimitInterval = "SECOND"
	RateLimitIntervalHour   RateLimitInterval = "HOUR"
	RateLimitIntervalMinute RateLimitInterval = "MINUTE"
	RateLimitIntervalDay    RateLimitInterval = "DAY"
)

type RateLimitType added in v1.2.0

type RateLimitType string
const (
	RateLimitTypeRequestWeight RateLimitType = "REQUEST_WEIGHT"
	RateLimitTypeOrders        RateLimitType = "ORDERS"
	RateLimitTypeRawRequests   RateLimitType = "RAW_REQUESTS"
)

type RestClient added in v1.2.0

type RestClient interface {
	Do(method, endpoint string, data interface{}, sign bool, stream bool) ([]byte, error)

	SetWindow(window int)
	UsedWeight() map[string]int64
	OrderCount() map[string]int64
	RetryAfter() int64
}

func NewCustomRestClient added in v1.2.0

func NewCustomRestClient(config RestClientConfig) RestClient

func NewRestClient added in v1.2.0

func NewRestClient(key, secret string) RestClient

func NewRestClientHTTP2 added in v1.3.1

func NewRestClientHTTP2(key, secret string) (RestClient, error)

type RestClientConfig added in v1.2.0

type RestClientConfig struct {
	APIKey         string
	APISecret      string
	HTTPClient     *fasthttp.HostClient
	ResponseWindow int
}

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"`
	QuotePrecision             int                `json:"quotePrecision"`
	QuoteAssetPrecision        int                `json:"quoteAssetPrecision"`
	BaseCommissionPrecision    int                `json:"baseCommissionPrecision"`
	QuoteCommissionPrecision   int                `json:"quoteCommissionPrecision"`
	OrderTypes                 []OrderType        `json:"orderTypes"`
	IcebergAllowed             bool               `json:"icebergAllowed"`
	OCOAllowed                 bool               `json:"ocoAllowed"`
	QuoteOrderQtyMarketAllowed bool               `json:"quoteOrderQtyMarketAllowed"`
	AllowTrailingStop          bool               `json:"allowTrailingStop"`
	IsSpotTradingAllowed       bool               `json:"isSpotTradingAllowed"`
	IsMarginTradingAllowed     bool               `json:"isMarginTradingAllowed"`
	CancelReplaceAllowed       bool               `json:"cancelReplaceAllowed"`
	Filters                    []SymbolInfoFilter `json:"filters"`
	Permissions                []AccountType      `json:"permissions"`
}

type SymbolInfoFilter

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

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

	// PERCENT_PRICE parameters
	MultiplierUp   string `json:"multiplierUp"`
	MultiplierDown string `json:"multiplierDown"`
	AvgPriceMins   int    `json:"avgPriceMins"`

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

	// MIN_NOTIONAL parameter
	MinNotional   string `json:"minNotional"`
	ApplyToMarket bool   `json:"applyToMarket"`

	// ICEBERG_PARTS parameter
	IcebergLimit int `json:"limit"`

	// TRAILING_DELTA parameter
	MinTrailingAboveDelta int `json:"minTrailingAboveDelta"`
	MaxTrailingAboveDelta int `json:"maxTrailingAboveDelta"`
	MinTrailingBelowDelta int `json:"minTrailingBelowDelta"`
	MaxTrailingBelowDelta int `json:"maxTrailingBelowDelta"`

	// MAX_NUM_ORDERS parameter
	MaxNumOrders int `json:"maxNumOrders"`

	// MAX_NUM_ALGO_ORDERS parameter
	MaxNumAlgoOrders int `json:"maxNumAlgoOrders"`

	// MAX_NUM_ICEBERG_ORDERS parameter
	MaxNumIcebergOrders int `json:"maxNumIcebergOrders"`

	// MAX_POSITION parameter
	MaxPosition string `json:"maxPosition"`
}

type SymbolPrice

type SymbolPrice struct {
	Symbol string
	Price  string
}

type SymbolStatus

type SymbolStatus string
const (
	SymbolStatusPreTrading   SymbolStatus = "PRE_TRADING"
	SymbolStatusTrading      SymbolStatus = "TRADING"
	SymbolStatusPostTrading  SymbolStatus = "POST_TRADING"
	SymbolStatusEndOfDay     SymbolStatus = "END_OF_DAY"
	SymbolStatusHalt         SymbolStatus = "HALT"
	SymbolStatusAuctionMatch SymbolStatus = "AUCTION_MATCH"
	SymbolStatusBreak        SymbolStatus = "BREAK"
)

type TickerPriceReq

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

type TickerReq

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

TickerReq represents the request for a specified ticker

type TickerStats

type TickerStats struct {
	Symbol             string `json:"symbol"`
	PriceChange        string `json:"priceChange"`
	PriceChangePercent string `json:"priceChangePercent"`
	WeightedAvgPrice   string `json:"weightedAvgPrice"`
	PrevClosePrice     string `json:"prevClosePrice"`
	LastPrice          string `json:"lastPrice"`
	LastQty            string `json:"lastQty"`
	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"`
	QuoteVolume        string `json:"quoteVolume"`
	OpenTime           uint64 `json:"openTime"`
	CloseTime          uint64 `json:"closeTime"`
	FirstID            int    `json:"firstId"`
	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 Trade

type Trade struct {
	ID           int64  `json:"id"`
	Price        string `json:"price"`
	Qty          string `json:"qty"`
	QuoteQty     string `json:"quoteQty"`
	Time         int64  `json:"time"`
	IsBuyerMaker bool   `json:"isBuyerMaker"`
	IsBestMatch  bool   `json:"isBestMatch"`
}

type TradeReq

type TradeReq struct {
	Symbol string `url:"symbol"` // Symbol is the symbol to fetch data for
	Limit  int    `url:"limit"`  // Limit is the maximal number of elements to receive. Default 500; Max 1000
}

TradeReq are used to specify symbol to get recent trades

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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