binance-java-api is a Java library for interacting with the Binance API, providing complete API coverage, and supporting synchronous and asynchronous requests, as well as event streaming using WebSockets.
- Support for synchronous and asynchronous REST requests to all General, Market Data, Account endpoints, and User stream endpoints.
- Support for User Data, Trade, and Depth event streaming using Binance WebSocket API.
- Install library into your Maven's local repository by running
mvn install
- Add the following Maven dependency to your project's
pom.xml
:
<dependency>
<groupId>com.binance.api</groupId>
<artifactId>binance-api-client</artifactId>
<version>1.0.0</version>
</dependency>
Alternatively, you can clone this repository and run the examples.
There are three main client classes that can be used to interact with the API:
BinanceApiRestClient
, a synchronous/blocking Binance API client;BinanceApiAsyncRestClient
, an asynchronous/non-blocking Binance API client;BinanceApiWebSocketClient
, a data streaming client using Binance WebSocket API.
These can be instantiated through the corresponding factory method of BinanceApiClientFactory
, by passing the security parameters API-KEY
and SECRET
, which can be created at https://www.binance.com/userCenter/createApi.html.
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("API-KEY", "SECRET");
BinanceApiRestClient client = factory.newRestClient();
If the client only needs to access endpoints which do not require additional security, then these parameters are optional.
Once the client is instantiated, it is possible to start making requests to the API.
client.ping();
long serverTime = client.getServerTime();
System.out.println(serverTime);
View Response
1508380346873
OrderBook orderBook = client.getOrderBook("NEOETH", 10);
List<OrderBookEntry> asks = orderBook.getAsks();
OrderBookEntry firstAskEntry = asks.get(0);
System.out.println(firstAskEntry.getPrice() + " / " + firstAskEntry.getQty());
View Response
0.09200000 / 5.52000000
List<AggTrade> aggTrades = client.getAggTrades("NEOETH");
System.out.println(aggTrades);
View Response
[AggTrade[aggregatedTradeId=30593,price=0.09880800,quantity=40.89000000,firstBreakdownTradeId=33363,lastBreakdownTradeId=33363,tradeTime=1508331041246,isBuyerMaker=true], ...]
List<Candlestick> candlesticks = client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY);
System.out.println(candlesticks);
View Response
[Candlestick[openTime=1506297600000,open=0.09700000,high=0.12000100,low=0.05500000,close=0.11986900,volume=25709.37000000,closeTime=1506902399999,quoteAssetVolume=2649.80091051,numberOfTrades=2435,takerBuyBaseAssetVolume=10520.59000000,takerBuyQuoteAssetVolume=1101.94985388], ...]
TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH");
System.out.println(tickerStatistics.getLastPrice());
View Response
0.09100100
List<TickerPrice> allPrices = client.getAllPrices();
System.out.println(allPrices);
View Response
[TickerPrice[symbol=ETHBTC,price=0.05590400], TickerPrice[symbol=LTCBTC,price=0.01073300], ...]
Account account = client.getAccount();
System.out.println(account.getBalances());
System.out.println(account.getAssetBalance("ETH").getFree());
View Response
AssetBalance[asset=ETH,free=0.10000000,locked=0.00000000]
0.10000000
List<Order> openOrders = client.getOpenOrders(new OrderRequest("LINKETH"));
System.out.println(openOrders);
View Response
[Order[symbol=LINKETH,orderId=12345,clientOrderId=XYZ,price=0.00010000,origQty=1000.00000000,executedQty=0.00000000,status=NEW,timeInForce=GTC,type=LIMIT,side=BUY,stopPrice=0.00000000,icebergQty=0.00000000,time=1508382291552]]
Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 12345L));
System.out.println(order.getExecutedQty());
View Response
0.00000000
NewOrderResponse newOrderResponse = client.newOrder(marketBuy("LINKETH", "1000"));
System.out.println(newOrderResponse.getClientOrderId());
View Response
XXXXXfc2XXzTXXGs66ZcXX
NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"));
System.out.println(newOrderResponse.getTransactTime());
View Response
1508382322725
client.cancelOrder(new CancelOrderRequest("LINKETH", 123015L));
String listenKey = client.startUserDataStream();
client.keepAliveUserDataStream(listenKey);
client.closeUserDataStream(listenKey);
BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient();
client.onAggTradeEvent("ethbtc", (AggTradeEvent response) -> {
System.out.println(response.getPrice());
System.out.println(response.getQuantity());
});
View Response
0.05583500 / 1.06400000
1508383333069
0.05557200 / 2.00000000
1508383345070
0.05583200 / 2.68500000
1508383352961
...
client.onDepthEvent("ethbtc", (DepthEvent response) -> {
System.out.println(response.getAsks());
});
View Response
[OrderBookEntry[price=0.05559500,qty=7.94200000], OrderBookEntry[price=0.05559800,qty=0.00000000]]
[OrderBookEntry[price=0.05558400,qty=30.61800000], OrderBookEntry[price=0.05559500,qty=0.00000000], OrderBookEntry[price=0.05560600,qty=8.32100000]]
[OrderBookEntry[price=0.05559100,qty=7.86600000], OrderBookEntry[price=0.05560600,qty=0.00000000], OrderBookEntry[price=0.05607700,qty=5.15500000], OrderBookEntry[price=0.05620700,qty=0.00000000], OrderBookEntry[price=0.05842200,qty=0.00000000]]
[OrderBookEntry[price=0.05558400,qty=29.61700000]]
...
client.onUserDataUpdateEvent(listenKey, response -> {
if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) {
AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent();
// Print new balances of every available asset
System.out.println(accountUpdateEvent.getBalances());
} else {
OrderTradeUpdateEvent orderTradeUpdateEvent = response.getOrderTradeUpdateEvent();
// Print details about an order/trade
System.out.println(orderTradeUpdateEvent);
// Print original quantity
System.out.println(orderTradeUpdateEvent.getOriginalQuantity());
// Or price
System.out.println(orderTradeUpdateEvent.getPrice());
}
});
To make an asynchronous request it is necessary to use the BinanceApiAsyncRestClient
, and call the method with the same name as in the synchronous version, but passing a callback BinanceApiCallback
that handles the response whenever it arrives.
client.get24HrPriceStatistics("NEOETH", (TickerStatistics response) -> {
System.out.println(response.getLastPrice());
System.out.println(response.getVolume());
});
View Response
0.09100100
client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), (NewOrderResponse response) -> {
System.out.println(response.getTransactTime());
});
View Response
1508382322725
Every API method can potentially throw a checked BinanceApiException
which wraps the error message returned from the Binance API, or an exception, in case the request never properly reached the server.
try {
client.getOrderBook("UNKNOWN", 10);
} catch (BinanceApiException e) {
System.out.println(e.getError().getCode()); // -1121
System.out.println(e.getError().getMsg()); // Invalid symbol
}
View Response
-1121
Invalid symbol
An extensive set of examples, covering most aspects of the API, can be found at https://github.com/joaopsilva/binance-java-api/tree/master/src/test/java/com/binance/api/examples.