binance

package
v1.22.3 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2021 License: MIT Imports: 24 Imported by: 10

Documentation

Index

Constants

View Source
const BNB = "BNB"
View Source
const BinanceFuturesWebSocketURL = "wss://fstream.binance.com"
View Source
const BinanceUSBaseURL = "https://api.binance.us"
View Source
const BinanceUSWebSocketURL = "wss://stream.binance.us:9443"
View Source
const BinanceWebSocketURL = "wss://stream.binance.com:9443"

Variables

This section is empty.

Functions

func ConvertTrades added in v1.2.0

func ConvertTrades(remoteTrades []*binance.TradeV3) (trades []types.Trade, err error)

ConvertTrades converts the binance v3 trade into the global trade type

func IsBookTicker added in v1.21.0

func IsBookTicker(val *fastjson.Value) bool

IsBookTicker document ref :https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-book-ticker-streams use key recognition because there's no identify in the content.

func ParseEvent

func ParseEvent(message string) (interface{}, error)

Types

type AccountConfig added in v1.21.1

type AccountConfig struct {
	Symbol   string           `json:"s"`
	Leverage fixedpoint.Value `json:"l"`
}

type AccountConfigUpdateEvent added in v1.21.1

type AccountConfigUpdateEvent struct {
	EventBase
	Transaction int64 `json:"T"`

	AccountConfig AccountConfig `json:"ac"`
}

type AccountUpdate added in v1.21.1

type AccountUpdate struct {
	EventReasonType string                     `json:"m"`
	Balances        []*futures.Balance         `json:"B,omitempty"`
	Positions       []*futures.AccountPosition `json:"P,omitempty"`
}

type AccountUpdateEvent added in v1.21.1

type AccountUpdateEvent struct {
	EventBase
	Transaction int64 `json:"T"`

	AccountUpdate AccountUpdate `json:"a"`
}

type Balance

type Balance struct {
	Asset  string           `json:"a"`
	Free   fixedpoint.Value `json:"f"`
	Locked fixedpoint.Value `json:"l"`
}

outboundAccountInfo

{
  "e": "outboundAccountInfo",   // KLineEvent type
  "E": 1499405658849,           // KLineEvent time
  "m": 0,                       // Maker commission rate (bips)
  "t": 0,                       // Taker commission rate (bips)
  "b": 0,                       // Buyer commission rate (bips)
  "s": 0,                       // Seller commission rate (bips)
  "T": true,                    // Can trade?
  "W": true,                    // Can withdraw?
  "D": true,                    // Can deposit?
  "u": 1499405658848,           // Time of last account update
  "B": [                        // AccountBalances array
    {
      "a": "LTC",               // Asset
      "f": "17366.18538083",    // Free amount
      "l": "0.00000000"         // Locked amount
    },
    {
      "a": "BTC",
      "f": "10537.85314051",
      "l": "2.19464093"
    },
    {
      "a": "ETH",
      "f": "17902.35190619",
      "l": "0.00000000"
    },
    {
      "a": "BNC",
      "f": "1114503.29769312",
      "l": "0.00000000"
    },
    {
      "a": "NEO",
      "f": "0.00000000",
      "l": "0.00000000"
    }
  ],
  "P": [                       // Account Permissions
        "SPOT"
  ]
}

type BalanceUpdateEvent

type BalanceUpdateEvent struct {
	EventBase

	Asset     string `json:"a"`
	Delta     string `json:"d"`
	ClearTime int64  `json:"T"`
}

balanceUpdate

{
  "e": "balanceUpdate",         //KLineEvent Type
  "E": 1573200697110,           //KLineEvent Time
  "a": "BTC",                   //Asset
  "d": "100.00000000",          //Balance Delta
  "T": 1573200697068            //Clear Time
}

type BookTickerEvent added in v1.21.0

type BookTickerEvent struct {
	EventBase
	Symbol   string           `json:"s"`
	Buy      fixedpoint.Value `json:"b"`
	BuySize  fixedpoint.Value `json:"B"`
	Sell     fixedpoint.Value `json:"a"`
	SellSize fixedpoint.Value `json:"A"`
}

