Websocket streams
Description
Binance4j-websocket is a set of Java connectors for the Binance Websocket API.
Installation
Event Callback
WebsocketCallback
is a generic functional interface every WebsocketClient
receives at instantiation that will handle the stream events.
WebsocketCallback<Candle> callback = new WebsocketCallback<>{
// Data received from the server
@Override
public void onMessage(Object response) {
//...
}
// Stream is open
@Override
public void onOpen(Response response) {
//...
}
// Stream issue
@Override
public void onFailure(ApiException exception) {
//...
}
// Stream is closing
@Override
public void onClosing(WebsocketCloseObject websocketCloseObject) {
//...
}
// Stream is closed
@Override
public void onClosed(WebsocketCloseObject websocketCloseObject) {
//...
}
};
//Client instantiation
WebsocketCandlestickClient client = new WebsocketCandlestickClient("BTCBUSD", CandlestickInterval.FIVE_MINUTE, callback);
//open stream
client.open();
//close stream
client.close();
Configuration
Every WebsocketClient
possess a WebsocketClientConfiguration
accessible through:
client.getConfiguration();
Parameter | Type | Description | Default |
---|---|---|---|
baseUrl | String | The stream base url | wss://stream.binance.com:9443/ws |
pingInterval | Duration | The interval the client will send a ping | 3m |
keepAlive | Boolean | Reconnect if stream is closed by server | true |
maxReconnections | Integer | The number of time the client tries to reconnect | 5 |
reconnectionInterval | Duration | The reconnection interval | 10s |
noResponseTimeout | Duration | The time the client waits for a server response before triggering a timeout | 3m |
noResponseTimeoutMarginError | Duration | Margin error added to WebsocketCandleStickClient noResponseTimeout 's configuration | 5s |
disconnectionTimeout | Duration | Time after which the client disconnects if stuck in closing state | 5s |
closeAfter | Duration | Time after which the client will disconnect. If keepAlive is true, will automatically reconnect. Bypasses server unwanted disconnections. | 1d |
Available Websocket clients
Individual Symbol Ticker Streams
Handles 24hr rolling window ticker statistics for a single symbol.
- One symbol
- Multiple symbols (List)
WebsocketTickerClient client = new WebsocketTickerClient("BNBBTC", callback);
WebsocketTickerClient client = new WebsocketTickerClient(List.of("BNBBTC", "BNBBUSD"), callback);
These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
24hr rolling window mini-ticker statistics.
- One symbol
- Multiple symbols (List)
WebsocketMiniTickerClient client = new WebsocketMiniTickerClient("BNBBTC", callback);
WebsocketMiniTickerClient client = new WebsocketMiniTickerClient(List.of("BNBBTC", "BNBBUSD"), callback);
These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
All Market Tickers Stream
24hr rolling window ticker statistics for all symbols that changed.
WebsocketAllTickersClient client = new WebsocketAllTickersClient(callback);
These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
All Market Mini Tickers Stream
24hr rolling window mini-ticker statistics for all symbols that changed.
WebsocketAllMiniTickersClient client = new WebsocketAllMiniTickersClient(callback);
These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
Individual Symbol Book Ticker Streams
Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.
- One symbol
- Multiple symbols (List)
WebsocketBookTickerClient client = new WebsocketBookTickerClient("BNBBTC", callback);
WebsocketBookTickerClient client = new WebsocketBookTickerClient(List.of("BNBBTC", "BNBBUSD"), callback);
All Book Tickers Stream
Pushes any update to the best bid or ask's price or quantity in real-time for all symbols.
WebsocketAllBookTickersClient client = new WebsocketAllBookTickersClient(callback);
Kline/Candlestick Streams
The Kline/Candlestick Stream push updates to the current klines/candlestick every second.
- One symbol
- Multiple symbols (List)
WebsocketCandlestickClient client = new WebsocketCandlestickClient("BNBBTC", CandlestickInterval.FIVE_MINUTE, callback);
WebsocketCandlestickClient client = new WebsocketCandlestickClient(List.of("BNBBTC", "BNBBUSD", CandlestickInterval.FIVE_MINUTE), callback);
Diff. Depth Stream
Order book price and quantity depth updates used to locally manage an order book.
- One symbol
- Multiple symbols (List)
WebsocketDepthClient client = new WebsocketDepthClient("BNBBTC", DepthUpdateSpeed.MS_1000, callback);
WebsocketDepthClient client = new WebsocketDepthClient(List.of("BNBBTC", "BNBBUSD"), DepthUpdateSpeed.MS_1000, callback);
Partial Book Depth Streams
Top bids and asks.
- One symbol
- Multiple symbols (List)
WebsocketMiniDepthClient client = new WebsocketMiniDepthClient("BNBBTC", DepthLevel.LEVEL_5, DepthUpdateSpeed.MS_1000, callback);
WebsocketMiniDepthClient client = new WebsocketMiniDepthClient(List.of("BNBBTC", "BNBBUSD"), DepthLevel.LEVEL_5, DepthUpdateSpeed.MS_1000, callback);
Trade Streams
The Trade Streams push raw trade information; each trade has a unique buyer and seller.
- One symbol
- Multiple symbols (List)
WebsocketTradeClient client = new WebsocketTradeClient("BNBBTC", callback);
WebsocketTradeClient client = new WebsocketTradeClient(List.of("BNBBTC", "BNBBUSD"), callback);
Aggregate Trade Streams
The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
- One symbol
- Multiple symbols (List)
WebsocketAggTradeClient client = new WebsocketAggTradeClient("BNBBTC", callback);
WebsocketAggTradeClient client = new WebsocketAggTradeClient(List.of("BNBBTC", "BNBBUSD"), callback);
User Data Streams
The User Data Streams push account, balance and order update infos.
// Instantiate a UserDataClient
UserDataClient userDataClient = new UserDataClient(key,secret);
// instantiate the ws client
WebsocketUserDataClient client = new WebsocketUserDataClient(userDataClient, callback);
The client will automatically keep alive the listen key every 30 minutes as advised by Binance.
The client handles thoses events:
Account Update : 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: 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. Check the Public API Definitions and below for relevant enum definitions. 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)
User data endpoints
Start user data stream
Returns a listen key to open a user data websocket stream.
- Sync
- Async
try{
ListenKey res = client.startUserDataStream().sync();
}catch(ApiException e){
//...
}
client.startUserDataStream().async((response, exception) -> {
if(exception == null){
//...
}else{
//...
}
});
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.
If you're using WebsocketUserDataClient
, this is done automatically.
Keep alive user data stream
Keepalive a user data stream to prevent a time out.
- Sync
- Async
try{
client.keepAliveUserDataStream(listenKey).sync();
}catch(ApiException e){
//...
}
client.keepAliveUserDataStream(listenKey).async((response, exception) -> {
if(exception == null){
//...
}else{
//...
}
});
User data streams will close after 60 minutes.
It's recommended to send a ping about every 30 minutes.
If you're using WebsocketUserDataClient
, this is done automatically.
Close out a user data stream
- Sync
- Async
try{
client.closeUserDataStream(listenKey).sync();
}catch(ApiException e){
//...
}
client.closeUserDataStream(listenKey).async((response, exception) -> {
if(exception == null){
//...
}else{
//...
}
});