com.binance.connector.client.impl.WebsocketClientImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of binance-connector-java Show documentation
Show all versions of binance-connector-java Show documentation
lightweight connector to API
package com.binance.connector.client.impl;
import com.binance.connector.client.WebsocketClient;
import com.binance.connector.client.enums.DefaultUrls;
import com.binance.connector.client.utils.HttpClientSingleton;
import com.binance.connector.client.utils.RequestBuilder;
import com.binance.connector.client.utils.UrlBuilder;
import com.binance.connector.client.utils.WebSocketCallback;
import com.binance.connector.client.utils.WebSocketConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Websocket Streams
* All stream endpoints under the
* Websocket Market Streams and
* User Data Streams
* section of the API documentation will be implemented in this class.
*
* Response will be returned as callback.
*/
public class WebsocketClientImpl implements WebsocketClient {
private final String baseUrl;
private final Map connections = new HashMap<>();
private final WebSocketCallback noopCallback = msg -> {
};
private static final Logger logger = LoggerFactory.getLogger(WebsocketClientImpl.class);
public WebsocketClientImpl() {
this.baseUrl = DefaultUrls.WS_URL;
}
public WebsocketClientImpl(String baseUrl) {
this.baseUrl = baseUrl;
}
/**
* The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
*
* <symbol>@aggTrade
*
* Update Speed: Real-time
*
* @param symbol Name of trading pair
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#aggregate-trade-streams
*/
@Override
public int aggTradeStream(String symbol, WebSocketCallback callback) {
return aggTradeStream(symbol, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #aggTradeStream(String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int aggTradeStream(String symbol, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@aggTrade", baseUrl, symbol));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* The Trade Streams push raw trade information; each trade has a unique buyer and seller.
*
* <symbol>@trade
*
* Update Speed: Real-time
*
* @param symbol Name of trading pair
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#trade-streams
*/
@Override
public int tradeStream(String symbol, WebSocketCallback callback) {
return tradeStream(symbol, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #tradeStream(String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int tradeStream(String symbol, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@trade", baseUrl, symbol));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* The Kline/Candlestick Stream push updates to the current klines/candlestick every second.
*
* <symbol>@kline_<interval>
*
* Update Speed: Real-time
*
* @param symbol Name of trading pair
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#kline-candlestick-streams
*/
@Override
public int klineStream(String symbol, String interval, WebSocketCallback callback) {
return klineStream(symbol, interval, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #klineStream(String, String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param interval
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int klineStream(String symbol, String interval, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@kline_%s", baseUrl, symbol, interval));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* 24hr rolling window mini-ticker statistics.
* These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs.
*
* <symbol>@miniTicker
*
* Update Speed: Real-time
*
* @param symbol Name of trading pair
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream
*/
@Override
public int miniTickerStream(String symbol, WebSocketCallback callback) {
return miniTickerStream(symbol, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #miniTickerStream(String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int miniTickerStream(String symbol, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@miniTicker", baseUrl, symbol));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* 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.
*
* !miniTicker@arr
*
* Update Speed: Real-time
*
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#all-market-mini-tickers-stream
*/
@Override
public int allMiniTickerStream(WebSocketCallback callback) {
return allMiniTickerStream(noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #allMiniTickerStream(WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int allMiniTickerStream(WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/!miniTicker@arr", baseUrl));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* 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.
*
* <symbol>@ticker
*
* Update Speed: Real-time
*
* @param symbol Name of trading pair
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-ticker-streams
*/
@Override
public int symbolTicker(String symbol, WebSocketCallback callback) {
return symbolTicker(symbol, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #symbolTicker(String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int symbolTicker(String symbol, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@ticker", baseUrl, symbol));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* 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.
*
* !ticker@arr
*
* Update Speed: Real-time
*
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#all-market-tickers-stream
*/
@Override
public int allTickerStream(WebSocketCallback callback) {
return allTickerStream(noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #allTickerStream(WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int allTickerStream(WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/!ticker@arr", baseUrl));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol.
*
* <symbol>@bookTicker
*
* Update Speed: Real-time
*
* @param symbol Name of trading pair
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-book-ticker-streams
*/
@Override
public int bookTicker(String symbol, WebSocketCallback callback) {
return bookTicker(symbol, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #bookTicker(String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int bookTicker(String symbol, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@bookTicker", baseUrl, symbol));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* Pushes any update to the best bid or ask's price or quantity in real-time for all symbols.
*
* !bookTicker
*
* Update Speed: Real-time
*
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#all-book-tickers-stream
*/
@Override
public int allBookTickerStream(WebSocketCallback callback) {
return allBookTickerStream(noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #allBookTickerStream(WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int allBookTickerStream(WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/!bookTicker", baseUrl));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* Top bids and asks, Valid are 5, 10, or 20.
*
* <symbol>@depth<levels>@<speed>ms
*
* Update Speed: 1000ms or 100ms
*
* @param symbol Name of trading pair
* @param levels Valid are 5, 10, or 20
* @param speed 1000ms or 100ms
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#partial-book-depth-streams
*/
@Override
public int partialDepthStream(String symbol, int levels, int speed, WebSocketCallback callback) {
return partialDepthStream(symbol, levels, speed, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #partialDepthStream(String, int, int, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param levels
* @param speed
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int partialDepthStream(String symbol, int levels, int speed, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@depth%s@%sms", baseUrl, symbol, levels, speed));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* Order book price and quantity depth updates used to locally manage an order book.
*
* <symbol>@depth@<speed>ms
*
* Update Speed: 1000ms or 100ms
*
* @param symbol Name of trading pair
* @param speed 1000ms or 100ms
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream
*/
@Override
public int diffDepthStream(String symbol, int speed, WebSocketCallback callback) {
return diffDepthStream(symbol, speed, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #diffDepthStream(String, int, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param symbol
* @param speed
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int diffDepthStream(String symbol, int speed, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@depth@%sms", baseUrl, symbol, speed));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* User Data Streams are accessed at /ws/<listenKey>
*
* @param listenKey listen key obtained from this
* endpoint
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#user-data-streams
*/
@Override
public int listenUserStream(String listenKey, WebSocketCallback callback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s", baseUrl, listenKey));
return listenUserStream(listenKey, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #listenUserStream(String, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param listenKey
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int listenUserStream(String listenKey, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s", baseUrl, listenKey));
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* Combined streams are accessed at /stream?streams=<streamName1>/<streamName2>/<streamName3>
*
* @param streams A list of stream names to be combined
* @return int - Connection ID
* @see
* https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams
*/
@Override
public int combineStreams(ArrayList streams, WebSocketCallback callback) {
return combineStreams(streams, noopCallback, callback, noopCallback, noopCallback);
}
/**
* Same as {@link #combineStreams(ArrayList, WebSocketCallback)} plus accepts callbacks for all major websocket connection events.
*
* @param streams
* @param onOpenCallback
* @param onMessageCallback
* @param onClosingCallback
* @param onFailureCallback
* @return
*/
@Override
public int combineStreams(ArrayList streams, WebSocketCallback onOpenCallback, WebSocketCallback onMessageCallback, WebSocketCallback onClosingCallback, WebSocketCallback onFailureCallback) {
String url = UrlBuilder.buildStreamUrl(String.format("%s/stream", baseUrl), streams);
Request request = RequestBuilder.buildWebsocketRequest(url);
return createConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
}
/**
* Closes a specific stream based on stream Id.
*
* @param connectionId
*/
@Override
public void closeConnection(int connectionId) {
if (connections.containsKey(connectionId)) {
connections.get(connectionId).close();
logger.info("Closing Connection ID {}", connectionId);
connections.remove(connectionId);
} else {
logger.info("Connection ID {} does not exist!", connectionId);
}
}
/**
* Closes all streams
*/
@Override
public void closeAllConnections() {
if (!connections.isEmpty()) {
logger.info("Closing {} connections(s)", connections.size());
Iterator> iter = connections.entrySet().iterator();
while (iter.hasNext()) {
WebSocketConnection connection = iter.next().getValue();
connection.close();
iter.remove();
}
}
if (connections.isEmpty()) {
HttpClientSingleton.getHttpClient().dispatcher().executorService().shutdown();
logger.info("All connections are closed!");
}
}
private int createConnection(
WebSocketCallback onOpenCallback,
WebSocketCallback onMessageCallback,
WebSocketCallback onClosingCallback,
WebSocketCallback onFailureCallback,
Request request
) {
WebSocketConnection connection = new WebSocketConnection(onOpenCallback, onMessageCallback, onClosingCallback, onFailureCallback, request);
connection.connect();
int connectionId = connection.getConnectionId();
connections.put(connectionId, connection);
return connectionId;
}
}