binance

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

binance-go

CI Go Go Reference codecov

Unofficial Binance REST + WebSocket SDK for Go.

One client, automatic timestamps, typed models, string decimals, and reconnecting streams — the python-binance experience, written as idiomatic Go.

go get github.com/Slrrxx/binance-go

Not affiliated with Binance. Trading and withdrawals can lose money. Use at your own risk.

Why this SDK

Day-one DX NewClient → ticker, account, or order in a few lines
Safe money types prices and quantities stay string — no float64
Production HTTP context.Context, retries that skip order creates, 429 / 418 handling
Live markets typed WebSocket events, reconnect + backoff, depth cache
Tested in CI gofmt, vet, test, -race, lint — no live exchange in default CI

Quick start

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/Slrrxx/binance-go"
)

func main() {
    client := binance.NewClient(
        os.Getenv("BINANCE_API_KEY"),
        os.Getenv("BINANCE_API_SECRET"),
    )

    ticker, err := client.GetSymbolTicker(context.Background(), "BTCUSDT")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(ticker.Price)
}
account, err := client.GetAccount(ctx)

order, err := client.CreateOrder(ctx, binance.OrderRequest{
    Symbol:        "BTCUSDT",
    Side:          binance.SideBuy,
    Type:          binance.OrderTypeMarket,
    Quantity:      "0.001",
    ClientOrderID: binance.NewClientOrderID(),
})

Public market data works with empty credentials. Signed calls need BINANCE_API_KEY / BINANCE_API_SECRET.

Features

  • Spot market data, trading, account, and user-data stream
  • USD-M and COIN-M futures, portfolio margin (papi), vanilla options (eapi)
  • Cross / isolated margin and wallet (withdrawals documented as dangerous)
  • Simple Earn, convert, and gift card
  • HMAC-SHA256, RSA, and Ed25519 signing
  • Automatic timestamps, configurable recvWindow, optional server-time sync
  • Testnet, demo, TLD, and HTTP proxy: WithTestnet(), WithDemo(), WithProxy
  • Historical klines — slice helper and memory-efficient iterator
  • Reconnecting market WebSockets (client.WebSocket().Trade) with typed events
  • WebSocket API trading (client.WSAPI(), client.FuturesWSAPI())
  • Thread-safe depth cache (snapshot + incremental sync) for spot and futures
  • Optional retry and rate limiter; secrets never logged

Authentication

client := binance.NewClient(
    os.Getenv("BINANCE_API_KEY"),
    os.Getenv("BINANCE_API_SECRET"),
    binance.WithRecvWindow(5000),
    binance.WithAutoTimeSync(),
    binance.WithTestnet(),
)

RSA / Ed25519:

client := binance.NewClient(apiKey, "",
    binance.WithEd25519PrivateKey(pemBytes, nil),
)

Market data · orders · streams

info, _ := client.GetExchangeInfo(ctx)
book, _ := client.GetOrderBook(ctx, "BTCUSDT", 100)

err := client.TestOrder(ctx, binance.OrderRequest{
    Symbol: "BTCUSDT", Side: binance.SideBuy,
    Type: binance.OrderTypeLimit, TimeInForce: binance.TimeInForceGTC,
    Quantity: "0.001", Price: "50000",
})
stream, err := client.WebSocket().Trade(ctx, "BTCUSDT")
// or: client.Subscribe(ctx, binance.StreamTrade("BTCUSDT"))
defer stream.Close()

for {
    ev, err := stream.Next(ctx)
    if err != nil {
        break
    }
    if ev.Trade != nil {
        fmt.Println(ev.Trade.Price, ev.Trade.Quantity)
    }
}
it := client.HistoricalKlines(binance.KlineQuery{
    Symbol: "BTCUSDT", Interval: binance.Interval1m, StartTime: start, EndTime: end,
})
for it.Next(ctx) {
    _ = it.Kline()
}
cache, err := client.DepthCache(ctx, "BTCUSDT")
defer cache.Close()
_, _ = cache.Wait(ctx)
bids, asks := cache.Bids(), cache.Asks()

Futures: client.Futures() · COIN-M: client.CoinFutures() · margin / wallet: client.Margin(), client.Wallet() · portfolio / options: client.Portfolio(), client.Options() · earn / convert: client.Earn(), client.Convert().

err := client.WSAPI().Ping(ctx)
order, err := client.WSAPI().CreateOrder(ctx, binance.OrderRequest{
    Symbol: "BTCUSDT", Side: binance.SideBuy, Type: binance.OrderTypeMarket, Quantity: "0.001",
})

Order creates over the WebSocket API are not retried.

Errors

var apiErr *binance.APIError
if errors.As(err, &apiErr) {
    fmt.Println(apiErr.Code, apiErr.Message, apiErr.HTTPStatus)
}

Also: AuthError, DecodeError, RequestError, RateLimitError, WebsocketError.

Order creates, withdrawals, borrow/repay, and transfers are not retried.

Examples

export BINANCE_API_KEY=
export BINANCE_API_SECRET=
go run ./examples/ticker
Example
ticker public price
order / test_order live / validate-only order
account spot account
historical_klines candle iterator
websocket_trade / websocket_depth market streams
user_stream authenticated user data
futures_order USD-M on testnet
margin margin account
testnet ping + test order
websocket_facade WebSocket().Trade
wsapi spot WebSocket API ping + ticker

Never commit real keys.

Docs

go test ./...
go test -race ./...

Live public endpoints: BINANCE_INTEGRATION=1 go test -tags=integration ./...

License

MIT — original code. Not a port of python-binance source.

v1 module: github.com/Slrrxx/binance-go. Breaking changes go to /v2.

Documentation

Overview

Package binance is a production-oriented unofficial Binance REST and WebSocket SDK for Go.

The public API is intentionally similar to python-binance in spirit (one client, automatic timestamps, testnet, historical klines, depth cache) while remaining idiomatic Go: context on every network call, typed structs, string decimals, and structured errors.

client := binance.NewClient(os.Getenv("BINANCE_API_KEY"), os.Getenv("BINANCE_API_SECRET"))
ticker, err := client.GetSymbolTicker(ctx, "BTCUSDT")
stream, err := client.WebSocket().Trade(ctx, "BTCUSDT")

Index

Examples

Constants

View Source
const (
	Version = "0.1.0"
)

REST and WebSocket hosts. Keep all versioned paths in one file so Binance URL changes do not scatter across the client.

Variables

View Source
var (
	ErrMissingAPIKey    = errors.New("binance: api key is required")
	ErrMissingAPISecret = errors.New("binance: api secret or private key is required")
	ErrStreamClosed     = errors.New("binance: websocket stream closed")
	ErrStreamOverflow   = errors.New("binance: websocket event buffer overflow")
	ErrDepthDesync      = errors.New("binance: depth cache sequence gap")
	ErrNoProgress       = errors.New("binance: historical pagination made no progress")
	ErrInvalidInterval  = errors.New("binance: unknown kline interval")
)

Sentinel errors for errors.Is checks.

Functions

func IntervalDuration

func IntervalDuration(interval Interval) (int64, bool)

IntervalDuration returns the interval length. The 1M interval is treated as 30 days for pagination only; callers should prefer an explicit EndTime.

func NewClientOrderID

func NewClientOrderID() string

NewClientOrderID returns a unique client order id (32 hex chars).

func RedactQuery

func RedactQuery(raw string) string

RedactQuery returns a query string safe for logs. Signature and other sensitive keys are replaced with [redacted].

Types

type APIError

type APIError struct {
	Code       int    `json:"code"`
	Message    string `json:"msg"`
	HTTPStatus int    `json:"-"`
}

APIError is a JSON error body returned by Binance.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) IsRateLimited

func (e *APIError) IsRateLimited() bool

IsRateLimited reports whether the error is a Binance rate-limit or IP ban.

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"`
	Brokered                   bool      `json:"brokered"`
	RequireSelfTradePrevention bool      `json:"requireSelfTradePrevention"`
	PreventSor                 bool      `json:"preventSor"`
	UpdateTime                 TimeMS    `json:"updateTime"`
	AccountType                string    `json:"accountType"`
	Balances                   []Balance `json:"balances"`
	Permissions                []string  `json:"permissions"`
	UID                        int64     `json:"uid"`
}

Account is a spot account snapshot.

func (*Account) BalanceOf

func (a *Account) BalanceOf(asset string) (Balance, bool)

BalanceOf returns a single asset from an account snapshot.

type AccountAPIStatus

type AccountAPIStatus struct {
	Data struct {
		IsLocked           bool  `json:"isLocked"`
		PlannedRecoverTime int64 `json:"plannedRecoverTime"`
		TriggerCondition   struct {
			GCR  int `json:"GCR"`
			IFER int `json:"IFER"`
			UFR  int `json:"UFR"`
		} `json:"triggerCondition"`
		UpdateTime TimeMS `json:"updateTime"`
	} `json:"data"`
}

AccountAPIStatus is GET /sapi/v1/account/apiTradingStatus.

type AccountRequest

type AccountRequest struct {
	OmitZeroBalances bool
	RecvWindow       int64
}

AccountRequest is GET /api/v3/account.

type AccountSnapshot

type AccountSnapshot struct {
	Code        int                      `json:"code"`
	Msg         string                   `json:"msg"`
	SnapshotVos []AccountSnapshotPayload `json:"snapshotVos"`
}

AccountSnapshot is a daily account snapshot.

type AccountSnapshotPayload

type AccountSnapshotPayload struct {
	Type       string          `json:"type"`
	UpdateTime TimeMS          `json:"updateTime"`
	Data       jsonRawSnapshot `json:"data"`
}

AccountSnapshotPayload is one snapshot day.

type AccountSnapshotRequest

type AccountSnapshotRequest struct {
	Type       string // SPOT, MARGIN, FUTURES
	StartTime  int64
	EndTime    int64
	Limit      int
	RecvWindow int64
}

AccountSnapshotRequest is GET /sapi/v1/accountSnapshot.

type AccountStatus

type AccountStatus struct {
	Data string `json:"data"`
}

AccountStatus is GET /sapi/v1/account/status.

type AggTrade

type AggTrade struct {
	AggTradeID   int64  `json:"a"`
	Price        string `json:"p"`
	Quantity     string `json:"q"`
	FirstTradeID int64  `json:"f"`
	LastTradeID  int64  `json:"l"`
	Timestamp    TimeMS `json:"T"`
	IsBuyerMaker bool   `json:"m"`
	IsBestMatch  bool   `json:"M"`
}

AggTrade is a compressed aggregate trade.

type AggTradeEvent

type AggTradeEvent struct {
	EventType    string `json:"e"`
	EventTime    TimeMS `json:"E"`
	Symbol       string `json:"s"`
	AggTradeID   int64  `json:"a"`
	Price        string `json:"p"`
	Quantity     string `json:"q"`
	FirstTradeID int64  `json:"f"`
	LastTradeID  int64  `json:"l"`
	TradeTime    TimeMS `json:"T"`
	IsBuyerMaker bool   `json:"m"`
}

AggTradeEvent is an aggregate trade stream payload.

type AggTradeIterator

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

AggTradeIterator pages aggregate trades.

func (*AggTradeIterator) AggTrade

func (it *AggTradeIterator) AggTrade() AggTrade

AggTrade returns the current aggregate trade.

func (*AggTradeIterator) Err

func (it *AggTradeIterator) Err() error

Err returns the iterator error.

func (*AggTradeIterator) Next

func (it *AggTradeIterator) Next(ctx context.Context) bool

Next advances the aggregate-trade iterator.

type AggTradeQuery

type AggTradeQuery struct {
	Symbol    string
	StartTime int64
	EndTime   int64
	FromID    int64
	Limit     int
}

AggTradeQuery pages public aggregate trades.

type AggTradesRequest

type AggTradesRequest struct {
	Symbol    string
	FromID    int64
	StartTime int64
	EndTime   int64
	Limit     int
}

AggTradesRequest is GET /api/v3/aggTrades.

type AllOrdersRequest

type AllOrdersRequest struct {
	Symbol     string
	OrderID    int64
	StartTime  int64
	EndTime    int64
	Limit      int
	RecvWindow int64
}

AllOrdersRequest is GET /api/v3/allOrders.

type AssetDetail

type AssetDetail map[string]AssetDetailEntry

AssetDetail is GET /sapi/v1/asset/assetDetail.

type AssetDetailEntry

type AssetDetailEntry struct {
	MinWithdrawAmount string `json:"minWithdrawAmount"`
	DepositStatus     bool   `json:"depositStatus"`
	WithdrawFee       any    `json:"withdrawFee"`
	WithdrawStatus    bool   `json:"withdrawStatus"`
	DepositTip        string `json:"depositTip"`
}

AssetDetailEntry is one asset's withdraw/deposit flags.

type AuthError

type AuthError struct {
	Msg string
}

AuthError is a local authentication / signing configuration problem.

func (*AuthError) Error

func (e *AuthError) Error() string

type AvgPrice

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

AvgPrice is the current average price.

type Balance

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

Balance is a spot asset balance. Free and Locked are decimal strings.

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"`
}

BookTicker is the best bid/ask.

type BookTickerEvent

type BookTickerEvent struct {
	UpdateID int64  `json:"u"`
	Symbol   string `json:"s"`
	BidPrice string `json:"b"`
	BidQty   string `json:"B"`
	AskPrice string `json:"a"`
	AskQty   string `json:"A"`
}

BookTickerEvent is a best bid/ask stream payload.

type BookTickerRequest

type BookTickerRequest struct {
	Symbol  string
	Symbols []string
}

BookTickerRequest is GET /api/v3/ticker/bookTicker.

type BorrowRepayRequest

type BorrowRepayRequest struct {
	Asset      string
	IsIsolated string
	Symbol     string
	Amount     string
	Type       string // BORROW or REPAY
	RecvWindow int64
}

BorrowRepayRequest is POST /sapi/v1/margin/borrow-repay.

type BorrowRepayResult

