API Binance
Binance is an international multi-language cryptocurrency exchange. It offers some APIs to access Binance data. The following APIs are supported:
- 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.
- UserData stream: subscribed clients get account details. Requires an API key to authenticate and uses WebSocket as protocol.
- REST API: clients can request to server market and account data. Requires an API Key and Secret to authenticate and uses HTTPs as protocol.
- Futures: WebSocket Futures Market Data Streams are supported through the Binance Futures Client API.
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.
- ApiKey: you can request a new api key in your binance account, just copy the value to this property.
- ApiSecret: API secret is only required for REST_API, websocket api only requires ApiKey for some methods.
- TestNet: if enabled it will connect to Binance Demo Account (by default false).
- HTTPLogOptions: stores in a text file a log of HTTP requests
- Enabled: if enabled, will store all HTTP requests of WebSocket API.
- FileName: full path of filename where logs will be stored
- REST: stores in a text file a log of REST API requests
- Enabled: if enabled, will store all HTTP Requests of REST API.
- FileName: full path of filename where logs will be stored.
- HTTPLogOptions: stores in a text file a log of HTTP requests
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 bids and asks, pushed every second. Valid 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.
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 | |
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.
Public API EndPoints
These endpoints can be accessed without any authorization.
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 or symbols. |
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 |
PlaceLimitOrder | Side, Symbol, Quantity, LimitPrice | Places a New Limit Order |
PlaceStopOrder | Side, Symbol, Quantity, StopPrice, LimitPrice | Places a New Stop 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. |
Events
Binance Messages are received in TsgcWebSocketClient component, you can use the following events:
After a successful connection to Binance server.
After a disconnection from Binance server
Messages sent by server to client are handled in this event.
If there is any error in protocol, this event will be called.
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).
Источник
User data stream binance
Table of Contents generated with DocToc
User Data Streams for Binance (2020-07-09)
General WSS information
- The base API endpoint is: https://api.binance.us
- A User Data Stream listenKey is valid for 60 minutes after creation.
- Doing a PUT on a listenKey will extend its validity for 60 minutes.
- Doing a DELETE on a listenKey will close the stream and invalidate the listenKey .
- Doing a POST on an account with an active listenKey will return the currently active listenKey and extend its validity for 60 minutes.
- The base websocket endpoint is: wss://stream.binance.us:9443
- User Data Streams are accessed at /ws/ or /stream?streams=
- A single connection to stream.binance.us is only valid for 24 hours; expect to be disconnected at the 24 hour mark
Create a listenKey
Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active listenKey , that listenKey will be returned and its validity will be extended for 60 minutes.
Weight: 1
Parameters: NONE
Response:
Ping/Keep-alive a listenKey
Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It’s recommended to send a ping about every 30 minutes.
Weight: 1
Parameters:
Name | Type | Mandatory | Description |
---|---|---|---|
listenKey | STRING | YES |
Response:
Close a listenKey
Close out a user data stream.
Weight: 1
Parameters:
Name | Type | Mandatory | Description |
---|---|---|---|
listenKey | STRING | YES |
Response:
Web Socket Payloads
Account state is updated with the outboundAccountInfo event.
Payload:
An additional event outboundAccountPosition is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change.
Orders are updated with the executionReport event.
Check the Rest API Documentation and below for relevant enum definitions.
Average price can be found by doing Z divided by z .
Payload:
Execution types:
- NEW — The order has been accepted into the engine.
- CANCELED — The order has been canceled by the user.
- REPLACED (currently unused)
- REJECTED — The order has been rejected and was not processed. (This is never pushed into the User Data Stream)
- TRADE — Part of the order or all of the order’s quantity has filled.
- EXPIRED — The order was canceled according to the order type’s rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during liquidation, orders canceled during maintenance)
If the order is an OCO, an event will be displayed named ListStatus in addition to the executionReport event.
Payload
Balance Update occurs during deposit or withdrawals from the account.
Источник
User data stream binance
Table of Contents generated with DocToc
User Data Streams for Binance (2021-01-01)
General WSS information
- The base API endpoint is: https://api.binance.com
- A User Data Stream listenKey is valid for 60 minutes after creation.
- Doing a PUT on an active listenKey will extend its validity for 60 minutes.
- Doing a DELETE on an active listenKey will close the stream and invalidate the listenKey .
- Doing a POST on an account with an active listenKey will return the currently active listenKey and extend its validity for 60 minutes.
- The base websocket endpoint is: wss://stream.binance.com:9443
- User Data Streams are accessed at /ws/ or /stream?streams=
- A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark
Create a listenKey
Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active listenKey , that listenKey will be returned and its validity will be extended for 60 minutes.
Weight: 1
Parameters: NONE
Response:
Ping/Keep-alive a listenKey
Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It’s recommended to send a ping about every 30 minutes.
Weight: 1
Parameters:
Name | Type | Mandatory | Description |
---|---|---|---|
listenKey | STRING | YES |
Response:
Close a listenKey
Close out a user data stream.
Weight: 1
Parameters:
Name | Type | Mandatory | Description |
---|---|---|---|
listenKey | STRING | YES |
Response:
Web Socket Payloads
outboundAccountPosition is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change.
Balance Update occurs during the following:
- Deposits or withdrawals from the account
- Transfer of funds between accounts (e.g. Spot to Margin)
Payload
Orders are updated with the executionReport event.
Check the Rest API Documentation and below for relevant enum definitions.
Average price can be found by doing Z divided by z .
Payload:
Execution types:
- NEW — The order has been accepted into the engine.
- CANCELED — The order has been canceled by the user.
- REPLACED (currently unused)
- REJECTED — The order has been rejected and was not processed. (This is never pushed into the User Data Stream)
- TRADE — Part of the order or all of the order’s quantity has filled.
- EXPIRED — The order was canceled according to the order type’s rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during liquidation, orders canceled during maintenance)
If the order is an OCO, an event will be displayed named ListStatus in addition to the executionReport event.
Источник