func (*BookTickerEvent) BookTicker added in v1.21.0

func (k *BookTickerEvent) BookTicker() types.BookTicker

type ContinuousKLineEvent added in v1.18.1

type ContinuousKLineEvent struct {
	EventBase
	Symbol string `json:"ps"`

	KLine KLine `json:"k,omitempty"`
	// contains filtered or unexported fields
}

type DepthEntry

type DepthEntry struct {
	PriceLevel fixedpoint.Value
	Quantity   fixedpoint.Value
}

type DepthEvent

type DepthEvent struct {
	EventBase

	Symbol        string `json:"s"`
	FirstUpdateID int64  `json:"U"`
	FinalUpdateID int64  `json:"u"`

	Bids types.PriceVolumeSlice `json:"b"`
	Asks types.PriceVolumeSlice `json:"a"`
}

func (*DepthEvent) OrderBook

func (e *DepthEvent) OrderBook() (book types.SliceOrderBook, err error)

func (*DepthEvent) String added in v1.17.0

func (e *DepthEvent) String() (o string)

type EventBase

type EventBase struct {
	Event string `json:"e"` // event
	Time  int64  `json:"E"`
}

type Exchange

type Exchange struct {
	types.MarginSettings
	types.FuturesSettings

	Client *binance.Client // Spot & Margin
	// contains filtered or unexported fields
}

func New

func New(key, secret string) *Exchange

func (*Exchange) BatchQueryKLines

func (e *Exchange) BatchQueryKLines(ctx context.Context, symbol string, interval types.Interval, startTime, endTime time.Time) ([]types.KLine, error)

func (*Exchange) CancelOrders

func (e *Exchange) CancelOrders(ctx context.Context, orders ...types.Order) (err error)

func (*Exchange) Name

func (e *Exchange) Name() types.ExchangeName

func (*Exchange) NewStream

func (e *Exchange) NewStream() types.Stream

func (*Exchange) PlatformFeeCurrency

func (e *Exchange) PlatformFeeCurrency() string

func (*Exchange) QueryAccount

func (e *Exchange) QueryAccount(ctx context.Context) (*types.Account, error)

func (*Exchange) QueryAccountBalances

func (e *Exchange) QueryAccountBalances(ctx context.Context) (types.BalanceMap, error)

func (*Exchange) QueryAveragePrice

func (e *Exchange) QueryAveragePrice(ctx context.Context, symbol string) (float64, error)

func (*Exchange) QueryClosedOrders

func (e *Exchange) QueryClosedOrders(ctx context.Context, symbol string, since, until time.Time, lastOrderID uint64) (orders []types.Order, err error)

func (*Exchange) QueryDepositHistory

func (e *Exchange) QueryDepositHistory(ctx context.Context, asset string, since, until time.Time) (allDeposits []types.Deposit, err error)

func (*Exchange) QueryDepth added in v1.21.0

func (e *Exchange) QueryDepth(ctx context.Context, symbol string) (snapshot types.SliceOrderBook, finalUpdateID int64, err error)

func (*Exchange) QueryFundingRateHistory added in v1.18.0

func (e *Exchange) QueryFundingRateHistory(ctx context.Context, symbol string) (*types.FundingRate, error)

func (*Exchange) QueryIsolatedMarginAccount added in v1.8.0

func (e *Exchange) QueryIsolatedMarginAccount(ctx context.Context, symbols ...string) (*types.IsolatedMarginAccount, error)

func (*Exchange) QueryKLines

func (e *Exchange) QueryKLines(ctx context.Context, symbol string, interval types.Interval, options types.KLineQueryOptions) ([]types.KLine, error)

QueryKLines queries the Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. Binance uses inclusive start time query range, eg: https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1m&startTime=1620172860000 the above query will return a kline with startTime = 1620172860000 and, https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1m&startTime=1620172860000&endTime=1620172920000 the above query will return a kline with startTime = 1620172860000, and a kline with endTime = 1620172860000