type BorrowRepayResult struct {
	TranID int64 `json:"tranId"`
}

BorrowRepayResult is a margin loan/repay ticket.

type CancelOrderRequest

type CancelOrderRequest struct {
	Symbol             string
	OrderID            int64
	OrigClientOrderID  string
	NewClientOrderID   string
	CancelRestrictions string
	RecvWindow         int64
}

CancelOrderRequest is DELETE /api/v3/order.

type CancelReplaceRequest

type CancelReplaceRequest struct {
	OrderRequest
	CancelReplaceMode   string
	CancelOrderID       int64
	CancelClientOrderID string
}

CancelReplaceRequest is POST /api/v3/order/cancelReplace.

type Client

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

Client is a thread-safe Binance REST and WebSocket client.

func NewClient

func NewClient(apiKey, apiSecret string, opts ...Option) *Client

NewClient constructs a Client. apiSecret may be empty when an RSA or Ed25519 private key option is supplied. Public market-data methods work with empty credentials.

Example
package main

import (
	"os"

	"github.com/Slrrxx/binance-go"
)

func main() {
	client := binance.NewClient(
		os.Getenv("BINANCE_API_KEY"),
		os.Getenv("BINANCE_API_SECRET"),
		binance.WithTestnet(),
		binance.WithProxy("http://127.0.0.1:7890"),
	)
	_ = client.Spot()
	_ = client.Futures()
	_ = client.CoinFutures()
	_ = client.Margin()
	_ = client.Wallet()
	_ = client.WebSocket()
	_ = client.WSAPI()
	_ = client.Portfolio()
	_ = client.Options()
	_ = client.Earn()
	_ = client.Convert()
	_ = client.GiftCard()
}

func (*Client) AggTrades

func (c *Client) AggTrades(q AggTradeQuery) *AggTradeIterator

AggTrades returns an iterator over public aggregate trades.

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, req CancelOrderRequest) (*Order, error)

CancelOrder cancels a spot order.

func (*Client) CoinFutures

func (c *Client) CoinFutures() *CoinFuturesService

CoinFutures returns the COIN-M futures service.

func (*Client) Convert

func (c *Client) Convert() *ConvertService

Convert returns convert-quote helpers.

func (*Client) CreateOrder

func (c *Client) CreateOrder(ctx context.Context, req OrderRequest) (*Order, error)

CreateOrder places a spot order. This call is not retried.

func (*Client) DepthCache

func (c *Client) DepthCache(ctx context.Context, symbol string, opts ...DepthCacheOption) (*DepthCache, error)

DepthCache starts a synchronized local order book for symbol.

func (*Client) Earn

func (c *Client) Earn() *EarnService

Earn returns Simple Earn helpers.

func (*Client) Environment

func (c *Client) Environment() Environment

Environment reports the configured environment.

func (*Client) Futures

func (c *Client) Futures() *FuturesService

Futures returns the USDⓈ-M futures service.

func (*Client) FuturesWSAPI

func (c *Client) FuturesWSAPI() *WSAPI

FuturesWSAPI returns the USD-M futures WebSocket API client.

func (*Client) GetAccount

func (c *Client) GetAccount(ctx context.Context) (*Account, error)

GetAccount returns the current spot account.

func (*Client) GetExchangeInfo

func (c *Client) GetExchangeInfo(ctx context.Context) (*ExchangeInfo, error)

GetExchangeInfo returns spot exchange information.

func (*Client) GetHistoricalKlines

func (c *Client) GetHistoricalKlines(ctx context.Context, symbol string, interval Interval, startTime, endTime int64) ([]Kline, error)

GetHistoricalKlines fetches all klines in [start, end] into memory. Prefer HistoricalKlines for large ranges.

func (*Client) GetOrder

func (c *Client) GetOrder(ctx context.Context, req QueryOrderRequest) (*Order, error)

GetOrder queries a spot order.

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(ctx context.Context, symbol string, limit int) (*OrderBook, error)

GetOrderBook returns the spot order book for symbol.

func (*Client) GetServerTime

func (c *Client) GetServerTime(ctx context.Context) (int64, error)

GetServerTime returns Binance server time in milliseconds.

func (*Client) GetSymbolTicker

func (c *Client) GetSymbolTicker(ctx context.Context, symbol string) (*SymbolPrice, error)

GetSymbolTicker returns the latest price for a symbol.

func (*Client) GiftCard

func (c *Client) GiftCard() *GiftCardService

GiftCard returns gift-card helpers.

func (*Client) HistoricalKlines

func (c *Client) HistoricalKlines(q KlineQuery) *KlineIterator

HistoricalKlines returns a memory-efficient iterator over paginated klines.

func (*Client) Margin

func (c *Client) Margin() *MarginService

Margin returns cross and isolated margin methods.

func (*Client) Options

func (c *Client) Options() *OptionsService

Options returns the vanilla options (eapi) service.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping tests REST connectivity.

func (*Client) Portfolio

func (c *Client) Portfolio() *PortfolioService

Portfolio returns the portfolio-margin (papi) service.

func (*Client) SetTimeOffset

func (c *Client) SetTimeOffset(ms int64)

SetTimeOffset stores a millisecond offset added to request timestamps.

func (*Client) Spot

func (c *Client) Spot() *SpotService

Spot returns the spot REST service.

func (*Client) String

func (c *Client) String() string

String does not expose credentials.

func (*Client) SubAccount

func (c *Client) SubAccount() *SubAccountService

SubAccount returns sub-account helpers.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, specs ...StreamSpec) (*Stream, error)

Subscribe opens a reconnecting stream for one or more specs on the same market.

func (*Client) SyncTime

func (c *Client) SyncTime(ctx context.Context) error

SyncTime sets the local clock offset from Binance server time.

func (*Client) TestOrder

func (c *Client) TestOrder(ctx context.Context, req OrderRequest) error

TestOrder validates a spot order without submitting it.

func (*Client) TimeOffset

func (c *Client) TimeOffset() int64

TimeOffset returns the server-local clock offset in milliseconds.

func (*Client) UsedWeight

func (c *Client) UsedWeight() int

UsedWeight returns the last observed X-MBX-USED-WEIGHT-1M value.

func (*Client) UserData

func (c *Client) UserData(ctx context.Context) (*Stream, error)

UserData opens a reconnecting user-data stream and keepalives the listen key.

func (*Client) UserStream

func (c *Client) UserStream() *UserStreamService

UserStream returns listenKey management for the spot user-data stream.

func (*Client) WSAPI

func (c *Client) WSAPI() *WSAPI

WSAPI returns the spot WebSocket API (order.place and related methods).

func (*Client) Wallet

func (c *Client) Wallet() *WalletService

Wallet returns wallet / capital REST methods.

func (*Client) WebSocket

func (c *Client) WebSocket() *WebSocketService

WebSocket returns market-stream helpers such as Trade and Depth.

type CoinFuturesService

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

CoinFuturesService is COIN-M futures (dapi).

func (*CoinFuturesService) Account

func (s *CoinFuturesService) Account(ctx context.Context, recv int64) (*FuturesAccount, error)

Account returns COIN-M account information.

func (*CoinFuturesService) AllOrders

func (s *CoinFuturesService) AllOrders(ctx context.Context, req AllOrdersRequest, pair string) ([]FuturesOrder, error)

AllOrders returns COIN-M order history.

func (*CoinFuturesService) Balance

func (s *CoinFuturesService) Balance(ctx context.Context, recv int64) ([]FuturesBalance, error)

Balance returns COIN-M balances.

func (*CoinFuturesService) BookTicker

func (s *CoinFuturesService) BookTicker(ctx context.Context, symbol string) ([]BookTicker, error)

BookTicker returns COIN-M best bid/ask.

func (*CoinFuturesService) CancelAllOpenOrders

func (s *CoinFuturesService) CancelAllOpenOrders(ctx context.Context, symbol string, recv int64) error

CancelAllOpenOrders cancels all COIN-M open orders for a symbol.

func (*CoinFuturesService) CancelOrder

CancelOrder cancels a COIN-M order.

func (*CoinFuturesService) ChangeLeverage

func (s *CoinFuturesService) ChangeLeverage(ctx context.Context, symbol string, leverage int, recv int64) error

ChangeLeverage sets COIN-M leverage. Not retried.

func (*CoinFuturesService) ChangeMarginType

func (s *CoinFuturesService) ChangeMarginType(ctx context.Context, symbol string, marginType MarginType, recv int64) error

ChangeMarginType sets COIN-M margin type. Not retried.

func (*CoinFuturesService) ChangePositionMode

func (s *CoinFuturesService) ChangePositionMode(ctx context.Context, dualSide bool, recv int64) error

ChangePositionMode enables/disables COIN-M hedge mode. Not retried.

func (*CoinFuturesService) CloseListenKey

func (s *CoinFuturesService) CloseListenKey(ctx context.Context, listenKey string) error

CloseListenKey closes a COIN-M listen key.

func (*CoinFuturesService) CreateOrder

CreateOrder places a COIN-M order. Not retried.

func (*CoinFuturesService) DepthCache

func (s *CoinFuturesService) DepthCache(ctx context.Context, symbol string) (*DepthCache, error)

DepthCache starts a COIN-M local order book.

func (*CoinFuturesService) ExchangeInfo

func (s *CoinFuturesService) ExchangeInfo(ctx context.Context) (*FuturesExchangeInfo, error)

ExchangeInfo returns COIN-M exchange information.

func (*CoinFuturesService) GetOrder

GetOrder queries a COIN-M order.

func (*CoinFuturesService) GetPositionMode

func (s *CoinFuturesService) GetPositionMode(ctx context.Context, recv int64) (*PositionMode, error)

GetPositionMode returns COIN-M hedge mode.

func (*CoinFuturesService) IncomeHistory

func (s *CoinFuturesService) IncomeHistory(ctx context.Context, req IncomeHistoryRequest) ([]Income, error)

IncomeHistory returns COIN-M income history.

func (*CoinFuturesService) KeepListenKey

func (s *CoinFuturesService) KeepListenKey(ctx context.Context, listenKey string) error

KeepListenKey keepalives a COIN-M listen key.

func (*CoinFuturesService) Klines

func (s *CoinFuturesService) Klines(ctx context.Context, req KlinesRequest) ([]Kline, error)

Klines returns COIN-M candlesticks.

func (*CoinFuturesService) ListenKey

func (s *CoinFuturesService) ListenKey(ctx context.Context) (string, error)

ListenKey creates a COIN-M user-data listen key.

func (*CoinFuturesService) MarkPrice

func (s *CoinFuturesService) MarkPrice(ctx context.Context, symbol, pair string) ([]MarkPrice, error)

MarkPrice returns COIN-M mark prices.

func (*CoinFuturesService) OpenOrders

func (s *CoinFuturesService) OpenOrders(ctx context.Context, symbol, pair string, recv int64) ([]FuturesOrder, error)

OpenOrders returns COIN-M open orders.

func (*CoinFuturesService) OrderBook

OrderBook returns the COIN-M order book.

func (*CoinFuturesService) Ping

func (s *CoinFuturesService) Ping(ctx context.Context) error

Ping tests COIN-M connectivity.

func (*CoinFuturesService) Positions

func (s *CoinFuturesService) Positions(ctx context.Context, marginAsset, pair string, recv int64) ([]FuturesPosition, error)

Positions returns COIN-M position risk.

func (*CoinFuturesService) ServerTime

func (s *CoinFuturesService) ServerTime(ctx context.Context) (int64, error)

ServerTime returns COIN-M server time.

func (*CoinFuturesService) Ticker24h

func (s *CoinFuturesService) Ticker24h(ctx context.Context, symbol string) ([]Ticker24h, error)

Ticker24h returns COIN-M 24h tickers.

func (*CoinFuturesService) TickerPrice

func (s *CoinFuturesService) TickerPrice(ctx context.Context, symbol string) ([]SymbolPrice, error)

TickerPrice returns COIN-M latest prices.

func (*CoinFuturesService) UserData

func (s *CoinFuturesService) UserData(ctx context.Context) (*Stream, error)

UserData opens a COIN-M futures user-data stream with listen-key keepalive.

func (*CoinFuturesService) UserTrades

func (s *CoinFuturesService) UserTrades(ctx context.Context, req MyTradesRequest, pair string) ([]FuturesUserTrade, error)

UserTrades returns COIN-M account trades.

type CoinInfo

type CoinInfo struct {
	Coin              string        `json:"coin"`
	DepositAllEnable  bool          `json:"depositAllEnable"`
	WithdrawAllEnable bool          `json:"withdrawAllEnable"`
	Name              string        `json:"name"`
	Free              string        `json:"free"`
	Locked            string        `json:"locked"`
	Freeze            string        `json:"freeze"`
	Withdrawing       string        `json:"withdrawing"`
	Ipoing            string        `json:"ipoing"`
	Ipoable           string        `json:"ipoable"`
	Storage           string        `json:"storage"`
	IsLegalMoney      bool          `json:"isLegalMoney"`
	Trading           bool          `json:"trading"`
	NetworkList       []CoinNetwork `json:"networkList"`
}

CoinInfo is one entry from GET /sapi/v1/capital/config/getall.

type CoinNetwork

type CoinNetwork struct {
	Network                 string `json:"network"`
	Coin                    string `json:"coin"`
	WithdrawIntegerMultiple string `json:"withdrawIntegerMultiple"`
	IsDefault               bool   `json:"isDefault"`
	DepositEnable           bool   `json:"depositEnable"`
	WithdrawEnable          bool   `json:"withdrawEnable"`
	DepositDesc             string `json:"depositDesc"`
	WithdrawDesc            string `json:"withdrawDesc"`
	SpecialTips             string `json:"specialTips"`
	Name                    string `json:"name"`
	ResetAddressStatus      bool   `json:"resetAddressStatus"`
	AddressRegex            string `json:"addressRegex"`
	MemoRegex               string `json:"memoRegex"`
	WithdrawFee             string `json:"withdrawFee"`
	WithdrawMin             string `json:"withdrawMin"`
	WithdrawMax             string `json:"withdrawMax"`
	MinConfirm              int    `json:"minConfirm"`
	UnLockConfirm           int    `json:"unLockConfirm"`
}

