API Binance

Binance

 

Binance is an international multi-language cryptocurrency exchange. It offers some APIs to access Binance data. The following APIs are supported:

 

  1. WebSocket streams: allows to subscribe to some methods and get data in real-time. Events are pushed to clients by server to subscribers. Uses WebSocket as protocol.
  2. UserData stream: subscribed clients get account details. Requires an API key to authenticate and uses WebSocket as protocol.
  3. REST API: Requires an API Key and Secret to authenticate and uses HTTPs as protocol.
    1. Market Data
    2. Account and Trading Data
    3. Wallet
  4. Futures: WebSocket Futures Market Data Streams are supported through the Binance Futures Client API.

 

The client supports Binance.us too, the following APIs are supported:

 

  1. WebSocket streams: allows to subscribe to some methods and get data in real-time. Events are pushed to clients by server to subscribers. Uses WebSocket as protocol.
  2. UserData stream: subscribed clients get account details. Requires an API key to authenticate and uses WebSocket as protocol.
  3. REST API: clients can request to server market and account data. Requires an API Key and Secret to authenticate and uses HTTPs as protocol.

 

Properties

Binance API has 2 types of methods: public and private. Public methods can be accessed without authentication, example: get ticker prices. Only are only private and related to user data, those methods requires the use of Binance API keys.

 

 

 

 

Most common uses

 

WebSocket Stream API

Base endpoint is wss://stream.binance.com:9443, client can subscribe / unsubscribe from events after a successful connection.

The following Subscription / Unsubscription methods are supported.

 

Method Parameters Description
AggregateTrades Symbol push trade information that is aggregated for a single taker order
Trades Symbol push raw trade information; each trade has a unique buyer and seller
KLine Symbol, Interval push updates to the current klines/candlestick every second, minute, hour...
MiniTicker Symbol 24hr rolling window mini-ticker statistics. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
AllMiniTickers   24hr rolling window mini-ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.
Ticker Symbol 24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
AllMarketTickers   24hr rolling window ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array.
BookTicker Symbol Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.
AllBookTickers   Pushes any update to the best bid or ask's price or quantity in real-time for all symbols.
PartialBookDepth Symbol, Depth Top <levels> bids and asks, pushed every second. Valid <levels> are 5, 10, or 20.
DiffDepth Symbol Order book price and quantity depth updates used to locally manage an order book.

 

After a successful subcription / unsubscription, client receives a message about it, where id is the result of Subscribed / Unsubscribed method.

 


{
  "result": null,
  "id": 1
}

 

User Data Stream API

Requires a valid ApiKey obtained from your binance account, and ApiKey must be set in Binance.ApiKey property of component.

 

The following data is pushed to client every time there is a change. There is no need to subscribe to any method, this is done automatically if you set a valid ApiKey.

 

Method Description
Account Update Account state is updated with the outboundAccountInfo event.
Balance Update

Balance Update occurs during the following:

 

  • Deposits or withdrawals from the account
  • Transfer of funds between accounts (e.g. Spot to Margin)
Order Update Orders are updated with the executionReport event.

 

 

REST API

The base endpoint is: https://api.binance.com. All endpoints return either a JSON object or array. Data is returned in ascending order. Oldest first, newest last.

 

Access to the REST API Options, using the property REST_API.BinanceOptions.

 

 

Public API EndPoints

 

These endpoints can be accessed without any authorization.

 

General EndPoints

 

Method Parameters Description
Ping   Test connectivity to the Rest API.
GetServerTime   Test connectivity to the Rest API and get the current server time.
GetExchangeInformation   Current exchange trading rules and symbol information

 

 

Market Data EndPoints

 

Method Parameters Description
GetOrderBook Symbol Get Order Book.
GetTrades Symbol Get recent trades
GetHistoricalTrades Symbol Get older trades.
GetAggregateTrades Symbol Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.
GetKLines Symbol, Interval Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
GetAveragePrice Symbol Current average price for a symbol.
Get24hrTicker Symbol 24 hour rolling window price change statistics. Careful when accessing this with no symbol.
GetPriceTicker Symbol Latest price for a symbol.
GetPriceTickers Symbols Latest price for an array of symbols. Example: ["BTCUSDT","BNBUSDT"]
GetBookTicker Symbol Best price/qty on the order book for a symbol or symbols.

 

 

 