the endTime of a binance kline, is the (startTime + interval time - 1 millisecond), e.g., millisecond unix timestamp: 1620172860000 and 1620172919999

func (*Exchange) QueryMarginAccount added in v1.8.0

func (e *Exchange) QueryMarginAccount(ctx context.Context) (*types.MarginAccount, error)

func (*Exchange) QueryMarkets

func (e *Exchange) QueryMarkets(ctx context.Context) (types.MarketMap, error)

func (*Exchange) QueryOpenOrders

func (e *Exchange) QueryOpenOrders(ctx context.Context, symbol string) (orders []types.Order, err error)

func (*Exchange) QueryPremiumIndex added in v1.18.0

func (e *Exchange) QueryPremiumIndex(ctx context.Context, symbol string) (*types.PremiumIndex, error)

func (*Exchange) QueryTicker added in v1.11.1

func (e *Exchange) QueryTicker(ctx context.Context, symbol string) (*types.Ticker, error)

func (*Exchange) QueryTickers added in v1.11.0

func (e *Exchange) QueryTickers(ctx context.Context, symbol ...string) (map[string]types.Ticker, error)

func (*Exchange) QueryTrades

func (e *Exchange) QueryTrades(ctx context.Context, symbol string, options *types.TradeQueryOptions) (trades []types.Trade, err error)

func (*Exchange) QueryWithdrawHistory

func (e *Exchange) QueryWithdrawHistory(ctx context.Context, asset string, since, until time.Time) (allWithdraws []types.Withdraw, err error)

func (*Exchange) SubmitOrders

func (e *Exchange) SubmitOrders(ctx context.Context, orders ...types.SubmitOrder) (createdOrders types.OrderSlice, err error)

func (*Exchange) Withdrawal added in v1.16.0

func (e *Exchange) Withdrawal(ctx context.Context, asset string, amount fixedpoint.Value, address string, options *types.WithdrawalOptions) error

type ExecutionReportEvent

type ExecutionReportEvent struct {
	EventBase

	Symbol string `json:"s"`
	Side   string `json:"S"`

	ClientOrderID         string `json:"c"`
	OriginalClientOrderID string `json:"C"`

	OrderType         string `json:"o"`
	OrderCreationTime int64  `json:"O"`

	TimeInForce     string `json:"f"`
	IcebergQuantity string `json:"F"`

	OrderQuantity      string `json:"q"`
	QuoteOrderQuantity string `json:"Q"`

	OrderPrice string `json:"p"`
	StopPrice  string `json:"P"`

	IsOnBook bool `json:"w"`

	IsMaker bool `json:"m"`
	Ignore  bool `json:"M"`

	CommissionAmount string `json:"n"`
	CommissionAsset  string `json:"N"`

	CurrentExecutionType string `json:"x"`
	CurrentOrderStatus   string `json:"X"`

	OrderID int64 `json:"i"`
	Ignored int64 `json:"I"`

	TradeID         int64 `json:"t"`
	TransactionTime int64 `json:"T"`

	LastExecutedQuantity string `json:"l"`
	LastExecutedPrice    string `json:"L"`

	CumulativeFilledQuantity               string `json:"z"`
	CumulativeQuoteAssetTransactedQuantity string `json:"Z"`

	LastQuoteAssetTransactedQuantity string `json:"Y"`
}

executionReport