CoinNetwork describes a withdraw/deposit network.

type ContractType

type ContractType string

ContractType is a futures contract type.

const (
	ContractPerpetual      ContractType = "PERPETUAL"
	ContractCurrentQuarter ContractType = "CURRENT_QUARTER"
	ContractNextQuarter    ContractType = "NEXT_QUARTER"
	ContractCurrentMonth   ContractType = "CURRENT_MONTH"
	ContractNextMonth      ContractType = "NEXT_MONTH"
)

type ConvertPair

type ConvertPair struct {
	FromAsset          string `json:"fromAsset"`
	ToAsset            string `json:"toAsset"`
	FromAssetMinAmount string `json:"fromAssetMinAmount"`
	FromAssetMaxAmount string `json:"fromAssetMaxAmount"`
	ToAssetMinAmount   string `json:"toAssetMinAmount"`
	ToAssetMaxAmount   string `json:"toAssetMaxAmount"`
}

ConvertPair is GET /sapi/v1/convert/exchangeInfo.

type ConvertQuote

type ConvertQuote struct {
	QuoteID        string `json:"quoteId"`
	Ratio          string `json:"ratio"`
	InverseRatio   string `json:"inverseRatio"`
	ValidTimestamp int64  `json:"validTimestamp"`
	ToAmount       string `json:"toAmount"`
	FromAmount     string `json:"fromAmount"`
}

ConvertQuote is a convert quote ticket.

type ConvertService

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

ConvertService covers the convert (quote) API.

func (*ConvertService) AcceptQuote

func (s *ConvertService) AcceptQuote(ctx context.Context, quoteID string, recv int64) (*UniversalTransferResult, error)

AcceptQuote accepts a convert quote. Not retried.

func (*ConvertService) ExchangeInfo

func (s *ConvertService) ExchangeInfo(ctx context.Context, fromAsset, toAsset string) ([]ConvertPair, error)

ExchangeInfo returns convert pairs.

func (*ConvertService) GetQuote

func (s *ConvertService) GetQuote(ctx context.Context, fromAsset, toAsset, fromAmount string, recv int64) (*ConvertQuote, error)

GetQuote requests a convert quote. Not retried.

func (*ConvertService) OrderStatus