Private API EndPoints

 

Requires an APIKey and APISecret to get authorized by server.

 

Account Data EndPoints

 

Method Parameters Description
NewOrder Symbol, Side, Type Send in a new order.
PlaceMarketOrder Side, Symbol, Quantity Places a New Market Order
PlaceMarketQuoteOrder Side, Symbol, QuoteOrderQty Places a New Market Quote Order
PlaceLimitOrder Side, Symbol, Quantity, LimitPrice Places a New Limit Order
PlaceStopOrder Side, Symbol, Quantity, StopPrice, LimitPrice Places a New Stop Order
PlaceStopTrailingOrder Side, Symbol, Quantity, TrailingDelta, LimitPrice Places a New Stop Trailing Order
PlaceTakeProfitOrder Side, Symbol, Quantity, StopPrice, LimitPrice Places a New Take Profit Order
PlaceTakeProfitTrailingOrder Side, Symbol, Quantity, TrailingDelta, LimitPrice Places a New Take ProfitTrailing Order
PlaceLimitMakerOrder Side, Symbol, Quantity Places a New Limit Market Order
TestNewOrder Symbol, Side, Type Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.
QueryOrder Symbol Check an order's status.
CancelOrder Symbol Cancel an active order. Cancel an active order. Either OrderId or OrigClientOrderId must be sent.
CancelAllOpenOrders Symbol (optional)  
GetOpenOrders   Get all open orders on a symbol. Careful when accessing this with no symbol.
GetAllOrders Symbol Get all account orders; active, canceled, or filled.
NewOCO Symbol, Side, Quantity, Price, StopPrice Send in a new OCO
CancelOCO Symbol Cancel an entire Order List
QueryOCO Symbol Retrieves a specific OCO based on provided optional parameters
GetAllOCO   Retrieves all OCO based on provided optional parameters
GetOpenOCO   Get All Open OCO.
GetAccountInformation   Get current account information.
GetAccountTradeList Symbol Get trades for a specific account and symbol.

 

 

 

Convert EndPoints

 

Method Parameters Description
GetAllConvertPairs FromAsset, ToAsset Query for all convertible token pairs and the tokens’ respective upper/lower limits
GetConvertAssetInfo   Query for supported asset’s precision information
SendConvertQuoteRequest FromAsset, ToAsset Request a quote for the requested token pairs
AcceptConvertQuote QuoteId Accept the offered quote by quote ID.
GetConvertOrderStatus OrderId or QuoteId Query order status by order ID.
PlaceConvertLimitOrder BaseAsset, QuoteAsset, Side, LimitPrice

Enable users to place a limit order.

baseAsset or quoteAsset can be determined via exchangeInfo endpoint.
Limit price is defined from baseAsset to quoteAsset.
Either baseAmount or quoteAmount is used.

CancelConvertLimitOrder OrderId Enable users to cancel a limit order
GetConvertLimitOpenOrders   Enable users to query for all existing limit orders
GetConvertTradeHistory StartTime, EndTime The max interval between startTime and endTime is 30 days.

 

 

 

Wallet EndPoints

(*wallet endpoints only work with production server, not demo)

 

Method Description
GetWalletSystemStatus Fetch system status.
GetWalletAllCoinsInformation Get information of coins (available for deposit and withdraw) for user.
GetWalletDailyAccountSnapshot Type: "SPOT", "MARGIN", "FUTURES"
  • The query time period must be less then 30 days
  • Support query within the last one month only
  • If startTimeand endTime not sent, return records of the last 7 days by default
SetWalletDisableFastWithdrawSwitch This request will disable fastwithdraw switch under your account.
You need to enable "trade" option for the api key which requests this endpoint.
SetWalletEnableFastWithdrawSwitch This request will enable fastwithdraw switch under your account.
You need to enable "trade" option for the api key which requests this endpoint.
When Fast Withdraw Switch is on, transferring funds to a Binance account will be done instantly. There is no on-chain transaction, no transaction ID and no withdrawal fee.
WalletWithdraw