{
  "e": "executionReport",        // Event type
  "E": 1499405658658,            // Event time
  "s": "ETHBTC",                 // Symbol
  "c": "mUvoqJxFIILMdfAW5iGSOW", // Client order ID
  "S": "BUY",                    // Side
  "o": "LIMIT",                  // Order type
  "f": "GTC",                    // Time in force
  "q": "1.00000000",             // Order quantity
  "p": "0.10264410",             // Order price
  "P": "0.00000000",             // Stop price
  "F": "0.00000000",             // Iceberg quantity
  "g": -1,                       // OrderListId
  "C": null,                     // Original client order ID; This is the ID of the order being canceled
  "x": "NEW",                    // Current execution type
  "X": "NEW",                    // Current order status
  "r": "NONE",                   // Order reject reason; will be an error code.
  "i": 4293153,                  // Order ID
  "l": "0.00000000",             // Last executed quantity
  "z": "0.00000000",             // Cumulative filled quantity
  "L": "0.00000000",             // Last executed price
  "n": "0",                      // Commission amount
  "N": null,                     // Commission asset
  "T": 1499405658657,            // Transaction time
  "t": -1,                       // Trade ID
  "I": 8641984,                  // Ignore
  "w": true,                     // Is the order on the book?
  "m": false,                    // Is this trade the maker side?
  "M": false,                    // Ignore
  "O": 1499405658657,            // Order creation time
  "Z": "0.00000000",             // Cumulative quote asset transacted quantity
  "Y": "0.00000000",             // Last quote asset transacted quantity (i.e. lastPrice * lastQty)
  "Q": "0.00000000"              // Quote Order Qty
}

func (*ExecutionReportEvent) Order

func (e *ExecutionReportEvent) Order() (*types.Order, error)

func (*ExecutionReportEvent) Trade

func (e *ExecutionReportEvent) Trade() (*types.Trade, error)

type KLine

type KLine struct {
	StartTime int64 `json:"t"`
	EndTime   int64 `json:"T"`

	Symbol   string `json:"s"`
	Interval string `json:"i"`

	Open  fixedpoint.Value `json:"o"`
	Close fixedpoint.Value `json:"c"`
	High  fixedpoint.Value `json:"h"`
	Low   fixedpoint.Value `json:"l"`

	Volume      fixedpoint.Value `json:"v"` // base asset volume (like 10 BTC)
	QuoteVolume fixedpoint.Value `json:"q"` // quote asset volume

	TakerBuyBaseAssetVolume  fixedpoint.Value `json:"V"` // taker buy base asset volume (like 10 BTC)
	TakerBuyQuoteAssetVolume fixedpoint.Value `json:"Q"` // taker buy quote asset volume (like 1000USDT)

	LastTradeID    int   `json:"L"`
	NumberOfTrades int64 `json:"n"`
	Closed         bool  `json:"x"`
}

func (*KLine) KLine

func (k *KLine) KLine() types.KLine

type KLineEvent

type KLineEvent struct {
	EventBase
	Symbol string `json:"s"`
	KLine  KLine  `json:"k,omitempty"`
}

type MarkPriceUpdateEvent added in v1.18.1

type MarkPriceUpdateEvent struct {
	EventBase

	Symbol string `json:"s"`

	MarkPrice      fixedpoint.Value `json:"p"`
	IndexPrice     fixedpoint.Value `json:"i"`
	EstimatedPrice fixedpoint.Value `json:"P"`

	FundingRate     fixedpoint.Value `json:"r"`
	NextFundingTime int64            `json:"T"`
}

type OrderTrade added in v1.21.0

type OrderTrade struct {
	Symbol           string `json:"s"`
	ClientOrderID    string `json:"c"`
	Side             string `json:"S"`
	OrderType        string `json:"o"`
	TimeInForce      string `json:"f"`
	OriginalQuantity string `json:"q"`
	OriginalPrice    string `json:"p"`

	AveragePrice         string `json:"ap"`
	StopPrice            string `json:"sp"`
	CurrentExecutionType string `json:"x"`
	CurrentOrderStatus   string `json:"X"`

	OrderId                        int64  `json:"i"`
	OrderLastFilledQuantity        string `json:"l"`
	OrderFilledAccumulatedQuantity string `json:"z"`
	LastFilledPrice                string `json:"L"`

	CommissionAmount string `json:"n"`
	CommissionAsset  string `json:"N"`

	OrderTradeTime int64 `json:"T"`
	TradeId        int64 `json:"t"`

	BidsNotional string `json:"b"`
	AskNotional  string `json:"a"`

	IsMaker      bool `json:"m"`
	IsReduceOnly bool ` json:"r"`

	StopPriceWorkingType string `json:"wt"`
	OriginalOrderType    string `json:"ot"`
	PositionSide         string `json:"ps"`
	RealizedProfit       string `json:"rp"`
}

