Skip to main content
Version: 2.x

Websocket streams

 License: MIT 

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();

Available parameters

ParameterTypeDescriptionDefault
baseUrlStringThe stream base urlwss://stream.binance.com:9443/ws
pingIntervalDurationThe interval the client will send a ping3m
keepAliveBooleanReconnect if stream is closed by servertrue
maxReconnectionsIntegerThe number of time the client tries to reconnect5
reconnectionIntervalDurationThe reconnection interval10s
noResponseTimeoutDurationThe time the client waits for a server response before triggering a timeout3m
noResponseTimeoutMarginErrorDurationMargin error added to WebsocketCandleStickClient noResponseTimeout's configuration5s
disconnectionTimeoutDurationTime after which the client disconnects if stuck in closing state5s
closeAfterDurationTime 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.

WebsocketTickerClient client = new WebsocketTickerClient("BNBBTC", callback);
caution

These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.

24hr rolling window mini-ticker statistics.

WebsocketMiniTickerClient client = new WebsocketMiniTickerClient("BNBBTC", callback);
caution

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);
caution

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);
caution

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.

WebsocketBookTickerClient client = new WebsocketBookTickerClient("BNBBTC", 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.

WebsocketCandlestickClient client = new WebsocketCandlestickClient("BNBBTC", CandlestickInterval.FIVE_MINUTE, callback);

Diff. Depth Stream

Order book price and quantity depth updates used to locally manage an order book.

WebsocketDepthClient client = new WebsocketDepthClient("BNBBTC", DepthUpdateSpeed.MS_1000, callback);

Partial Book Depth Streams

Top bids and asks.

WebsocketMiniDepthClient client = new WebsocketMiniDepthClient("BNBBTC", DepthLevel.LEVEL_5, DepthUpdateSpeed.MS_1000, callback);

Trade Streams

The Trade Streams push raw trade information; each trade has a unique buyer and seller.

WebsocketTradeClient client = new WebsocketTradeClient("BNBBTC", callback);

Aggregate Trade Streams

The Aggregate Trade Streams push trade information that is aggregated for a single taker order.

WebsocketAggTradeClient client = new WebsocketAggTradeClient("BNBBTC", 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);
note

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.

try{
ListenKey res = client.startUserDataStream().sync();
}catch(ApiException e){
//...
}
note

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.

try{
client.keepAliveUserDataStream(listenKey).sync();
}catch(ApiException e){
//...
}
note

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

try{
client.closeUserDataStream(listenKey).sync();
}catch(ApiException e){
//...
}