func (s *ConvertService) OrderStatus(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

OrderStatus queries a convert order by quote or order id. extra may be nil.

type DecodeError

type DecodeError struct {
	Op     string
	Err    error
	Status int
}

DecodeError is returned when a response body cannot be decoded.

func (*DecodeError) Error

func (e *DecodeError) Error() string

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

type Deposit

type Deposit struct {
	ID            string `json:"id"`
	Amount        string `json:"amount"`
	Coin          string `json:"coin"`
	Network       string `json:"network"`
	Status        int    `json:"status"`
	Address       string `json:"address"`
	AddressTag    string `json:"addressTag"`
	TxID          string `json:"txId"`
	InsertTime    TimeMS `json:"insertTime"`
	TransferType  int    `json:"transferType"`
	ConfirmTimes  string `json:"confirmTimes"`
	UnlockConfirm int    `json:"unlockConfirm"`
	WalletType    int    `json:"walletType"`
}

Deposit is one deposit history row.

type DepositAddress

type DepositAddress struct {
	Address string `json:"address"`
	Coin    string `json:"coin"`
	Tag     string `json:"tag"`
	URL     string `json:"url"`
}

DepositAddress is a deposit address.

type DepositAddressRequest

type DepositAddressRequest struct {
	Coin       string
	Network    string
	RecvWindow int64
}

DepositAddressRequest is GET /sapi/v1/capital/deposit/address.

type DepositHistoryRequest

type DepositHistoryRequest struct {
	Coin       string
	Status     int
	StartTime  int64
	EndTime    int64
	Offset     int
	Limit      int
	TxID       string
	RecvWindow int64
}

DepositHistoryRequest is GET /sapi/v1/capital/deposit/hisrec.

type DepthCache

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

DepthCache is a thread-safe local order book synchronized from a REST snapshot plus incremental depth WebSocket events.

func (*DepthCache) Asks

func (d *DepthCache) Asks() []PriceLevel

Asks returns asks sorted by price ascending.

func (*DepthCache) Bids

func (d *DepthCache) Bids() []PriceLevel

Bids returns bids sorted by price descending.

func (*DepthCache) Close

func (d *DepthCache) Close() error

Close stops the cache and underlying stream.

func (*DepthCache) LastUpdateID

func (d *DepthCache) LastUpdateID() int64

LastUpdateID is the last applied update id.

func (*DepthCache) Updates

func (d *DepthCache) Updates() <-chan struct{}

Updates is signaled (non-blocking, coalesced) after each applied book update.

func (*DepthCache) Wait

func (d *DepthCache) Wait(ctx context.Context) (struct{}, error)

Wait blocks until the book is updated or ctx is done.

type DepthCacheOption

type DepthCacheOption func(*DepthCache)

DepthCacheOption configures DepthCache.

func WithDepthMarket

func WithDepthMarket(m Market) DepthCacheOption

WithDepthMarket selects spot (default), USD-M, or COIN-M books.

type DepthEvent

type DepthEvent struct {
	EventType     string       `json:"e"`
	EventTime     TimeMS       `json:"E"`
	Symbol        string       `json:"s"`
	FirstUpdateID int64        `json:"U"`
	FinalUpdateID int64        `json:"u"`
	PrevUpdateID  int64        `json:"pu"`
	Bids          []PriceLevel `json:"b"`
	Asks          []PriceLevel `json:"a"`
}

DepthEvent is a diff depth stream payload.

type DepthLevel

type DepthLevel string

DepthLevel is a partial book depth for WebSocket streams.

const (
	DepthLevel5  DepthLevel = "5"
	DepthLevel10 DepthLevel = "10"
	DepthLevel20 DepthLevel = "20"
)

type EarnPage

type EarnPage struct {
	Rows  []EarnProduct `json:"rows"`
	Total int           `json:"total"`
}

EarnPage is a paginated Simple Earn list.

type EarnProduct

type EarnProduct struct {
	Asset                      string            `json:"asset"`
	LatestAnnualPercentageRate string            `json:"latestAnnualPercentageRate"`
	TierAnnualPercentageRate   map[string]string `json:"tierAnnualPercentageRate"`
	CanPurchase                bool              `json:"canPurchase"`
	CanRedeem                  bool              `json:"canRedeem"`
	IsSoldOut                  bool              `json:"isSoldOut"`
	Hot                        bool              `json:"hot"`
	MinPurchaseAmount          string            `json:"minPurchaseAmount"`
	ProductID                  string            `json:"productId"`
	Status                     string            `json:"status"`
	SubscriptionStartTime      TimeMS            `json:"subscriptionStartTime"`
}

EarnProduct is a Simple Earn product row.

type EarnService

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

EarnService covers Simple Earn flexible/locked products.

func (*EarnService) Account

func (s *EarnService) Account(ctx context.Context, recv int64) (map[string]string, error)

Account returns Simple Earn account totals.

func (*EarnService) FlexiblePosition

func (s *EarnService) FlexiblePosition(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

FlexiblePosition returns flexible Simple Earn positions. extra may be nil.

func (*EarnService) FlexibleProducts

func (s *EarnService) FlexibleProducts(ctx context.Context, asset string, recv int64) (*EarnPage, error)

FlexibleProducts lists flexible Simple Earn products.

func (*EarnService) LockedPosition

func (s *EarnService) LockedPosition(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

LockedPosition returns locked Simple Earn positions. extra may be nil.

func (*EarnService) LockedProducts

func (s *EarnService) LockedProducts(ctx context.Context, asset string, recv int64) (*EarnPage, error)

LockedProducts lists locked Simple Earn products.

func (*EarnService) RedeemFlexible

func (s *EarnService) RedeemFlexible(ctx context.Context, productID, amount string, recv int64) (*UniversalTransferResult, error)

RedeemFlexible redeems a flexible product. Not retried.

func (*EarnService) SubscribeFlexible

func (s *EarnService) SubscribeFlexible(ctx context.Context, productID, amount string, recv int64) (*UniversalTransferResult, error)

SubscribeFlexible subscribes to a flexible product. Not retried.

type Environment

type Environment int

Environment selects production, testnet, or demo hosts.

const (
	// EnvProduction is the live Binance environment.
	EnvProduction Environment = iota
	// EnvTestnet is the public testnet.
	EnvTestnet
	// EnvDemo is Binance demo trading.
	EnvDemo
)

type Event

type Event struct {
	Stream     string
	Type       string
	EventTime  time.Time
	Trade      *TradeEvent
	AggTrade   *AggTradeEvent
	Ticker     *TickerEvent
	MiniTicker *MiniTickerEvent
	BookTicker *BookTickerEvent
	Depth      *DepthEvent
	Kline      *KlineEvent
	User       json.RawMessage
	Raw        json.RawMessage
	Err        error
}

Event is a typed WebSocket payload. Exactly one of the pointer fields is typically set; Raw always holds the decoded JSON object.

type ExchangeInfo

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

ExchangeInfo is /api/v3/exchangeInfo.

type ExchangeInfoRequest

type ExchangeInfoRequest struct {
	Symbol  string
	Symbols []string
}

ExchangeInfoRequest filters GET /api/v3/exchangeInfo.

type Fill

type Fill struct {
	Price           string `json:"price"`
	Qty             string `json:"qty"`
	Commission      string `json:"commission"`
	CommissionAsset string `json:"commissionAsset"`
	TradeID         int64  `json:"tradeId"`
}

Fill is an execution fill on an order.

type FundingRate

type FundingRate struct {
	Symbol      string `json:"symbol"`
	FundingRate string `json:"fundingRate"`
	FundingTime TimeMS `json:"fundingTime"`
}

FundingRate is GET /fapi/v1/fundingRate.

type FuturesAccount

type FuturesAccount struct {
	FeeTier                     int               `json:"feeTier"`
	CanTrade                    bool              `json:"canTrade"`
	CanDeposit                  bool              `json:"canDeposit"`
	CanWithdraw                 bool              `json:"canWithdraw"`
	UpdateTime                  TimeMS            `json:"updateTime"`
	TotalInitialMargin          string            `json:"totalInitialMargin"`
	TotalMaintMargin            string            `json:"totalMaintMargin"`
	TotalWalletBalance          string            `json:"totalWalletBalance"`
	TotalUnrealizedProfit       string            `json:"totalUnrealizedProfit"`
	TotalMarginBalance          string            `json:"totalMarginBalance"`
	TotalPositionInitialMargin  string            `json:"totalPositionInitialMargin"`
	TotalOpenOrderInitialMargin string            `json:"totalOpenOrderInitialMargin"`
	TotalCrossWalletBalance     string            `json:"totalCrossWalletBalance"`
	TotalCrossUnPnl             string            `json:"totalCrossUnPnl"`
	AvailableBalance            string            `json:"availableBalance"`
	MaxWithdrawAmount           string            `json:"maxWithdrawAmount"`
	Assets                      []FuturesAsset    `json:"assets"`
	Positions                   []FuturesPosition `json:"positions"`
}

FuturesAccount is GET /fapi/v2/account.

type FuturesAsset

type FuturesAsset struct {
	Asset                  string `json:"asset"`
	WalletBalance          string `json:"walletBalance"`
	UnrealizedProfit       string `json:"unrealizedProfit"`
	MarginBalance          string `json:"marginBalance"`
	MaintMargin            string `json:"maintMargin"`
	InitialMargin          string `json:"initialMargin"`
	PositionInitialMargin  string `json:"positionInitialMargin"`
	OpenOrderInitialMargin string `json:"openOrderInitialMargin"`
	CrossWalletBalance     string `json:"crossWalletBalance"`
	CrossUnPnl             string `json:"crossUnPnl"`
	AvailableBalance       string `json:"availableBalance"`
	MaxWithdrawAmount      string `json:"maxWithdrawAmount"`
	UpdateTime             TimeMS `json:"updateTime"`
}

FuturesAsset is one futures wallet asset.

type FuturesBalance

type FuturesBalance struct {
	AccountAlias       string `json:"accountAlias"`
	Asset              string `json:"asset"`
	Balance            string `json:"balance"`
	CrossWalletBalance string `json:"crossWalletBalance"`
	CrossUnPnl         string `json:"crossUnPnl"`
	AvailableBalance   string `json:"availableBalance"`
	MaxWithdrawAmount  string `json:"maxWithdrawAmount"`
	MarginAvailable    bool   `json:"marginAvailable"`
	UpdateTime         TimeMS `json:"updateTime"`
}

FuturesBalance is GET /fapi/v2/balance.

type FuturesExchangeInfo

type FuturesExchangeInfo struct {
	Timezone   string              `json:"timezone"`
	ServerTime TimeMS              `json:"serverTime"`
	RateLimits []RateLimit         `json:"rateLimits"`
	Symbols    []FuturesSymbolInfo `json:"symbols"`
}

FuturesExchangeInfo is /fapi/v1/exchangeInfo.

type FuturesOrder

type FuturesOrder struct {
	ClientOrderID string       `json:"clientOrderId"`
	CumQty        string       `json:"cumQty"`
	CumQuote      string       `json:"cumQuote"`
	ExecutedQty   string       `json:"executedQty"`
	OrderID       int64        `json:"orderId"`
	AvgPrice      string       `json:"avgPrice"`
	OrigQty       string       `json:"origQty"`
	Price         string       `json:"price"`
	ReduceOnly    bool         `json:"reduceOnly"`
	Side          Side         `json:"side"`
	PositionSide  PositionSide `json:"positionSide"`
	Status        OrderStatus  `json:"status"`
	StopPrice     string       `json:"stopPrice"`
	ClosePosition bool         `json:"closePosition"`
	Symbol        string       `json:"symbol"`
	TimeInForce   TimeInForce  `json:"timeInForce"`
	Type          OrderType    `json:"type"`
	OrigType      OrderType    `json:"origType"`
	UpdateTime    TimeMS       `json:"updateTime"`
	WorkingType   WorkingType  `json:"workingType"`
	PriceProtect  bool         `json:"priceProtect"`
}

FuturesOrder is a USD-M / COIN-M order.

type FuturesOrderRequest

type FuturesOrderRequest struct {
	Symbol                  string
	Side                    Side
	PositionSide            PositionSide
	Type                    OrderType
	TimeInForce             TimeInForce
	Quantity                string
	ReduceOnly              string
	Price                   string
	ClientOrderID           string
	StopPrice               string
	ClosePosition           string
	ActivationPrice         string
	CallbackRate            string
	WorkingType             WorkingType
	PriceProtect            string
	NewOrderRespType        OrderRespType
	PriceMatch              string
	SelfTradePreventionMode SelfTradePreventionMode
	GoodTillDate            int64
	RecvWindow              int64
}

FuturesOrderRequest is POST /fapi/v1/order.

type FuturesPosition

type FuturesPosition struct {
	Symbol           string       `json:"symbol"`
	PositionAmt      string       `json:"positionAmt"`
	EntryPrice       string       `json:"entryPrice"`
	BreakEvenPrice   string       `json:"breakEvenPrice"`
	MarkPrice        string       `json:"markPrice"`
	UnRealizedProfit string       `json:"unRealizedProfit"`
	LiquidationPrice string       `json:"liquidationPrice"`
	Leverage         string       `json:"leverage"`
	MaxNotionalValue string       `json:"maxNotionalValue"`
	MarginType       MarginType   `json:"marginType"`
	IsolatedMargin   string       `json:"isolatedMargin"`
	IsAutoAddMargin  string       `json:"isAutoAddMargin"`
	PositionSide     PositionSide `json:"positionSide"`
	Notional         string       `json:"notional"`
	IsolatedWallet   string       `json:"isolatedWallet"`
	UpdateTime       TimeMS       `json:"updateTime"`
}

FuturesPosition is GET /fapi/v2/positionRisk.

type FuturesService

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

FuturesService is USDⓈ-M futures (fapi).

func (*FuturesService) Account

func (s *FuturesService) Account(ctx context.Context, recv int64) (*FuturesAccount, error)

Account returns USD-M account information.

func (*FuturesService) AllOrders

func (s *FuturesService) AllOrders(ctx context.Context, req AllOrdersRequest) ([]FuturesOrder, error)

AllOrders returns USD-M order history for a symbol.

func (*FuturesService) Balance

func (s *FuturesService) Balance(ctx context.Context, recv int64) ([]FuturesBalance, error)

Balance returns USD-M futures balances.

func (*FuturesService) BookTicker

func (s *FuturesService) BookTicker(ctx context.Context, symbol string) ([]BookTicker, error)

BookTicker returns USD-M best bid/ask.

func (*FuturesService) CancelAllOpenOrders

func (s *FuturesService) CancelAllOpenOrders(ctx context.Context, symbol string, recv int64) error

CancelAllOpenOrders cancels all USD-M open orders for a symbol.

func (*FuturesService) CancelOrder

func (s *FuturesService) CancelOrder(ctx context.Context, req CancelOrderRequest) (*FuturesOrder, error)

CancelOrder cancels a USD-M order.

func (*FuturesService) ChangeLeverage

func (s *FuturesService) ChangeLeverage(ctx context.Context, symbol string, leverage int, recv int64) error

ChangeLeverage sets symbol leverage. Not retried.

func (*FuturesService) ChangeMarginType

func (s *FuturesService) ChangeMarginType(ctx context.Context, symbol string, marginType MarginType, recv int64) error

ChangeMarginType sets isolated or crossed margin. Not retried.

func (*FuturesService) ChangePositionMode

func (s *FuturesService) ChangePositionMode(ctx context.Context, dualSide bool, recv int64) error

ChangePositionMode enables/disables hedge mode. Not retried.

func (*FuturesService) CloseListenKey

func (s *FuturesService) CloseListenKey(ctx context.Context, listenKey string) error

CloseListenKey closes a USD-M listen key.

func (*FuturesService) CreateOrder

func (s *FuturesService) CreateOrder(ctx context.Context, req FuturesOrderRequest) (*FuturesOrder, error)

CreateOrder places a USD-M futures order. Not retried.

func (*FuturesService) DepthCache

func (s *FuturesService) DepthCache(ctx context.Context, symbol string) (*DepthCache, error)

DepthCache starts a USD-M local order book.

func (*FuturesService) ExchangeInfo

func (s *FuturesService) ExchangeInfo(ctx context.Context) (*FuturesExchangeInfo, error)

ExchangeInfo returns USD-M exchange information.

func (*FuturesService) FundingRateHistory

func (s *FuturesService) FundingRateHistory(ctx context.Context, symbol string, start, end int64, limit int) ([]FundingRate, error)

FundingRateHistory returns funding rate history.

func (*FuturesService) GetOrder

GetOrder queries a USD-M order.

func (*FuturesService) GetPositionMode

func (s *FuturesService) GetPositionMode(ctx context.Context, recv int64) (*PositionMode, error)

GetPositionMode returns whether hedge mode is enabled.

func (*FuturesService) IncomeHistory

func (s *FuturesService) IncomeHistory(ctx context.Context, req IncomeHistoryRequest) ([]Income, error)

IncomeHistory returns USD-M income (funding, realized PnL, ...).

func (*FuturesService) KeepListenKey

func (s *FuturesService) KeepListenKey(ctx context.Context, listenKey string) error

KeepListenKey keepalives a USD-M listen key.

func (*FuturesService) Klines

func (s *FuturesService) Klines(ctx context.Context, req KlinesRequest) ([]Kline, error)

Klines returns USD-M candlesticks.

func (*FuturesService) ListenKey

func (s *FuturesService) ListenKey(ctx context.Context) (string, error)

ListenKey creates a USD-M user-data listen key.

func (*FuturesService) MarkPrice

func (s *FuturesService) MarkPrice(ctx context.Context, symbol string) ([]MarkPrice, error)

MarkPrice returns mark/index price and funding info.

func (*FuturesService) OpenOrders

func (s *FuturesService) OpenOrders(ctx context.Context, symbol string, recv int64) ([]FuturesOrder, error)

OpenOrders returns USD-M open orders.

func (*FuturesService) OrderBook

func (s *FuturesService) OrderBook(ctx context.Context, req OrderBookRequest) (*OrderBook, error)

OrderBook returns the USD-M order book.

func (*FuturesService) Ping

func (s *FuturesService) Ping(ctx context.Context) error

Ping tests USD-M futures connectivity.

func (*FuturesService) Positions

func (s *FuturesService) Positions(ctx context.Context, symbol string, recv int64) ([]FuturesPosition, error)

Positions returns USD-M position risk.

func (*FuturesService) ServerTime

func (s *FuturesService) ServerTime(ctx context.Context) (int64, error)

ServerTime returns USD-M server time.

func (*FuturesService) TestOrder

func (s *FuturesService) TestOrder(ctx context.Context, req FuturesOrderRequest) error

TestOrder validates a USD-M order without matching.

func (*FuturesService) Ticker24h

func (s *FuturesService) Ticker24h(ctx context.Context, symbol string) ([]Ticker24h, error)

Ticker24h returns USD-M 24h tickers.

func (*FuturesService) TickerPrice

func (s *FuturesService) TickerPrice(ctx context.Context, symbol string) ([]SymbolPrice, error)

TickerPrice returns USD-M latest prices.

func (*FuturesService) UserData

func (s *FuturesService) UserData(ctx context.Context) (*Stream, error)

UserData opens a USD-M futures user-data stream with listen-key keepalive.

func (*FuturesService) UserTrades

func (s *FuturesService) UserTrades(ctx context.Context, req MyTradesRequest) ([]FuturesUserTrade, error)

UserTrades returns USD-M account trades.

type FuturesSymbolInfo

type FuturesSymbolInfo struct {
	Symbol            string         `json:"symbol"`
	Pair              string         `json:"pair"`
	ContractType      ContractType   `json:"contractType"`
	Status            string         `json:"status"`
	BaseAsset         string         `json:"baseAsset"`
	QuoteAsset        string         `json:"quoteAsset"`
	MarginAsset       string         `json:"marginAsset"`
	PricePrecision    int            `json:"pricePrecision"`
	QuantityPrecision int            `json:"quantityPrecision"`
	UnderlyingType    string         `json:"underlyingType"`
	Filters           []SymbolFilter `json:"filters"`
	OrderTypes        []OrderType    `json:"orderTypes"`
	TimeInForce       []TimeInForce  `json:"timeInForce"`
}

FuturesSymbolInfo is a USD-M or COIN-M symbol.

type FuturesUserTrade

type FuturesUserTrade struct {
	Buyer           bool         `json:"buyer"`
	Commission      string       `json:"commission"`
	CommissionAsset string       `json:"commissionAsset"`
	ID              int64        `json:"id"`
	Maker           bool         `json:"maker"`
	OrderID         int64        `json:"orderId"`
	Price           string       `json:"price"`
	Qty             string       `json:"qty"`
	QuoteQty        string       `json:"quoteQty"`
	RealizedPnl     string       `json:"realizedPnl"`
	Side            Side         `json:"side"`
	PositionSide    PositionSide `json:"positionSide"`
	Symbol          string       `json:"symbol"`
	Time            TimeMS       `json:"time"`
}

FuturesUserTrade is GET /fapi/v1/userTrades.

type GiftCardService

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

GiftCardService covers Binance gift-card endpoints.

func (*GiftCardService) CreateCode

func (s *GiftCardService) CreateCode(ctx context.Context, token, amount string, recv int64) (json.RawMessage, error)

CreateCode issues a gift card. Not retried.

func (*GiftCardService) Redeem

func (s *GiftCardService) Redeem(ctx context.Context, code string, recv int64) (json.RawMessage, error)

Redeem redeems a gift card. Not retried.

func (*GiftCardService) TokenLimit

func (s *GiftCardService) TokenLimit(ctx context.Context, baseToken string, recv int64) (json.RawMessage, error)

TokenLimit returns gift-card buy limits for a token.

func (*GiftCardService) Verify

func (s *GiftCardService) Verify(ctx context.Context, referenceNo string, recv int64) (json.RawMessage, error)

Verify checks a gift-card reference number.

type HistoricalTradesRequest

type HistoricalTradesRequest struct {
	Symbol string
	Limit  int
	FromID int64
}

HistoricalTradesRequest is GET /api/v3/historicalTrades (API key).

type Income

type Income struct {
	Symbol     string `json:"symbol"`
	IncomeType string `json:"incomeType"`
	Income     string `json:"income"`
	Asset      string `json:"asset"`
	Info       string `json:"info"`
	Time       TimeMS `json:"time"`
	TranID     int64  `json:"tranId"`
	TradeID    string `json:"tradeId"`
}

Income is GET /fapi/v1/income.

type IncomeHistoryRequest

type IncomeHistoryRequest struct {
	Symbol     string
	IncomeType string
	StartTime  int64
	EndTime    int64
	Page       int
	Limit      int
	RecvWindow int64
}

IncomeHistoryRequest is GET /fapi/v1/income.

type InterestHistoryPage

type InterestHistoryPage struct {
	Rows  []InterestRecord `json:"rows"`
	Total int              `json:"total"`
}

InterestHistoryPage is a paginated interest history.

type InterestHistoryRequest

type InterestHistoryRequest struct {
	Asset          string
	IsolatedSymbol string
	StartTime      int64
	EndTime        int64
	Current        int
	Size           int
	RecvWindow     int64
}

InterestHistoryRequest is GET /sapi/v1/margin/interestHistory.

type InterestRecord

type InterestRecord struct {
	TxID                int64  `json:"txId"`
	InterestAccuredTime TimeMS `json:"interestAccuredTime"`
	Asset               string `json:"asset"`
	RawAsset            string `json:"rawAsset"`
	Principal           string `json:"principal"`
	Interest            string `json:"interest"`
	InterestRate        string `json:"interestRate"`
	Type                string `json:"type"`
	IsolatedSymbol      string `json:"isolatedSymbol"`
}

InterestRecord is one interest row.

type Interval

type Interval string

Interval is a kline/candlestick interval.

const (
	Interval1s  Interval = "1s"
	Interval1m  Interval = "1m"
	Interval3m  Interval = "3m"
	Interval5m  Interval = "5m"
	Interval15m Interval = "15m"
	Interval30m Interval = "30m"
	Interval1h  Interval = "1h"
	Interval2h  Interval = "2h"
	Interval4h  Interval = "4h"
	Interval6h  Interval = "6h"
	Interval8h  Interval = "8h"
	Interval12h Interval = "12h"
	Interval1d  Interval = "1d"
	Interval3d  Interval = "3d"
	Interval1w  Interval = "1w"
	Interval1M  Interval = "1M"
)

type IsolatedMarginAccount

type IsolatedMarginAccount struct {
	Assets              []IsolatedMarginPair `json:"assets"`
	TotalAssetOfBtc     string               `json:"totalAssetOfBtc"`
	TotalLiabilityOfBtc string               `json:"totalLiabilityOfBtc"`
	TotalNetAssetOfBtc  string               `json:"totalNetAssetOfBtc"`
}

IsolatedMarginAccount is GET /sapi/v1/margin/isolated/account.

type IsolatedMarginPair

type IsolatedMarginPair struct {
	Symbol            string      `json:"symbol"`
	IsolatedCreated   bool        `json:"isolatedCreated"`
	Enabled           bool        `json:"enabled"`
	MarginLevel       string      `json:"marginLevel"`
	MarginLevelStatus string      `json:"marginLevelStatus"`
	MarginRatio       string      `json:"marginRatio"`
	IndexPrice        string      `json:"indexPrice"`
	LiquidatePrice    string      `json:"liquidatePrice"`
	LiquidateRate     string      `json:"liquidateRate"`
	TradeEnabled      bool        `json:"tradeEnabled"`
	BaseAsset         MarginAsset `json:"baseAsset"`
	QuoteAsset        MarginAsset `json:"quoteAsset"`
}

IsolatedMarginPair is one isolated symbol bucket.

type IsolatedTransferRequest

type IsolatedTransferRequest struct {
	Asset      string
	Symbol     string
	TransFrom  string
	TransTo    string
	Amount     string
	RecvWindow int64
}

IsolatedTransferRequest is POST /sapi/v1/margin/isolated/transfer.

type Kline

type Kline struct {
	OpenTime                 TimeMS
	Open                     string
	High                     string
	Low                      string
	Close                    string
	Volume                   string
	CloseTime                TimeMS
	QuoteAssetVolume         string
	NumberOfTrades           int64
	TakerBuyBaseAssetVolume  string
	TakerBuyQuoteAssetVolume string
}

Kline is a candlestick. Prices and volumes are decimal strings.

func (*Kline) UnmarshalJSON

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

UnmarshalJSON accepts the Binance kline array encoding.

type KlineEvent

type KlineEvent struct {
	EventType string     `json:"e"`
	EventTime TimeMS     `json:"E"`
	Symbol    string     `json:"s"`
	Kline     KlineFrame `json:"k"`
}

KlineEvent is a kline stream payload.

type KlineFrame

type KlineFrame struct {
	StartTime     TimeMS   `json:"t"`
	CloseTime     TimeMS   `json:"T"`
	Symbol        string   `json:"s"`
	Interval      Interval `json:"i"`
	FirstTradeID  int64    `json:"f"`
	LastTradeID   int64    `json:"L"`
	Open          string   `json:"o"`
	Close         string   `json:"c"`
	High          string   `json:"h"`
	Low           string   `json:"l"`
	Volume        string   `json:"v"`
	TradeCount    int64    `json:"n"`
	Closed        bool     `json:"x"`
	QuoteVolume   string   `json:"q"`
	TakerBuyBase  string   `json:"V"`
	TakerBuyQuote string   `json:"Q"`
}

KlineFrame is the nested kline object.

type KlineIterator

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

KlineIterator pages through historical candlesticks like database/sql Rows.

func (*KlineIterator) Err

func (it *KlineIterator) Err() error

Err returns the first iterator error.

func (*KlineIterator) Kline

func (it *KlineIterator) Kline() Kline

Kline returns the current kline after a successful Next.

func (*KlineIterator) Next

func (it *KlineIterator) Next(ctx context.Context) bool

Next loads the next kline. It returns false on exhaustion or error.

type KlineQuery

type KlineQuery struct {
	Symbol    string
	Interval  Interval
	StartTime int64
	EndTime   int64
	Market    Market
	Limit     int // per-request page size, default 1000
}

KlineQuery describes a historical kline range.

type KlinesRequest

type KlinesRequest struct {
	Symbol    string
	Interval  Interval
	StartTime int64
	EndTime   int64
	Limit     int
	TimeZone  string
}

KlinesRequest is GET /api/v3/klines.

type ListenKeyResponse

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

ListenKeyResponse is a user-data stream listen key.

type Logger

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is an optional structured logger. The default is silent. Implementations must never log API secrets, signatures, or PEM material.

type MarginAccount

type MarginAccount struct {
	BorrowEnabled       bool          `json:"borrowEnabled"`
	MarginLevel         string        `json:"marginLevel"`
	TotalAssetOfBtc     string        `json:"totalAssetOfBtc"`
	TotalLiabilityOfBtc string        `json:"totalLiabilityOfBtc"`
	TotalNetAssetOfBtc  string        `json:"totalNetAssetOfBtc"`
	TradeEnabled        bool          `json:"tradeEnabled"`
	TransferEnabled     bool          `json:"transferEnabled"`
	AccountType         string        `json:"accountType"`
	UserAssets          []MarginAsset `json:"userAssets"`
}

MarginAccount is GET /sapi/v1/margin/account.

type MarginAsset

type MarginAsset struct {
	Asset    string `json:"asset"`
	Borrowed string `json:"borrowed"`
	Free     string `json:"free"`
	Interest string `json:"interest"`
	Locked   string `json:"locked"`
	NetAsset string `json:"netAsset"`
}

MarginAsset is one cross-margin asset.

type MarginOrderRequest

type MarginOrderRequest struct {
	OrderRequest
	IsIsolated        string
	SideEffectType    string
	AutoRepayAtCancel *bool
}

MarginOrderRequest is POST /sapi/v1/margin/order.

type MarginService

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

MarginService covers cross and isolated margin.

func (*MarginService) Account

func (s *MarginService) Account(ctx context.Context, recv int64) (*MarginAccount, error)

Account returns the cross-margin account.

func (*MarginService) AllOrders

func (s *MarginService) AllOrders(ctx context.Context, req AllOrdersRequest, isolated string) ([]Order, error)

AllOrders returns all margin orders for a symbol.

func (*MarginService) Borrow

Borrow borrows an asset. Not retried.

func (*MarginService) CancelOrder

func (s *MarginService) CancelOrder(ctx context.Context, req CancelOrderRequest, isolated string) (*Order, error)

CancelOrder cancels a margin order.

func (*MarginService) CreateOrder

func (s *MarginService) CreateOrder(ctx context.Context, req MarginOrderRequest) (*Order, error)

CreateOrder places a margin order. Not retried.

func (*MarginService) DisableIsolated

func (s *MarginService) DisableIsolated(ctx context.Context, symbol string, recv int64) error

DisableIsolated disables an isolated margin account for a symbol.

func (*MarginService) EnableIsolated

func (s *MarginService) EnableIsolated(ctx context.Context, symbol string, recv int64) error

EnableIsolated enables an isolated margin account for a symbol.

func (*MarginService) GetOrder

func (s *MarginService) GetOrder(ctx context.Context, req QueryOrderRequest, isolated string) (*Order, error)

GetOrder queries a margin order.

func (*MarginService) InterestHistory

InterestHistory returns margin interest records.

func (*MarginService) IsolatedAccount

func (s *MarginService) IsolatedAccount(ctx context.Context, symbols string, recv int64) (*IsolatedMarginAccount, error)

IsolatedAccount returns isolated margin account information.

func (*MarginService) IsolatedTransfer

IsolatedTransfer moves funds for isolated margin. Not retried.

func (*MarginService) ListenKey

func (s *MarginService) ListenKey(ctx context.Context) (string, error)

ListenKey creates a cross-margin user-data listen key.

func (*MarginService) MaxBorrowable

func (s *MarginService) MaxBorrowable(ctx context.Context, asset, isolatedSymbol string, recv int64) (*MaxBorrowable, error)

MaxBorrowable returns the max borrowable amount.

func (*MarginService) OpenOrders

func (s *MarginService) OpenOrders(ctx context.Context, symbol, isolated string, recv int64) ([]Order, error)

OpenOrders returns open margin orders.

func (*MarginService) Repay

Repay repays a margin loan. Not retried.

func (*MarginService) Transfer

Transfer moves funds between spot and cross margin. Not retried.

type MarginType

type MarginType string

MarginType is a futures margin type.

const (
	MarginTypeIsolated MarginType = "ISOLATED"
	MarginTypeCrossed  MarginType = "CROSSED"
)

type MarkPrice

type MarkPrice struct {
	Symbol               string `json:"symbol"`
	MarkPrice            string `json:"markPrice"`
	IndexPrice           string `json:"indexPrice"`
	EstimatedSettlePrice string `json:"estimatedSettlePrice"`
	LastFundingRate      string `json:"lastFundingRate"`
	NextFundingTime      TimeMS `json:"nextFundingTime"`
	InterestRate         string `json:"interestRate"`
	Time                 TimeMS `json:"time"`
}

MarkPrice is GET /fapi/v1/premiumIndex.

type Market

type Market int

Market is a product family used by streams and historical helpers.

const (
	MarketSpot Market = iota
	MarketUSDFutures
	MarketCoinFutures
	MarketPortfolio
	MarketOptions
)

type MaxBorrowable

type MaxBorrowable struct {
	Amount      string `json:"amount"`
	BorrowLimit string `json:"borrowLimit"`
}

MaxBorrowable is GET /sapi/v1/margin/maxBorrowable.

type MiniTickerEvent

type MiniTickerEvent struct {
	EventType   string `json:"e"`
	EventTime   TimeMS `json:"E"`
	Symbol      string `json:"s"`
	ClosePrice  string `json:"c"`
	OpenPrice   string `json:"o"`
	HighPrice   string `json:"h"`
	LowPrice    string `json:"l"`
	Volume      string `json:"v"`
	QuoteVolume string `json:"q"`
}

MiniTickerEvent is a mini-ticker stream payload.

type MyTrade

type MyTrade struct {
	Symbol          string `json:"symbol"`
	ID              int64  `json:"id"`
	OrderID         int64  `json:"orderId"`
	OrderListID     int64  `json:"orderListId"`
	Price           string `json:"price"`
	Qty             string `json:"qty"`
	QuoteQty        string `json:"quoteQty"`
	Commission      string `json:"commission"`
	CommissionAsset string `json:"commissionAsset"`
	Time            TimeMS `json:"time"`
	IsBuyer         bool   `json:"isBuyer"`
	IsMaker         bool   `json:"isMaker"`
	IsBestMatch     bool   `json:"isBestMatch"`
}

MyTrade is an account trade.

type MyTradesRequest

type MyTradesRequest struct {
	Symbol     string
	OrderID    int64
	StartTime  int64
	EndTime    int64
	FromID     int64
	Limit      int
	RecvWindow int64
}

MyTradesRequest is GET /api/v3/myTrades.

type OCORequest

type OCORequest struct {
	Symbol                  string
	Side                    Side
	Quantity                string
	ListClientOrderID       string
	AboveType               OrderType
	AbovePrice              string
	AboveStopPrice          string
	AboveClientOrderID      string
	AboveTimeInForce        TimeInForce
	BelowType               OrderType
	BelowPrice              string
	BelowStopPrice          string
	BelowClientOrderID      string
	BelowTimeInForce        TimeInForce
	NewOrderRespType        OrderRespType
	SelfTradePreventionMode SelfTradePreventionMode
	RecvWindow              int64
}

OCORequest is POST /api/v3/orderList/oco.

type OpenOrdersRequest

type OpenOrdersRequest struct {
	Symbol     string
	RecvWindow int64
}

OpenOrdersRequest is GET /api/v3/openOrders.

type Option

type Option func(*config)

Option configures a Client.

func WithAutoTimeSync

func WithAutoTimeSync() Option

WithAutoTimeSync fetches server time before the first signed request and stores a clock offset.

func WithBaseURL

func WithBaseURL(raw string) Option

WithBaseURL overrides the spot REST origin (tests, proxies, custom gateways).

func WithCoinFuturesBaseURL

func WithCoinFuturesBaseURL(raw string) Option

WithCoinFuturesBaseURL overrides the COIN-M futures REST origin.

func WithDebug

func WithDebug() Option

WithDebug enables verbose (redacted) request logging.

func WithDemo

func WithDemo() Option

WithDemo points REST hosts at Binance demo trading.

func WithEd25519PrivateKey

func WithEd25519PrivateKey(pemBytes []byte, password []byte) Option

WithEd25519PrivateKey uses an Ed25519 PEM (PKCS#8) private key.

func WithFuturesBaseURL

func WithFuturesBaseURL(raw string) Option

WithFuturesBaseURL overrides the USD-M futures REST origin.

func WithFuturesWSAPIURL

func WithFuturesWSAPIURL(raw string) Option

WithFuturesWSAPIURL overrides the USD-M WebSocket API origin.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient injects a custom *http.Client (timeouts, proxy, transport).

func WithHeader

func WithHeader(key, value string) Option

WithHeader adds a header sent on every REST request.

func WithLogger

func WithLogger(l Logger) Option

WithLogger installs an optional logger. The default is silent.

func WithOptionsURL

func WithOptionsURL(raw string) Option

WithOptionsURL overrides the vanilla options (eapi) REST origin.

func WithPortfolioURL

func WithPortfolioURL(raw string) Option

WithPortfolioURL overrides the portfolio-margin (papi) REST origin.

func WithProxy

func WithProxy(raw string) Option

WithProxy sets an HTTP(S) proxy URL on the client's transport (for example "http://127.0.0.1:7890"). Applied after WithHTTPClient.

func WithRSAPrivateKey

func WithRSAPrivateKey(pemBytes []byte, password []byte) Option

WithRSAPrivateKey uses an RSA PEM private key instead of HMAC.

func WithRateLimiter

func WithRateLimiter(l RateLimiter) Option

WithRateLimiter installs a limiter invoked before each REST call.

func WithRecvWindow

func WithRecvWindow(ms int64) Option

WithRecvWindow sets the default signed-request recvWindow in milliseconds.

func WithRetry

func WithRetry(r RetryConfig) Option

WithRetry overrides the transient-error retry policy.

func WithSigner

func WithSigner(s Signer) Option

WithSigner injects a custom signer.

func WithTLD

func WithTLD(tld string) Option

WithTLD selects a regional website TLD such as "us" or "jp".

func WithTestnet

func WithTestnet() Option

WithTestnet points REST and WebSocket hosts at Binance testnet.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets a default per-request timeout when the caller context has no deadline.

func WithWSAPIURL

func WithWSAPIURL(raw string) Option

WithWSAPIURL overrides the spot WebSocket API origin.

func WithWSBuffer

func WithWSBuffer(n int) Option

WithWSBuffer sets the per-stream event channel size.

func WithWSReconnect

func WithWSReconnect(maxRetries int, minBackoff, maxBackoff time.Duration) Option

WithWSReconnect configures websocket reconnect attempts. maxRetries <= 0 means retry until the stream context is cancelled.

func WithWebSocketURL

func WithWebSocketURL(raw string) Option

WithWebSocketURL overrides the spot WebSocket base (`.../ws`).

type OptionsExchangeInfo

type OptionsExchangeInfo struct {
	Timezone      string              `json:"timezone"`
	ServerTime    TimeMS              `json:"serverTime"`
	OptionSymbols []FuturesSymbolInfo `json:"optionSymbols"`
}

OptionsExchangeInfo is /eapi/v1/exchangeInfo.

type OptionsService

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

OptionsService is vanilla options (eapi).

func (*OptionsService) Account

func (s *OptionsService) Account(ctx context.Context, recv int64) (*FuturesAccount, error)

Account returns the options account.

func (*OptionsService) CancelOrder

func (s *OptionsService) CancelOrder(ctx context.Context, req CancelOrderRequest) (*FuturesOrder, error)

CancelOrder cancels an options order.

func (*OptionsService) CloseListenKey

func (s *OptionsService) CloseListenKey(ctx context.Context, listenKey string) error

CloseListenKey closes an options listen key.

func (*OptionsService) CreateOrder

func (s *OptionsService) CreateOrder(ctx context.Context, req FuturesOrderRequest) (*FuturesOrder, error)

CreateOrder places an options order. Not retried.

func (*OptionsService) ExchangeInfo

func (s *OptionsService) ExchangeInfo(ctx context.Context) (*OptionsExchangeInfo, error)

ExchangeInfo returns options trading rules.

func (*OptionsService) KeepListenKey

func (s *OptionsService) KeepListenKey(ctx context.Context, listenKey string) error

KeepListenKey keepalives an options listen key.

func (*OptionsService) Klines

func (s *OptionsService) Klines(ctx context.Context, req KlinesRequest) ([]Kline, error)

Klines returns options candlesticks.

func (*OptionsService) ListenKey

func (s *OptionsService) ListenKey(ctx context.Context) (string, error)

ListenKey creates an options user-data listen key.

func (*OptionsService) MarkPrice

func (s *OptionsService) MarkPrice(ctx context.Context, symbol string) ([]MarkPrice, error)

MarkPrice returns options mark prices.

func (*OptionsService) OpenOrders

func (s *OptionsService) OpenOrders(ctx context.Context, symbol string, recv int64) ([]FuturesOrder, error)

OpenOrders returns open options orders.

func (*OptionsService) OrderBook

func (s *OptionsService) OrderBook(ctx context.Context, req OrderBookRequest) (*OrderBook, error)

OrderBook returns an options order book.

func (*OptionsService) Ping

func (s *OptionsService) Ping(ctx context.Context) error

Ping tests options connectivity.

func (*OptionsService) Positions

func (s *OptionsService) Positions(ctx context.Context, symbol string, recv int64) ([]FuturesPosition, error)

Positions returns option positions.

func (*OptionsService) ServerTime

func (s *OptionsService) ServerTime(ctx context.Context) (int64, error)

ServerTime returns options server time.

func (*OptionsService) Ticker24h

func (s *OptionsService) Ticker24h(ctx context.Context, symbol string) ([]Ticker24h, error)

Ticker24h returns options 24h tickers.

func (*OptionsService) UserData

func (s *OptionsService) UserData(ctx context.Context) (*Stream, error)

UserData opens an options user-data stream with listen-key keepalive.

func (*OptionsService) UserTrades

func (s *OptionsService) UserTrades(ctx context.Context, req MyTradesRequest) ([]FuturesUserTrade, error)

UserTrades returns options account trades.

type Order

type Order struct {
	Symbol                  string      `json:"symbol"`
	OrderID                 int64       `json:"orderId"`
	OrderListID             int64       `json:"orderListId"`
	ClientOrderID           string      `json:"clientOrderId"`
	TransactTime            TimeMS      `json:"transactTime"`
	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                    Side        `json:"side"`
	StopPrice               string      `json:"stopPrice"`
	IcebergQty              string      `json:"icebergQty"`
	Time                    TimeMS      `json:"time"`
	UpdateTime              TimeMS      `json:"updateTime"`
	IsWorking               bool        `json:"isWorking"`
	WorkingTime             TimeMS      `json:"workingTime"`
	OrigQuoteOrderQty       string      `json:"origQuoteOrderQty"`
	SelfTradePreventionMode string      `json:"selfTradePreventionMode"`
	Fills                   []Fill      `json:"fills"`
}

Order is a spot order.

type OrderBook

type OrderBook struct {
	LastUpdateID int64        `json:"lastUpdateId"`
	Bids         []PriceLevel `json:"bids"`
	Asks         []PriceLevel `json:"asks"`
	E            int64        `json:"E"`
	T            int64        `json:"T"`
}

OrderBook is a REST depth snapshot.

type OrderBookRequest

type OrderBookRequest struct {
	Symbol string
	Limit  int
}

OrderBookRequest is GET /api/v3/depth.

type OrderCount

type OrderCount struct {
	RateLimitType string `json:"rateLimitType"`
	Interval      string `json:"interval"`
	IntervalNum   int    `json:"intervalNum"`
	Limit         int    `json:"limit"`
	Count         int    `json:"count"`
}

OrderCount is the current order rate-limit usage.

type OrderList

type OrderList struct {
	OrderListID       int64   `json:"orderListId"`
	ContingencyType   string  `json:"contingencyType"`
	ListStatusType    string  `json:"listStatusType"`
	ListOrderStatus   string  `json:"listOrderStatus"`
	ListClientOrderID string  `json:"listClientOrderId"`
	TransactionTime   TimeMS  `json:"transactionTime"`
	Symbol            string  `json:"symbol"`
	Orders            []Order `json:"orders"`
	OrderReports      []Order `json:"orderReports"`
}

OrderList is an OCO/OTO response.

type OrderRequest

type OrderRequest struct {
	Symbol                  string
	Side                    Side
	Type                    OrderType
	TimeInForce             TimeInForce
	Quantity                string
	QuoteOrderQty           string
	Price                   string
	ClientOrderID           string
	StrategyID              int64
	StrategyType            int
	StopPrice               string
	TrailingDelta           int64
	IcebergQty              string
	NewOrderRespType        OrderRespType
	SelfTradePreventionMode SelfTradePreventionMode
	RecvWindow              int64
}

OrderRequest is a spot new-order payload. Quantity and Price are decimal strings.

type OrderRespType

type OrderRespType string

OrderRespType selects how much detail create-order returns.

const (
	OrderRespACK    OrderRespType = "ACK"
	OrderRespResult OrderRespType = "RESULT"
	OrderRespFull   OrderRespType = "FULL"
)

type OrderStatus

type OrderStatus string

OrderStatus is a Binance order status.

const (
	OrderStatusNew             OrderStatus = "NEW"
	OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED"
	OrderStatusFilled          OrderStatus = "FILLED"
	OrderStatusCanceled        OrderStatus = "CANCELED"
	OrderStatusPendingCancel   OrderStatus = "PENDING_CANCEL"
	OrderStatusRejected        OrderStatus = "REJECTED"
	OrderStatusExpired         OrderStatus = "EXPIRED"
	OrderStatusExpiredInMatch  OrderStatus = "EXPIRED_IN_MATCH"
)

type OrderType

type OrderType string

OrderType is a spot or futures order type.

const (
	OrderTypeLimit              OrderType = "LIMIT"
	OrderTypeMarket             OrderType = "MARKET"
	OrderTypeStopLoss           OrderType = "STOP_LOSS"
	OrderTypeStopLossLimit      OrderType = "STOP_LOSS_LIMIT"
	OrderTypeTakeProfit         OrderType = "TAKE_PROFIT"
	OrderTypeTakeProfitLimit    OrderType = "TAKE_PROFIT_LIMIT"
	OrderTypeLimitMaker         OrderType = "LIMIT_MAKER"
	OrderTypeStop               OrderType = "STOP"
	OrderTypeStopMarket         OrderType = "STOP_MARKET"
	OrderTypeTakeProfitMarket   OrderType = "TAKE_PROFIT_MARKET"
	OrderTypeTrailingStopMarket OrderType = "TRAILING_STOP_MARKET"
)

type PortfolioService

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

PortfolioService is Binance portfolio margin (papi).

func (*PortfolioService) Account

func (s *PortfolioService) Account(ctx context.Context, recv int64) (*FuturesAccount, error)

Account returns the unified portfolio account.

func (*PortfolioService) Balance

func (s *PortfolioService) Balance(ctx context.Context, asset string, recv int64) ([]FuturesBalance, error)

Balance returns portfolio-margin balances.

func (*PortfolioService) CMPositions

func (s *PortfolioService) CMPositions(ctx context.Context, symbol string, recv int64) ([]FuturesPosition, error)

CMPositions returns COIN-M position risk under portfolio margin.

func (*PortfolioService) CancelUMOrder

func (s *PortfolioService) CancelUMOrder(ctx context.Context, req CancelOrderRequest) (*FuturesOrder, error)

CancelUMOrder cancels a USD-M portfolio-margin order.

func (*PortfolioService) CloseListenKey

func (s *PortfolioService) CloseListenKey(ctx context.Context, listenKey string) error

CloseListenKey closes a portfolio-margin listen key.

func (*PortfolioService) CreateCMOrder

func (s *PortfolioService) CreateCMOrder(ctx context.Context, req FuturesOrderRequest) (*FuturesOrder, error)

CreateCMOrder places a COIN-M order on portfolio margin. Not retried.

func (*PortfolioService) CreateUMOrder

func (s *PortfolioService) CreateUMOrder(ctx context.Context, req FuturesOrderRequest) (*FuturesOrder, error)

CreateUMOrder places a USD-M order on portfolio margin. Not retried.

func (*PortfolioService) KeepListenKey

func (s *PortfolioService) KeepListenKey(ctx context.Context, listenKey string) error

KeepListenKey keepalives a portfolio-margin listen key.

func (*PortfolioService) ListenKey

func (s *PortfolioService) ListenKey(ctx context.Context) (string, error)

ListenKey creates a portfolio-margin user-data listen key.

func (*PortfolioService) Ping

func (s *PortfolioService) Ping(ctx context.Context) error

Ping tests papi connectivity.

func (*PortfolioService) SetUMLeverage

func (s *PortfolioService) SetUMLeverage(ctx context.Context, symbol string, leverage int, recv int64) error

SetUMLeverage changes USD-M leverage under portfolio margin. Not retried.

func (*PortfolioService) UMPositions

func (s *PortfolioService) UMPositions(ctx context.Context, symbol string, recv int64) ([]FuturesPosition, error)

UMPositions returns USD-M position risk under portfolio margin.

func (*PortfolioService) UserData

func (s *PortfolioService) UserData(ctx context.Context) (*Stream, error)

UserData opens a portfolio-margin user-data stream with listen-key keepalive.

type PositionMode

type PositionMode struct {
	DualSidePosition bool `json:"dualSidePosition"`
}

PositionMode is GET /fapi/v1/positionSide/dual.

type PositionSide

type PositionSide string

PositionSide is a futures position side.

const (
	PositionSideBoth  PositionSide = "BOTH"
	PositionSideLong  PositionSide = "LONG"
	PositionSideShort PositionSide = "SHORT"
)

type PriceLevel

type PriceLevel struct {
	Price    string
	Quantity string
}

PriceLevel is a [price, quantity] pair from an order book.

func (PriceLevel) MarshalJSON

func (p PriceLevel) MarshalJSON() ([]byte, error)

MarshalJSON emits ["price","qty"].

func (*PriceLevel) UnmarshalJSON

func (p *PriceLevel) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts ["price","qty"].

type QueryOrderRequest

type QueryOrderRequest struct {
	Symbol            string
	OrderID           int64
	OrigClientOrderID string
	RecvWindow        int64
}

QueryOrderRequest is GET /api/v3/order.

type RateLimit

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

RateLimit describes an exchange rate limit.

type RateLimitError

type RateLimitError struct {
	HTTPStatus int
	RetryAfter time.Duration
	UsedWeight int
	Err        error
}

RateLimitError wraps HTTP 429 / 418 with retry metadata.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

type RateLimiter

type RateLimiter interface {
	Wait(ctx context.Context, weight int) error
}

RateLimiter is invoked before a REST request. Weight is the Binance request weight (1 when unknown).

type RecentTradesRequest

type RecentTradesRequest struct {
	Symbol string
	Limit  int
}

RecentTradesRequest is GET /api/v3/trades.

type RequestError

type RequestError struct {
	Method string
	Path   string
	Err    error
}

RequestError is a transport failure that is not a decoded API body.

func (*RequestError) Error

func (e *RequestError) Error() string

func (*RequestError) Unwrap

func (e *RequestError) Unwrap() error

type RetryConfig

type RetryConfig struct {
	// MaxAttempts includes the original try. 1 disables retries.
	MaxAttempts int
	// MinBackoff is the first delay after a failed attempt.
	MinBackoff time.Duration
	// MaxBackoff caps exponential backoff.
	MaxBackoff time.Duration
	// Retry429 retries HTTP 429 after honoring Retry-After when present.
	Retry429 bool
}

RetryConfig controls retries for idempotent REST calls.

type RollingTicker

type RollingTicker struct {
	Symbol             string `json:"symbol"`
	PriceChange        string `json:"priceChange"`
	PriceChangePercent string `json:"priceChangePercent"`
	WeightedAvgPrice   string `json:"weightedAvgPrice"`
	OpenPrice          string `json:"openPrice"`
	HighPrice          string `json:"highPrice"`
	LowPrice           string `json:"lowPrice"`
	LastPrice          string `json:"lastPrice"`
	Volume             string `json:"volume"`
	QuoteVolume        string `json:"quoteVolume"`
	OpenTime           TimeMS `json:"openTime"`
	CloseTime          TimeMS `json:"closeTime"`
	FirstID            int64  `json:"firstId"`
	LastID             int64  `json:"lastId"`
	Count              int64  `json:"count"`
}

RollingTicker is a rolling-window ticker (`/api/v3/ticker`).

type RollingTickerRequest

type RollingTickerRequest struct {
	Symbol     string
	Symbols    []string
	WindowSize string
	Type       string
}

RollingTickerRequest is GET /api/v3/ticker.

type SelfTradePreventionMode

type SelfTradePreventionMode string

SelfTradePreventionMode is a spot STP mode.

const (
	STPExpireMaker     SelfTradePreventionMode = "EXPIRE_MAKER"
	STPExpireTaker     SelfTradePreventionMode = "EXPIRE_TAKER"
	STPExpireBoth      SelfTradePreventionMode = "EXPIRE_BOTH"
	STPNone            SelfTradePreventionMode = "NONE"
	STPDecrementCancel SelfTradePreventionMode = "DECREMENT"
)

type ServerTime

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

ServerTime is the /api/v3/time response.

type Side

type Side string

Side is an order side.

const (
	// SideBuy is a buy order.
	SideBuy Side = "BUY"
	// SideSell is a sell order.
	SideSell Side = "SELL"
)

type Signer

type Signer interface {
	Sign(payload string) (string, error)
}

Signer produces a Binance request signature for a canonical payload.

type SpotService

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

SpotService exposes Binance spot REST endpoints.

func (*SpotService) APITradingStatus

func (s *SpotService) APITradingStatus(ctx context.Context, recv int64) (*AccountAPIStatus, error)

APITradingStatus returns account API trading status (sapi).

func (*SpotService) Account

func (s *SpotService) Account(ctx context.Context, req AccountRequest) (*Account, error)

Account returns current account information.

func (*SpotService) AggTrades

func (s *SpotService) AggTrades(ctx context.Context, req AggTradesRequest) ([]AggTrade, error)

AggTrades returns compressed aggregate trades.

func (*SpotService) AllOrders

func (s *SpotService) AllOrders(ctx context.Context, req AllOrdersRequest) ([]Order, error)

AllOrders returns all account orders (active, canceled, filled) for a symbol.

func (*SpotService) AvgPrice

func (s *SpotService) AvgPrice(ctx context.Context, symbol string) (*AvgPrice, error)

AvgPrice returns the current average price for a symbol.

func (*SpotService) BookTicker

func (s *SpotService) BookTicker(ctx context.Context, req BookTickerRequest) ([]BookTicker, error)

BookTicker returns the best bid/ask for one or all symbols.

func (*SpotService) CancelAllOpenOrders

func (s *SpotService) CancelAllOpenOrders(ctx context.Context, symbol string, recv int64) ([]Order, error)

CancelAllOpenOrders cancels all open orders on a symbol.

func (*SpotService) CancelOrder

func (s *SpotService) CancelOrder(ctx context.Context, req CancelOrderRequest) (*Order, error)

CancelOrder cancels an active order.

func (*SpotService) CancelOrderList

func (s *SpotService) CancelOrderList(ctx context.Context, symbol string, orderListID int64, listClientOrderID string, recv int64) (*OrderList, error)

CancelOrderList cancels an OCO/OTO list.

func (*SpotService) CancelReplace

func (s *SpotService) CancelReplace(ctx context.Context, req CancelReplaceRequest) (*Order, error)

CancelReplace cancels an order and places a new one atomically.

func (*SpotService) CreateOCO

func (s *SpotService) CreateOCO(ctx context.Context, req OCORequest) (*OrderList, error)

CreateOCO places an OCO order list.

func (*SpotService) CreateOrder

func (s *SpotService) CreateOrder(ctx context.Context, req OrderRequest) (*Order, error)

CreateOrder submits a new spot order. Not retried (non-idempotent).

func (*SpotService) ExchangeInfo

func (s *SpotService) ExchangeInfo(ctx context.Context, req ExchangeInfoRequest) (*ExchangeInfo, error)

ExchangeInfo returns trading rules and symbol information.

func (*SpotService) GetOrder

func (s *SpotService) GetOrder(ctx context.Context, req QueryOrderRequest) (*Order, error)

GetOrder queries an order's status.

func (*SpotService) HistoricalTrades

func (s *SpotService) HistoricalTrades(ctx context.Context, req HistoricalTradesRequest) ([]Trade, error)

HistoricalTrades returns older public trades. Requires an API key.

func (*SpotService) Klines

func (s *SpotService) Klines(ctx context.Context, req KlinesRequest) ([]Kline, error)

Klines returns candlestick bars.

func (*SpotService) MyTrades

func (s *SpotService) MyTrades(ctx context.Context, req MyTradesRequest) ([]MyTrade, error)

MyTrades returns account trade history for a symbol.

func (*SpotService) OpenOrderLists

func (s *SpotService) OpenOrderLists(ctx context.Context, recv int64) ([]OrderList, error)

OpenOrderLists returns open OCO orders.

func (*SpotService) OpenOrders

func (s *SpotService) OpenOrders(ctx context.Context, req OpenOrdersRequest) ([]Order, error)

OpenOrders returns all open orders; omit Symbol to query all symbols (heavier weight).

func (*SpotService) OrderBook

func (s *SpotService) OrderBook(ctx context.Context, req OrderBookRequest) (*OrderBook, error)

OrderBook returns the current order book.

func (*SpotService) OrderCountUsage

func (s *SpotService) OrderCountUsage(ctx context.Context, recv int64) ([]OrderCount, error)

OrderCountUsage returns the current order count rate limits.

func (*SpotService) Ping

func (s *SpotService) Ping(ctx context.Context) error

Ping tests connectivity to the spot REST API.

func (*SpotService) RecentTrades

func (s *SpotService) RecentTrades(ctx context.Context, req RecentTradesRequest) ([]Trade, error)

RecentTrades returns the most recent trades.

func (*SpotService) RollingTicker

func (s *SpotService) RollingTicker(ctx context.Context, req RollingTickerRequest) ([]RollingTicker, error)

RollingTicker returns a rolling-window ticker (default 1d when omitted).

func (*SpotService) SAPIAccountStatus

func (s *SpotService) SAPIAccountStatus(ctx context.Context, recv int64) (*AccountStatus, error)

SAPIAccountStatus returns account status (sapi).

func (*SpotService) ServerTime

func (s *SpotService) ServerTime(ctx context.Context) (int64, error)

ServerTime returns the Binance server time in milliseconds.

func (*SpotService) TestOrder

func (s *SpotService) TestOrder(ctx context.Context, req OrderRequest) error

TestOrder validates a new order without sending it to the matching engine.

func (*SpotService) Ticker24h

func (s *SpotService) Ticker24h(ctx context.Context, req Ticker24hRequest) ([]Ticker24h, error)

Ticker24h returns 24-hour rolling window price change statistics.

func (*SpotService) TickerPrice

func (s *SpotService) TickerPrice(ctx context.Context, req TickerPriceRequest) ([]SymbolPrice, error)

TickerPrice returns the latest price for one or all symbols.

func (*SpotService) UIKlines

func (s *SpotService) UIKlines(ctx context.Context, req KlinesRequest) ([]Kline, error)

UIKlines returns candlesticks optimized for presentation.

type StdLogger

type StdLogger struct {
	Printf func(format string, args ...any)
}

StdLogger adapts a printf-style function (for example log.Printf) to Logger.

func (StdLogger) Debug

func (l StdLogger) Debug(msg string, args ...any)

func (StdLogger) Error

func (l StdLogger) Error(msg string, args ...any)

func (StdLogger) Info

func (l StdLogger) Info(msg string, args ...any)

type Stream

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

Stream is a reconnecting combined WebSocket subscription.

func (*Stream) Close

func (s *Stream) Close() error

Close stops reconnects and closes the event channel.

func (*Stream) Events

func (s *Stream) Events() <-chan Event

Events returns the receive-only event channel. Do not mix with Next.

func (*Stream) Healthy

func (s *Stream) Healthy() bool

Healthy reports whether a message was received recently (2 minutes).

func (*Stream) Next

func (s *Stream) Next(ctx context.Context) (Event, error)

Next waits for the next event or ctx cancellation.

type StreamSpec

type StreamSpec struct {
	Name   string
	Market Market
	// contains filtered or unexported fields
}

StreamSpec names a Binance market-data or user-data stream.

func StreamAggTrade

func StreamAggTrade(symbol string) StreamSpec

StreamAggTrade is `{symbol}@aggTrade`.

func StreamBookTicker

func StreamBookTicker(symbol string) StreamSpec

StreamBookTicker is `{symbol}@bookTicker`.

func StreamCoinFuturesTrade

func StreamCoinFuturesTrade(symbol string) StreamSpec

StreamCoinFuturesTrade tags a stream as COIN-M futures.

func StreamDepth

func StreamDepth(symbol string) StreamSpec

StreamDepth is `{symbol}@depth` (diff book).

func StreamDepth100ms

func StreamDepth100ms(symbol string) StreamSpec

StreamDepth100ms is `{symbol}@depth@100ms`.

func StreamFuturesTrade

func StreamFuturesTrade(symbol string) StreamSpec

StreamFuturesTrade tags a stream as USD-M futures.

func StreamKline

func StreamKline(symbol string, interval Interval) StreamSpec

StreamKline is `{symbol}@kline_{interval}`.

func StreamMiniTicker

func StreamMiniTicker(symbol string) StreamSpec

StreamMiniTicker is `{symbol}@miniTicker`.

func StreamPartialDepth

func StreamPartialDepth(symbol string, level DepthLevel, ms100 bool) StreamSpec

StreamPartialDepth is `{symbol}@depth{level}` or `@depth{level}@100ms`.

func StreamTicker

func StreamTicker(symbol string) StreamSpec

StreamTicker is `{symbol}@ticker`.

func StreamTrade

func StreamTrade(symbol string) StreamSpec

StreamTrade is `{symbol}@trade`.

type SubAccount

type SubAccount struct {
	Email                       string `json:"email"`
	IsFreeze                    bool   `json:"isFreeze"`
	CreateTime                  TimeMS `json:"createTime"`
	IsManagedSubAccount         bool   `json:"isManagedSubAccount"`
	IsAssetManagementSubAccount bool   `json:"isAssetManagementSubAccount"`
}

SubAccount is one sub-account list row.

type SubAccountService

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

SubAccountService covers a useful subset of sub-account endpoints.

func (*SubAccountService) Assets

func (s *SubAccountService) Assets(ctx context.Context, email string, recv int64) ([]Balance, error)

Assets returns a sub-account's spot assets.

func (*SubAccountService) List

func (s *SubAccountService) List(ctx context.Context, email string, recv int64) ([]SubAccount, error)

List returns sub-accounts.

func (*SubAccountService) UniversalTransfer

UniversalTransfer transfers between master/sub accounts. Not retried.

type SubAccountTransferRequest

type SubAccountTransferRequest struct {
	FromEmail       string
	ToEmail         string
	FromAccountType string
	ToAccountType   string
	Asset           string
	Amount          string
	RecvWindow      int64
}

SubAccountTransferRequest is POST /sapi/v1/sub-account/universalTransfer.

type SymbolFilter

type SymbolFilter struct {
	FilterType       string `json:"filterType"`
	MinPrice         string `json:"minPrice"`
	MaxPrice         string `json:"maxPrice"`
	TickSize         string `json:"tickSize"`
	MinQty           string `json:"minQty"`
	MaxQty           string `json:"maxQty"`
	StepSize         string `json:"stepSize"`
	MinNotional      string `json:"minNotional"`
	ApplyMinToMarket bool   `json:"applyMinToMarket"`
	MaxNumOrders     int    `json:"maxNumOrders"`
}

SymbolFilter is a lot/price/notional filter. Unknown fields stay in Extra.

type SymbolInfo

type SymbolInfo 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"`
	QuoteAssetPrecision             int            `json:"quoteAssetPrecision"`
	OrderTypes                      []OrderType    `json:"orderTypes"`
	IcebergAllowed                  bool           `json:"icebergAllowed"`
	OCOAllowed                      bool           `json:"ocoAllowed"`
	OTOAllowed                      bool           `json:"otoAllowed"`
	QuoteOrderQtyMarketAllowed      bool           `json:"quoteOrderQtyMarketAllowed"`
	AllowTrailingStop               bool           `json:"allowTrailingStop"`
	CancelReplaceAllowed            bool           `json:"cancelReplaceAllowed"`
	IsSpotTradingAllowed            bool           `json:"isSpotTradingAllowed"`
	IsMarginTradingAllowed          bool           `json:"isMarginTradingAllowed"`
	Filters                         []SymbolFilter `json:"filters"`
	Permissions                     []string       `json:"permissions"`
	DefaultSelfTradePreventionMode  string         `json:"defaultSelfTradePreventionMode"`
	AllowedSelfTradePreventionModes []string       `json:"allowedSelfTradePreventionModes"`
}

SymbolInfo is one tradable symbol.

type SymbolPrice

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

SymbolPrice is a symbol price ticker.

type SystemStatus

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

SystemStatus is GET /sapi/v1/system/status.

type Ticker24h

type Ticker24h 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"`
	BidQty             string `json:"bidQty"`
	AskPrice           string `json:"askPrice"`
	AskQty             string `json:"askQty"`
	OpenPrice          string `json:"openPrice"`
	HighPrice          string `json:"highPrice"`
	LowPrice           string `json:"lowPrice"`
	Volume             string `json:"volume"`
	QuoteVolume        string `json:"quoteVolume"`
	OpenTime           TimeMS `json:"openTime"`
	CloseTime          TimeMS `json:"closeTime"`
	FirstID            int64  `json:"firstId"`
	LastID             int64  `json:"lastId"`
	Count              int64  `json:"count"`
}

Ticker24h is a 24-hour ticker statistics object.

type Ticker24hRequest

type Ticker24hRequest struct {
	Symbol  string
	Symbols []string
	Type    string
}

Ticker24hRequest is GET /api/v3/ticker/24hr.

type TickerEvent

type TickerEvent struct {
	EventType          string `json:"e"`
	EventTime          TimeMS `json:"E"`
	Symbol             string `json:"s"`
	PriceChange        string `json:"p"`
	PriceChangePercent string `json:"P"`
	WeightedAvgPrice   string `json:"w"`
	FirstTradePrice    string `json:"x"`
	LastPrice          string `json:"c"`
	LastQty            string `json:"Q"`
	BestBidPrice       string `json:"b"`
	BestBidQty         string `json:"B"`
	BestAskPrice       string `json:"a"`
	BestAskQty         string `json:"A"`
	OpenPrice          string `json:"o"`
	HighPrice          string `json:"h"`
	LowPrice           string `json:"l"`
	Volume             string `json:"v"`
	QuoteVolume        string `json:"q"`
	OpenTime           TimeMS `json:"O"`
	CloseTime          TimeMS `json:"C"`
	FirstTradeID       int64  `json:"F"`
	LastTradeID        int64  `json:"L"`
	Count              int64  `json:"n"`
}

TickerEvent is a 24hr ticker stream payload.

type TickerPriceRequest

type TickerPriceRequest struct {
	Symbol  string
	Symbols []string
}

TickerPriceRequest is GET /api/v3/ticker/price.

type TimeInForce

type TimeInForce string

TimeInForce controls how long an order remains active.

const (
	TimeInForceGTC TimeInForce = "GTC"
	TimeInForceIOC TimeInForce = "IOC"
	TimeInForceFOK TimeInForce = "FOK"
	TimeInForceGTX TimeInForce = "GTX"
	TimeInForceGTD TimeInForce = "GTD"
)

type TimeMS

type TimeMS int64

TimeMS is a Unix timestamp in milliseconds.

func (TimeMS) Time

func (t TimeMS) Time() time.Time

Time converts to time.Time in UTC.

type Trade

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

Trade is a public recent/historical trade.

type TradeEvent

type TradeEvent struct {
	EventType     string `json:"e"`
	EventTime     TimeMS `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"`
	TradeTime     TimeMS `json:"T"`
	IsBuyerMaker  bool   `json:"m"`
}

TradeEvent is a raw trade stream payload.

type TradeFee

type TradeFee struct {
	Symbol          string `json:"symbol"`
	MakerCommission string `json:"makerCommission"`
	TakerCommission string `json:"takerCommission"`
}

TradeFee is GET /sapi/v1/asset/tradeFee.

type TransferRequest

type TransferRequest struct {
	Asset      string
	Amount     string
	Type       int // 1: main->margin, 2: margin->main
	RecvWindow int64
}

TransferRequest is POST /sapi/v1/margin/transfer (cross).

type TransferType

type TransferType string

TransferType is a universal (wallet) transfer type.

const (
	TransferMainToUMFuture   TransferType = "MAIN_UMFUTURE"
	TransferMainToCMFuture   TransferType = "MAIN_CMFUTURE"
	TransferMainToMargin     TransferType = "MAIN_MARGIN"
	TransferUMFutureToMain   TransferType = "UMFUTURE_MAIN"
	TransferCMFutureToMain   TransferType = "CMFUTURE_MAIN"
	TransferMarginToMain     TransferType = "MARGIN_MAIN"
	TransferMarginToUMFuture TransferType = "MARGIN_UMFUTURE"
	TransferUMFutureToMargin TransferType = "UMFUTURE_MARGIN"
	TransferMainToFunding    TransferType = "MAIN_FUNDING"
	TransferFundingToMain    TransferType = "FUNDING_MAIN"
)

type UniversalTransferRequest

type UniversalTransferRequest struct {
	Type       TransferType
	Asset      string
	Amount     string
	FromSymbol string
	ToSymbol   string
	RecvWindow int64
}

UniversalTransferRequest is POST /sapi/v1/asset/transfer.

type UniversalTransferResult

type UniversalTransferResult struct {
	TranID int64 `json:"tranId"`
}

UniversalTransferResult is a transfer id.

type UserStreamService

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

UserStreamService manages spot listen keys.

func (*UserStreamService) Close

func (s *UserStreamService) Close(ctx context.Context, listenKey string) error

Close invalidates a listen key.

func (*UserStreamService) Create

func (s *UserStreamService) Create(ctx context.Context) (string, error)

Create opens a new listen key (valid ~60 minutes).

func (*UserStreamService) Keepalive

func (s *UserStreamService) Keepalive(ctx context.Context, listenKey string) error

Keepalive extends a listen key's validity.

type WSAPI

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

WSAPI is the spot WebSocket API (wss://ws-api.binance.com/ws-api/v3).

func (*WSAPI) CancelOrder

func (w *WSAPI) CancelOrder(ctx context.Context, req CancelOrderRequest) (*Order, error)

CancelOrder cancels an order over the WebSocket API.

func (*WSAPI) Close

func (w *WSAPI) Close() error

Close closes the underlying WebSocket API connection.

func (*WSAPI) CreateFuturesOrder

func (w *WSAPI) CreateFuturesOrder(ctx context.Context, req FuturesOrderRequest) (*FuturesOrder, error)

CreateFuturesOrder places a USD-M order over the futures WebSocket API.

func (*WSAPI) CreateOrder

func (w *WSAPI) CreateOrder(ctx context.Context, req OrderRequest) (*Order, error)

CreateOrder places an order over the WebSocket API. Not retried.

func (*WSAPI) GetAccount

func (w *WSAPI) GetAccount(ctx context.Context) (*Account, error)

GetAccount returns spot account information over the WebSocket API.

func (*WSAPI) GetOrder

func (w *WSAPI) GetOrder(ctx context.Context, req QueryOrderRequest) (*Order, error)

GetOrder queries an order over the WebSocket API.

func (*WSAPI) GetSymbolTicker

func (w *WSAPI) GetSymbolTicker(ctx context.Context, symbol string) (*SymbolPrice, error)

GetSymbolTicker returns a price ticker over the WebSocket API.

func (*WSAPI) Ping

func (w *WSAPI) Ping(ctx context.Context) error

Ping tests WebSocket API connectivity.

func (*WSAPI) ServerTime

func (w *WSAPI) ServerTime(ctx context.Context) (int64, error)

ServerTime returns exchange time over the WebSocket API.

func (*WSAPI) TestOrder

func (w *WSAPI) TestOrder(ctx context.Context, req OrderRequest) error

TestOrder validates an order over the WebSocket API.

type WalletService

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

WalletService covers capital / wallet REST endpoints (sapi).

func (*WalletService) APIRestrictions

func (s *WalletService) APIRestrictions(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

APIRestrictions returns the current API key permission set. extra may be nil.

func (*WalletService) APITradingStatus

func (s *WalletService) APITradingStatus(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

APITradingStatus returns account trading-lock status. extra may be nil.

func (*WalletService) AccountSnapshot

func (s *WalletService) AccountSnapshot(ctx context.Context, req AccountSnapshotRequest) (*AccountSnapshot, error)

AccountSnapshot returns a daily account snapshot.

func (*WalletService) AssetDetail

func (s *WalletService) AssetDetail(ctx context.Context, asset string, recv int64) (AssetDetail, error)

AssetDetail returns asset deposit/withdraw details.

func (*WalletService) AssetDividend

func (s *WalletService) AssetDividend(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

AssetDividend returns asset dividend (distribution) records. extra may be nil.

func (*WalletService) Coins

func (s *WalletService) Coins(ctx context.Context, recv int64) ([]CoinInfo, error)

Coins returns all coins' configuration and balances.

func (*WalletService) DepositAddress

func (s *WalletService) DepositAddress(ctx context.Context, req DepositAddressRequest) (*DepositAddress, error)

DepositAddress returns a deposit address for coin/network.

func (*WalletService) DepositHistory

func (s *WalletService) DepositHistory(ctx context.Context, req DepositHistoryRequest) ([]Deposit, error)

DepositHistory returns deposit records.

func (*WalletService) DustLog

func (s *WalletService) DustLog(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

DustLog returns small-balance conversion history. extra may be nil.

func (*WalletService) DustTransfer

func (s *WalletService) DustTransfer(ctx context.Context, assets []string, recv int64) (jsonRawSnapshot, error)

DustTransfer converts small balances to BNB. Not retried.

func (*WalletService) SpotDelistSchedule

func (s *WalletService) SpotDelistSchedule(ctx context.Context, recv int64, extra map[string]string) (json.RawMessage, error)

SpotDelistSchedule returns upcoming spot delistings. extra may be nil.

func (*WalletService) SystemStatus

func (s *WalletService) SystemStatus(ctx context.Context) (*SystemStatus, error)

SystemStatus returns 0 when the system is normal.

func (*WalletService) TradeFee

func (s *WalletService) TradeFee(ctx context.Context, symbol string, recv int64) ([]TradeFee, error)

TradeFee returns trade fees, optionally filtered by symbol.

func (*WalletService) UniversalTransfer

UniversalTransfer moves assets between Binance wallets. Not retried.

func (*WalletService) Withdraw

Withdraw submits a withdrawal. This call is not retried.

func (*WalletService) WithdrawHistory

func (s *WalletService) WithdrawHistory(ctx context.Context, req WithdrawHistoryRequest) ([]Withdrawal, error)

WithdrawHistory returns withdrawal records.

type WebSocketService

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

WebSocketService is the python-binance-style stream facade.

func (*WebSocketService) AggTrade

func (s *WebSocketService) AggTrade(ctx context.Context, symbol string) (*Stream, error)

AggTrade opens `{symbol}@aggTrade`.

func (*WebSocketService) BookTicker

func (s *WebSocketService) BookTicker(ctx context.Context, symbol string) (*Stream, error)

BookTicker opens `{symbol}@bookTicker`.

func (*WebSocketService) Combined

func (s *WebSocketService) Combined(ctx context.Context, specs ...StreamSpec) (*Stream, error)

Combined opens a combined stream of specs on the same market.

func (*WebSocketService) Depth

func (s *WebSocketService) Depth(ctx context.Context, symbol string) (*Stream, error)

Depth opens `{symbol}@depth`.

func (*WebSocketService) FuturesTrade

func (s *WebSocketService) FuturesTrade(ctx context.Context, symbol string) (*Stream, error)

FuturesTrade opens a USD-M trade stream.

func (*WebSocketService) Kline

func (s *WebSocketService) Kline(ctx context.Context, symbol string, interval Interval) (*Stream, error)

Kline opens `{symbol}@kline_{interval}`.

func (*WebSocketService) MiniTicker

func (s *WebSocketService) MiniTicker(ctx context.Context, symbol string) (*Stream, error)

MiniTicker opens `{symbol}@miniTicker`.

func (*WebSocketService) Ticker

func (s *WebSocketService) Ticker(ctx context.Context, symbol string) (*Stream, error)

Ticker opens `{symbol}@ticker`.

func (*WebSocketService) Trade

func (s *WebSocketService) Trade(ctx context.Context, symbol string) (*Stream, error)

Trade opens `{symbol}@trade`.

func (*WebSocketService) UserData

func (s *WebSocketService) UserData(ctx context.Context) (*Stream, error)

UserData opens the spot user-data stream (listen key + keepalive).

type WebsocketError

type WebsocketError struct {
	Op  string
	Err error
}

WebsocketError is a stream-level failure.

func (*WebsocketError) Error

func (e *WebsocketError) Error() string

func (*WebsocketError) Unwrap

func (e *WebsocketError) Unwrap() error

type WeightLimiter

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

WeightLimiter is a simple token-bucket limiter keyed to request weight.

func NewWeightLimiter

func NewWeightLimiter(weight int, window time.Duration) *WeightLimiter

NewWeightLimiter allows `weight` units per `window` (for example 1200/minute).

func (*WeightLimiter) Wait

func (l *WeightLimiter) Wait(ctx context.Context, weight int) error

Wait blocks until `weight` tokens are available.

type WithdrawHistoryRequest

type WithdrawHistoryRequest struct {
	Coin            string
	WithdrawOrderID string
	Status          int
	StartTime       int64
	EndTime         int64
	Offset          int
	Limit           int
	RecvWindow      int64
}

WithdrawHistoryRequest is GET /sapi/v1/capital/withdraw/history.

type WithdrawRequest

type WithdrawRequest struct {
	Coin               string
	WithdrawOrderID    string
	Network            string
	Address            string
	AddressTag         string
	Amount             string
	TransactionFeeFlag bool
	Name               string
	WalletType         int
	RecvWindow         int64
}

WithdrawRequest is POST /sapi/v1/capital/withdraw/apply.

Security: this moves real funds. Restrict API keys by IP, enable withdrawal whitelist, and never commit credentials. This method is not retried.

type WithdrawResult

type WithdrawResult struct {
	ID string `json:"id"`
}

WithdrawResult is the withdraw ticket id.

type Withdrawal

type Withdrawal struct {
	ID              string `json:"id"`
	Amount          string `json:"amount"`
	TransactionFee  string `json:"transactionFee"`
	Coin            string `json:"coin"`
	Status          int    `json:"status"`
	Address         string `json:"address"`
	TxID            string `json:"txId"`
	ApplyTime       string `json:"applyTime"`
	Network         string `json:"network"`
	TransferType    int    `json:"transferType"`
	WithdrawOrderID string `json:"withdrawOrderId"`
	Info            string `json:"info"`
	ConfirmNo       int    `json:"confirmNo"`
	WalletType      int    `json:"walletType"`
	TxKey           string `json:"txKey"`
}

Withdrawal is one withdraw history row.

type WorkingType

type WorkingType string

WorkingType is a futures stop working type.

const (
	WorkingTypeMarkPrice     WorkingType = "MARK_PRICE"
	WorkingTypeContractPrice WorkingType = "CONTRACT_PRICE"
)

Directories

Path Synopsis
examples
account command
futures_order command
margin command
order command
test_order command
testnet command
ticker command
user_stream command
websocket_depth command
websocket_trade command
wsapi command
internal
generator command
Command generator writes zz_generated.go from endpoints.json.
Command generator writes zz_generated.go from endpoints.json.

Jump to

Keyboard shortcuts

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