Similar to the ExecutionReportEvent's fields. But with totally different json key. e.g., Stop price. So that, we can not merge them.

type OrderTradeUpdateEvent added in v1.21.0

type OrderTradeUpdateEvent struct {
	EventBase
	Transaction int64      `json:"T"`
	OrderTrade  OrderTrade `json:"o"`
}

func (*OrderTradeUpdateEvent) OrderFutures added in v1.21.0

func (e *OrderTradeUpdateEvent) OrderFutures() (*types.Order, error)

type OutboundAccountInfoEvent

type OutboundAccountInfoEvent struct {
	EventBase

	MakerCommissionRate  int `json:"m"`
	TakerCommissionRate  int `json:"t"`
	BuyerCommissionRate  int `json:"b"`
	SellerCommissionRate int `json:"s"`

	CanTrade    bool `json:"T"`
	CanWithdraw bool `json:"W"`
	CanDeposit  bool `json:"D"`

	LastAccountUpdateTime int `json:"u"`

	Balances    []Balance `json:"B,omitempty"`
	Permissions []string  `json:"P,omitempty"`
}

type OutboundAccountPositionEvent added in v1.8.0

type OutboundAccountPositionEvent struct {
	EventBase

	LastAccountUpdateTime int       `json:"u"`
	Balances              []Balance `json:"B,omitempty"`
}

type ResultEvent

type ResultEvent struct {
	Result interface{} `json:"result,omitempty"`
	ID     int         `json:"id"`
}

type Stream

type Stream struct {
	types.MarginSettings
	types.FuturesSettings
	types.StandardStream

	Client *binance.Client

	Conn     *websocket.Conn
	ConnLock sync.Mutex
	// contains filtered or unexported fields
}

func NewStream

func NewStream(ex *Exchange, client *binance.Client, futuresClient *futures.Client) *Stream

func (*Stream) Close

func (s *Stream) Close() error

func (*Stream) Connect

func (s *Stream) Connect(ctx context.Context) error

Connect starts the stream and create the websocket connection

func (*Stream) EmitAccountConfigUpdateEvent added in v1.22.0

func (s *Stream) EmitAccountConfigUpdateEvent(e *AccountConfigUpdateEvent)

func (*Stream) EmitAccountUpdateEvent added in v1.22.0

func (s *Stream) EmitAccountUpdateEvent(e *AccountUpdateEvent)

func (*Stream) EmitBalanceUpdateEvent

func (s *Stream) EmitBalanceUpdateEvent(event *BalanceUpdateEvent)

func (*Stream) EmitBookTickerEvent added in v1.21.0

func (s *Stream) EmitBookTickerEvent(event *BookTickerEvent)

func (*Stream) EmitContinuousKLineClosedEvent added in v1.21.0

func (s *Stream) EmitContinuousKLineClosedEvent(e *ContinuousKLineEvent)

func (*Stream) EmitContinuousKLineEvent added in v1.18.1

func (s *Stream) EmitContinuousKLineEvent(e *ContinuousKLineEvent)

func (*Stream) EmitDepthEvent

func (s *Stream) EmitDepthEvent(e *DepthEvent)

func (*Stream) EmitExecutionReportEvent

func (s *Stream) EmitExecutionReportEvent(event *ExecutionReportEvent)

func (*Stream) EmitKLineClosedEvent

func (s *Stream) EmitKLineClosedEvent(e *KLineEvent)

func (*Stream) EmitKLineEvent

func (s *Stream) EmitKLineEvent(e *KLineEvent)

func (*Stream) EmitMarkPriceUpdateEvent added in v1.18.1

func (s *Stream) EmitMarkPriceUpdateEvent(e *MarkPriceUpdateEvent)

func (*Stream) EmitOrderTradeUpdateEvent added in v1.21.0

func (s *Stream) EmitOrderTradeUpdateEvent(e *OrderTradeUpdateEvent)

func (*Stream) EmitOutboundAccountInfoEvent