Submit a withdraw request.

 

GetWalletDepositHistory Fetch deposit history.
GetWalletWithdrawHistory Fetch Withdraw history.
GetWalletDepositAddress Fetch deposit address with network.
GetWalletAccountStatus Fetch account status detail.
GetWalletAccountAPITradingStatus Fetch account api trading status detail.
GetWalletDustLog Only return last 100 records
Only return records after 2020/12/01
GetWalletAssetsConvertedBNB  
WalletDustTransfer

Convert dust assets to BNB.

You need to openEnable Spot & Margin Trading permission for the API Key which requests this endpoint.

GetWalletAssetDividendRecord Query asset dividend record.
GetWalletAssetDetail Fetch details of assets supported on Binance.
GetWalletTradeFee Fetch trade fee
WalletUserUniversalTransfer

You need to enable Permits Universal Transfer option for the API Key which requests this endpoint.MAIN_UMFUTURE Spot account transfer to USDⓈ-M Futures account

ENUM of Type:

  • MAIN_CMFUTURE Spot account transfer to COIN-M Futures account
  • MAIN_MARGIN Spot account transfer to Margin(cross)account
  • UMFUTURE_MAIN USDⓈ-M Futures account transfer to Spot account
  • UMFUTURE_MARGIN USDⓈ-M Futures account transfer to Margin(cross)account
  • CMFUTURE_MAIN COIN-M Futures account transfer to Spot account
  • CMFUTURE_MARGIN COIN-M Futures account transfer to Margin(cross) account
  • MARGIN_MAIN Margin(cross)account transfer to Spot account
  • MARGIN_UMFUTURE Margin(cross)account transfer to USDⓈ-M Futures
  • MARGIN_CMFUTURE Margin(cross)account transfer to COIN-M Futures
  • ISOLATEDMARGIN_MARGIN Isolated margin account transfer to Margin(cross) account
  • MARGIN_ISOLATEDMARGIN Margin(cross) account transfer to Isolated margin account
  • ISOLATEDMARGIN_ISOLATEDMARGIN Isolated margin account transfer to Isolated margin account
  • MAIN_FUNDING Spot account transfer to Funding account
  • FUNDING_MAIN Funding account transfer to Spot account
  • FUNDING_UMFUTURE Funding account transfer to UMFUTURE account
  • UMFUTURE_FUNDING UMFUTURE account transfer to Funding account
  • MARGIN_FUNDING MARGIN account transfer to Funding account
  • FUNDING_MARGIN Funding account transfer to Margin account
  • FUNDING_CMFUTURE Funding account transfer to CMFUTURE account
  • CMFUTURE_FUNDING CMFUTURE account transfer to Funding account
GetWalletQueryUserUniversalTransferHistory
  • fromSymbol must be sent when type are ISOLATEDMARGIN_MARGIN and ISOLATEDMARGIN_ISOLATEDMARGIN
  • toSymbol must be sent when type are MARGIN_ISOLATEDMARGIN and ISOLATEDMARGIN_ISOLATEDMARGIN
  • Support query within the last 6 months only
  • If startTimeand endTime not sent, return records of the last 7 days by default
GetWalletFundingWallet Currently supports querying the following business assets:Binance Pay, Binance Card, Binance Gift Card, Stock Token
GetWalletUserAsset Get user assets, just for positive data.
GetWalletApiKeyPermission  

 

 

Events

Binance Messages are received in TsgcWebSocketClient component, you can use the following events:

 

OnConnect

After a successful connection to Binance server.

OnDisconnect

After a disconnection from Binance server

OnMessage

Messages sent by server to client are handled in this event.

OnError

If there is any error in protocol, this event will be called.

OnException

If there is an unhandled exception, this event will be called.

 

Additionally, there is a specific event in Binance API Component, called OnBinanceHTTPException, which is raised every time there is an error calling an HTTP Request (REST API or WebSocket User Stream).

 

(*) Due to changes in Binance Servers, Indy versions before Rad Studio 10.1, won't be able to connect to Test Servers. This issue doesn't affect to Enterprise Edition or if the Indy version has been upgraded to latest.