func (s *Stream) EmitOutboundAccountInfoEvent(event *OutboundAccountInfoEvent)

func (*Stream) EmitOutboundAccountPositionEvent added in v1.8.0

func (s *Stream) EmitOutboundAccountPositionEvent(event *OutboundAccountPositionEvent)

func (*Stream) OnAccountConfigUpdateEvent added in v1.22.0

func (s *Stream) OnAccountConfigUpdateEvent(cb func(e *AccountConfigUpdateEvent))

func (*Stream) OnAccountUpdateEvent added in v1.22.0

func (s *Stream) OnAccountUpdateEvent(cb func(e *AccountUpdateEvent))

func (*Stream) OnBalanceUpdateEvent

func (s *Stream) OnBalanceUpdateEvent(cb func(event *BalanceUpdateEvent))

func (*Stream) OnBookTickerEvent added in v1.21.0

func (s *Stream) OnBookTickerEvent(cb func(event *BookTickerEvent))

func (*Stream) OnContinuousKLineClosedEvent added in v1.21.0

func (s *Stream) OnContinuousKLineClosedEvent(cb func(e *ContinuousKLineEvent))

func (*Stream) OnContinuousKLineEvent added in v1.18.1

func (s *Stream) OnContinuousKLineEvent(cb func(e *ContinuousKLineEvent))

func (*Stream) OnDepthEvent

func (s *Stream) OnDepthEvent(cb func(e *DepthEvent))

func (*Stream) OnExecutionReportEvent

func (s *Stream) OnExecutionReportEvent(cb func(event *ExecutionReportEvent))

func (*Stream) OnKLineClosedEvent

func (s *Stream) OnKLineClosedEvent(cb func(e *KLineEvent))

func (*Stream) OnKLineEvent

func (s *Stream) OnKLineEvent(cb func(e *KLineEvent))

func (*Stream) OnMarkPriceUpdateEvent added in v1.18.1

func (s *Stream) OnMarkPriceUpdateEvent(cb func(e *MarkPriceUpdateEvent))

func (*Stream) OnOrderTradeUpdateEvent added in v1.21.0

func (s *Stream) OnOrderTradeUpdateEvent(cb func(e *OrderTradeUpdateEvent))

func (*Stream) OnOutboundAccountInfoEvent

func (s *Stream) OnOutboundAccountInfoEvent(cb func(event *OutboundAccountInfoEvent))

func (*Stream) OnOutboundAccountPositionEvent added in v1.8.0

func (s *Stream) OnOutboundAccountPositionEvent(cb func(event *OutboundAccountPositionEvent))

type StreamEventHub

type StreamEventHub interface {
	OnDepthEvent(cb func(e *DepthEvent))

	OnKLineEvent(cb func(e *KLineEvent))

	OnKLineClosedEvent(cb func(e *KLineEvent))

	OnMarkPriceUpdateEvent(cb func(e *MarkPriceUpdateEvent))

	OnContinuousKLineEvent(cb func(e *ContinuousKLineEvent))

	OnContinuousKLineClosedEvent(cb func(e *ContinuousKLineEvent))

	OnBalanceUpdateEvent(cb func(event *BalanceUpdateEvent))

	OnOutboundAccountInfoEvent(cb func(event *OutboundAccountInfoEvent))

	OnOutboundAccountPositionEvent(cb func(event *OutboundAccountPositionEvent))

	OnExecutionReportEvent(cb func(event *ExecutionReportEvent))

	OnBookTickerEvent(cb func(event *BookTickerEvent))

	OnOrderTradeUpdateEvent(cb func(e *OrderTradeUpdateEvent))

	OnAccountUpdateEvent(cb func(e *AccountUpdateEvent))

	OnAccountConfigUpdateEvent(cb func(e *AccountConfigUpdateEvent))
}

type WebSocketCommand added in v1.21.3

type WebSocketCommand struct {
	// request ID is required
	ID     int      `json:"id"`
	Method string   `json:"method"`
	Params []string `json:"params"`
}

Jump to

Keyboard shortcuts

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