From 108b877f8e6b92cdc007b811963a0de32351b5ec Mon Sep 17 00:00:00 2001 From: truong ha Date: Thu, 30 Apr 2020 12:39:41 +0700 Subject: [PATCH 1/8] Clone --- .../BinanceApiAsyncMarginRestClient.java | 109 +++ .../api/client/BinanceApiAsyncRestClient.java | 626 ++++++++--------- .../api/client/BinanceApiCallback.java | 46 +- .../api/client/BinanceApiClientFactory.java | 163 ++--- .../binance/api/client/BinanceApiError.java | 88 +-- .../client/BinanceApiMarginRestClient.java | 103 +++ .../api/client/BinanceApiRestClient.java | 596 ++++++++-------- .../api/client/BinanceApiWebSocketClient.java | 136 ++-- .../client/constant/BinanceApiConstants.java | 111 +-- .../api/client/domain/ExecutionType.java | 30 +- .../binance/api/client/domain/LoanStatus.java | 11 + .../api/client/domain/OrderRejectReason.java | 40 +- .../binance/api/client/domain/OrderSide.java | 24 +- .../api/client/domain/OrderStatus.java | 34 +- .../binance/api/client/domain/OrderType.java | 34 +- .../api/client/domain/TimeInForce.java | 38 +- .../api/client/domain/TransferType.java | 21 + .../api/client/domain/account/Account.java | 330 ++++----- .../client/domain/account/AssetBalance.java | 124 ++-- .../api/client/domain/account/Deposit.java | 176 ++--- .../client/domain/account/DepositAddress.java | 122 ++-- .../client/domain/account/DepositHistory.java | 114 ++-- .../api/client/domain/account/Loan.java | 51 ++ .../domain/account/LoanQueryResult.java | 33 + .../client/domain/account/MarginAccount.java | 121 ++++ .../domain/account/MarginAssetBalance.java | 103 +++ .../domain/account/MarginTransaction.java | 29 + .../api/client/domain/account/NewOrder.java | 518 +++++++------- .../domain/account/NewOrderResponse.java | 376 +++++------ .../domain/account/NewOrderResponseType.java | 30 +- .../api/client/domain/account/Order.java | 436 ++++++------ .../api/client/domain/account/Trade.java | 376 +++++------ .../domain/account/TradeHistoryItem.java | 208 +++--- .../api/client/domain/account/Withdraw.java | 248 +++---- .../domain/account/WithdrawHistory.java | 88 +-- .../client/domain/account/WithdrawResult.java | 124 ++-- .../account/request/AllOrdersRequest.java | 94 +-- .../account/request/CancelOrderRequest.java | 130 ++-- .../account/request/CancelOrderResponse.java | 154 ++--- .../domain/account/request/OrderRequest.java | 110 +-- .../account/request/OrderStatusRequest.java | 100 +-- .../domain/event/AccountUpdateEvent.java | 128 ++-- .../client/domain/event/AggTradeEvent.java | 114 ++-- .../domain/event/AllMarketTickersEvent.java | 588 ++++++++-------- .../event/AssetBalanceDeserializer.java | 62 +- .../client/domain/event/CandlestickEvent.java | 440 ++++++------ .../event/CandlestickEventDeserializer.java | 98 +-- .../event/CandlestickEventSerializer.java | 88 +-- .../api/client/domain/event/DepthEvent.java | 262 ++++---- .../api/client/domain/event/ListenKey.java | 50 +- .../domain/event/OrderTradeUpdateEvent.java | 636 +++++++++--------- .../domain/event/UserDataUpdateEvent.java | 200 +++--- .../UserDataUpdateEventDeserializer.java | 120 ++-- .../api/client/domain/general/Asset.java | 246 +++---- .../client/domain/general/ExchangeFilter.java | 88 +-- .../client/domain/general/ExchangeInfo.java | 156 ++--- .../api/client/domain/general/FilterType.java | 50 +- .../api/client/domain/general/RateLimit.java | 102 +-- .../domain/general/RateLimitInterval.java | 24 +- .../client/domain/general/RateLimitType.java | 24 +- .../api/client/domain/general/ServerTime.java | 48 +- .../client/domain/general/SymbolFilter.java | 320 ++++----- .../api/client/domain/general/SymbolInfo.java | 262 ++++---- .../client/domain/general/SymbolStatus.java | 34 +- .../api/client/domain/market/AggTrade.java | 206 +++--- .../api/client/domain/market/BookTicker.java | 176 ++--- .../api/client/domain/market/Candlestick.java | 286 ++++---- .../domain/market/CandlestickInterval.java | 72 +- .../api/client/domain/market/OrderBook.java | 124 ++-- .../client/domain/market/OrderBookEntry.java | 88 +-- .../market/OrderBookEntryDeserializer.java | 58 +- .../market/OrderBookEntrySerializer.java | 42 +- .../api/client/domain/market/TickerPrice.java | 92 +-- .../domain/market/TickerStatistics.java | 512 +++++++------- .../client/exception/BinanceApiException.java | 148 ++-- .../BinanceApiAsyncMarginRestClientImpl.java | 103 +++ .../impl/BinanceApiAsyncRestClientImpl.java | 484 ++++++------- .../impl/BinanceApiCallbackAdapter.java | 102 +-- .../impl/BinanceApiMarginRestClientImpl.java | 101 +++ .../client/impl/BinanceApiRestClientImpl.java | 466 ++++++------- .../api/client/impl/BinanceApiService.java | 393 ++++++----- .../impl/BinanceApiServiceGenerator.java | 192 +++--- .../impl/BinanceApiWebSocketClientImpl.java | 172 ++--- .../impl/BinanceApiWebSocketListener.java | 114 ++-- .../security/AuthenticationInterceptor.java | 182 ++--- .../api/client/security/HmacSHA256Signer.java | 58 +- .../constant/BinanceApiConstantsTest.java | 160 ++--- .../domain/account/NewOrderResponseTest.java | 96 +-- .../WithdrawHistoryDeserializerTest.java | 88 +-- .../CandlestickEventDeserializerTest.java | 136 ++-- .../UserDataUpdateEventDeserializerTest.java | 162 ++--- .../general/ExchangeInfoDeserializerTest.java | 256 +++---- .../market/CandlestickDeserializerTest.java | 102 +-- .../examples/AccountBalanceCacheExample.java | 162 ++--- .../api/examples/AccountEndpointsExample.java | 80 +-- .../AccountEndpointsExampleAsync.java | 62 +- .../api/examples/AggTradesCacheExample.java | 160 ++--- .../api/examples/AllMarketTickersExample.java | 42 +- .../examples/CandlesticksCacheExample.java | 172 ++--- .../api/examples/DepthCacheExample.java | 488 +++++++------- .../api/examples/GeneralEndpointsExample.java | 92 +-- .../GeneralEndpointsExampleAsync.java | 90 +-- .../MarginAccountEndpointsExample.java | 41 ++ .../MarginAccountEndpointsExampleAsync.java | 36 + ...arginAccountEndpointsLoanQueryExample.java | 24 + .../api/examples/MarginOrdersExample.java | 46 ++ .../examples/MarginOrdersExampleAsync.java | 36 + .../examples/MarginUserDataStreamExample.java | 55 ++ .../examples/MarketDataEndpointsExample.java | 114 ++-- .../MarketDataEndpointsExampleAsync.java | 114 ++-- .../api/examples/MarketDataStreamExample.java | 56 +- .../binance/api/examples/OrdersExample.java | 122 ++-- .../api/examples/OrdersExampleAsync.java | 96 +-- .../api/examples/UserDataStreamExample.java | 108 +-- 114 files changed, 9501 insertions(+), 8411 deletions(-) create mode 100755 src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiCallback.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiClientFactory.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiError.java create mode 100755 src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/constant/BinanceApiConstants.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/ExecutionType.java create mode 100755 src/main/java/com/binance/api/client/domain/LoanStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderRejectReason.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderSide.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/TimeInForce.java create mode 100755 src/main/java/com/binance/api/client/domain/TransferType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Account.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/AssetBalance.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Deposit.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/DepositAddress.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/DepositHistory.java create mode 100755 src/main/java/com/binance/api/client/domain/account/Loan.java create mode 100755 src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java create mode 100755 src/main/java/com/binance/api/client/domain/account/MarginAccount.java create mode 100755 src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java create mode 100755 src/main/java/com/binance/api/client/domain/account/MarginTransaction.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOrder.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Order.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Trade.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Withdraw.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/WithdrawResult.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/DepthEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/ListenKey.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/Asset.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/FilterType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/RateLimit.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/RateLimitType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/ServerTime.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/SymbolFilter.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/SymbolInfo.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/SymbolStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/AggTrade.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/BookTicker.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/Candlestick.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBook.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/TickerPrice.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/TickerStatistics.java mode change 100644 => 100755 src/main/java/com/binance/api/client/exception/BinanceApiException.java create mode 100755 src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java create mode 100755 src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiService.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java mode change 100644 => 100755 src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java mode change 100644 => 100755 src/main/java/com/binance/api/client/security/HmacSHA256Signer.java mode change 100644 => 100755 src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java mode change 100644 => 100755 src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AccountEndpointsExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AggTradesCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AllMarketTickersExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/CandlesticksCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/DepthCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/GeneralEndpointsExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java create mode 100755 src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java create mode 100755 src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java create mode 100755 src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java create mode 100755 src/test/java/com/binance/api/examples/MarginOrdersExample.java create mode 100755 src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java create mode 100755 src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/MarketDataStreamExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/OrdersExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/OrdersExampleAsync.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/UserDataStreamExample.java diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java new file mode 100755 index 000000000..cbab0781c --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java @@ -0,0 +1,109 @@ +package com.binance.api.client; + +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; + +import java.util.List; + +/** + * Binance API façade, supporting asynchronous/non-blocking access Binance's Margin REST API. + */ +public interface BinanceApiAsyncMarginRestClient { + + // Account endpoints + + /** + * Get current margin account information (async). + */ + void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback); + + /** + * Get current margin account information using default parameters (async). + */ + void getAccount(BinanceApiCallback callback); + + /** + * Get all open orders on margin account for a symbol (async). + * + * @param orderRequest order request parameters + * @param callback the callback that handles the response + */ + void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback); + + /** + * Send in a new margin order (async). + * + * @param order the new order to submit. + * @return a response containing details about the newly placed order. + */ + void newOrder(NewOrder order, BinanceApiCallback callback); + + /** + * Cancel an active margin order (async). + * + * @param cancelOrderRequest order status request parameters + */ + void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); + + /** + * Check margin order's status (async). + * + * @param orderStatusRequest order status request options/filters + * @return an order + */ + void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback); + + /** + * Get margin trades for a specific symbol (async). + * + * @param symbol symbol to get trades from + * @return a list of trades + */ + void getMyTrades(String symbol, BinanceApiCallback> callback); + + // User stream endpoints + + /** + * Start a new user data stream (async). + * + * @return a listen key that can be used with data streams + */ + void startUserDataStream(BinanceApiCallback callback); + + /** + * PING a user data stream to prevent a time out (async). + * + * @param listenKey listen key that identifies a data stream + */ + void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback); + + /** + * Execute transfer between spot account and margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + void transfer(String asset, String amount, TransferType type, BinanceApiCallback callback); + + /** + * Apply for a loan + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + void borrow(String asset, String amount, BinanceApiCallback callback); + + /** + * Repay loan for margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + void repay(String asset, String amount, BinanceApiCallback callback); + +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java old mode 100644 new mode 100755 index a6e7fe7ad..a51a2bb9f --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -1,314 +1,314 @@ -package com.binance.api.client; - -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.event.ListenKey; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.ServerTime; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -/** - * Binance API façade, supporting asynchronous/non-blocking access Binance's REST API. - */ -public interface BinanceApiAsyncRestClient { - - // General endpoints - - /** - * Test connectivity to the Rest API. - */ - void ping(BinanceApiCallback callback); - - /** - * Check server time. - */ - void getServerTime(BinanceApiCallback callback); - - /** - * Current exchange trading rules and symbol information - */ - void getExchangeInfo(BinanceApiCallback callback); - - /** - * ALL supported assets and whether or not they can be withdrawn. - */ - void getAllAssets(BinanceApiCallback> callback); - - // Market Data endpoints - - /** - * Get order book of a symbol (asynchronous) - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit depth of the order book (max 100) - * @param callback the callback that handles the response - */ - void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback); - - /** - * Get recent trades (up to last 500). Weight: 1 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - * @param callback the callback that handles the response - */ - void getTrades(String symbol, Integer limit, BinanceApiCallback> callback); - - /** - * Get older trades. Weight: 5 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - * @param fromId TradeId to fetch from. Default gets most recent trades. - * @param callback the callback that handles the response - */ - void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback); - - /** - * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with - * the same price will have the quantity aggregated. - * - * If both startTime and endTime are sent, limitshould not - * be sent AND the distance between startTime and endTime must be less than 24 hours. - * - * @param symbol symbol to aggregate (mandatory) - * @param fromId ID to get aggregate trades from INCLUSIVE (optional) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). - * @param callback the callback that handles the response - * @return a list of aggregate trades for the given symbol - */ - void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); - - /** - * Return the most recent aggregate trades for symbol - * - * @see #getAggTrades(String, String, Integer, Long, Long, BinanceApiCallback) - */ - void getAggTrades(String symbol, BinanceApiCallback> callback); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @param symbol symbol to aggregate (mandatory) - * @param interval candlestick interval (mandatory) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). - * @param callback the callback that handles the response containing a candlestick bar for the given symbol and interval - */ - void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @see #getCandlestickBars(String, CandlestickInterval, BinanceApiCallback) - */ - void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback); - - /** - * Get 24 hour price change statistics (asynchronous). - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param callback the callback that handles the response - */ - void get24HrPriceStatistics(String symbol, BinanceApiCallback callback); - - /** - * Get 24 hour price change statistics for all symbols (asynchronous). - * - * @param callback the callback that handles the response - */ - void getAll24HrPriceStatistics(BinanceApiCallback> callback); - - /** - * Get Latest price for all symbols (asynchronous). - * - * @param callback the callback that handles the response - */ - void getAllPrices(BinanceApiCallback> callback); - - /** - * Get latest price for symbol (asynchronous). - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param callback the callback that handles the response - */ - void getPrice(String symbol , BinanceApiCallback callback); - - /** - * Get best price/qty on the order book for all symbols (asynchronous). - * - * @param callback the callback that handles the response - */ - void getBookTickers(BinanceApiCallback> callback); - - // Account endpoints - - /** - * Send in a new order (asynchronous) - * - * @param order the new order to submit. - * @param callback the callback that handles the response - */ - void newOrder(NewOrder order, BinanceApiCallback callback); - - /** - * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. - * - * @param order the new TEST order to submit. - * @param callback the callback that handles the response - */ - void newOrderTest(NewOrder order, BinanceApiCallback callback); - - /** - * Check an order's status (asynchronous). - * - * @param orderStatusRequest order status request parameters - * @param callback the callback that handles the response - */ - void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback); - - /** - * Cancel an active order (asynchronous). - * - * @param cancelOrderRequest order status request parameters - * @param callback the callback that handles the response - */ - void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); - - /** - * Get all open orders on a symbol (asynchronous). - * - * @param orderRequest order request parameters - * @param callback the callback that handles the response - */ - void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback); - - /** - * Get all account orders; active, canceled, or filled. - * - * @param orderRequest order request parameters - * @param callback the callback that handles the response - */ - void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback); - - /** - * Get current account information (async). - */ - void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback); - - /** - * Get current account information using default parameters (async). - */ - void getAccount(BinanceApiCallback callback); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @param fromId TradeId to fetch from. Default gets most recent trades. - * @param callback the callback that handles the response with a list of trades - */ - void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @param callback the callback that handles the response with a list of trades - */ - void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param callback the callback that handles the response with a list of trades - */ - void getMyTrades(String symbol, BinanceApiCallback> callback); - - /** - * Submit a withdraw request. - * - * Enable Withdrawals option has to be active in the API settings. - * - * @param asset asset symbol to withdraw - * @param address address to withdraw to - * @param amount amount to withdraw - * @param name description/alias of the address - * @param addressTag Secondary address identifier for coins like XRP,XMR etc. - */ - void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback); - - /** - * Fetch account deposit history. - * - * @param callback the callback that handles the response and returns the deposit history - */ - void getDepositHistory(String asset, BinanceApiCallback callback); - - /** - * Fetch account withdraw history. - * - * @param callback the callback that handles the response and returns the withdraw history - */ - void getWithdrawHistory(String asset, BinanceApiCallback callback); - - /** - * Fetch deposit address. - * - * @param callback the callback that handles the response and returns the deposit address - */ - void getDepositAddress(String asset, BinanceApiCallback callback); - - // User stream endpoints - - /** - * Start a new user data stream. - * - * @param callback the callback that handles the response which contains a listenKey - */ - void startUserDataStream(BinanceApiCallback callback); - - /** - * PING a user data stream to prevent a time out. - * - * @param listenKey listen key that identifies a data stream - * @param callback the callback that handles the response which contains a listenKey - */ - void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback); - - /** - * Close out a new user data stream. - * - * @param listenKey listen key that identifies a data stream - * @param callback the callback that handles the response which contains a listenKey - */ - void closeUserDataStream(String listenKey, BinanceApiCallback callback); +package com.binance.api.client; + +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +/** + * Binance API façade, supporting asynchronous/non-blocking access Binance's REST API. + */ +public interface BinanceApiAsyncRestClient { + + // General endpoints + + /** + * Test connectivity to the Rest API. + */ + void ping(BinanceApiCallback callback); + + /** + * Check server time. + */ + void getServerTime(BinanceApiCallback callback); + + /** + * Current exchange trading rules and symbol information + */ + void getExchangeInfo(BinanceApiCallback callback); + + /** + * ALL supported assets and whether or not they can be withdrawn. + */ + void getAllAssets(BinanceApiCallback> callback); + + // Market Data endpoints + + /** + * Get order book of a symbol (asynchronous) + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit depth of the order book (max 100) + * @param callback the callback that handles the response + */ + void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback); + + /** + * Get recent trades (up to last 500). Weight: 1 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + * @param callback the callback that handles the response + */ + void getTrades(String symbol, Integer limit, BinanceApiCallback> callback); + + /** + * Get older trades. Weight: 5 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + * @param fromId TradeId to fetch from. Default gets most recent trades. + * @param callback the callback that handles the response + */ + void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback); + + /** + * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with + * the same price will have the quantity aggregated. + * + * If both startTime and endTime are sent, limitshould not + * be sent AND the distance between startTime and endTime must be less than 24 hours. + * + * @param symbol symbol to aggregate (mandatory) + * @param fromId ID to get aggregate trades from INCLUSIVE (optional) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). + * @param callback the callback that handles the response + * @return a list of aggregate trades for the given symbol + */ + void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); + + /** + * Return the most recent aggregate trades for symbol + * + * @see #getAggTrades(String, String, Integer, Long, Long, BinanceApiCallback) + */ + void getAggTrades(String symbol, BinanceApiCallback> callback); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @param symbol symbol to aggregate (mandatory) + * @param interval candlestick interval (mandatory) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). + * @param callback the callback that handles the response containing a candlestick bar for the given symbol and interval + */ + void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @see #getCandlestickBars(String, CandlestickInterval, BinanceApiCallback) + */ + void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback); + + /** + * Get 24 hour price change statistics (asynchronous). + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param callback the callback that handles the response + */ + void get24HrPriceStatistics(String symbol, BinanceApiCallback callback); + + /** + * Get 24 hour price change statistics for all symbols (asynchronous). + * + * @param callback the callback that handles the response + */ + void getAll24HrPriceStatistics(BinanceApiCallback> callback); + + /** + * Get Latest price for all symbols (asynchronous). + * + * @param callback the callback that handles the response + */ + void getAllPrices(BinanceApiCallback> callback); + + /** + * Get latest price for symbol (asynchronous). + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param callback the callback that handles the response + */ + void getPrice(String symbol , BinanceApiCallback callback); + + /** + * Get best price/qty on the order book for all symbols (asynchronous). + * + * @param callback the callback that handles the response + */ + void getBookTickers(BinanceApiCallback> callback); + + // Account endpoints + + /** + * Send in a new order (asynchronous) + * + * @param order the new order to submit. + * @param callback the callback that handles the response + */ + void newOrder(NewOrder order, BinanceApiCallback callback); + + /** + * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. + * + * @param order the new TEST order to submit. + * @param callback the callback that handles the response + */ + void newOrderTest(NewOrder order, BinanceApiCallback callback); + + /** + * Check an order's status (asynchronous). + * + * @param orderStatusRequest order status request parameters + * @param callback the callback that handles the response + */ + void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback); + + /** + * Cancel an active order (asynchronous). + * + * @param cancelOrderRequest order status request parameters + * @param callback the callback that handles the response + */ + void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); + + /** + * Get all open orders on a symbol (asynchronous). + * + * @param orderRequest order request parameters + * @param callback the callback that handles the response + */ + void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback); + + /** + * Get all account orders; active, canceled, or filled. + * + * @param orderRequest order request parameters + * @param callback the callback that handles the response + */ + void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback); + + /** + * Get current account information (async). + */ + void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback); + + /** + * Get current account information using default parameters (async). + */ + void getAccount(BinanceApiCallback callback); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @param fromId TradeId to fetch from. Default gets most recent trades. + * @param callback the callback that handles the response with a list of trades + */ + void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @param callback the callback that handles the response with a list of trades + */ + void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param callback the callback that handles the response with a list of trades + */ + void getMyTrades(String symbol, BinanceApiCallback> callback); + + /** + * Submit a withdraw request. + * + * Enable Withdrawals option has to be active in the API settings. + * + * @param asset asset symbol to withdraw + * @param address address to withdraw to + * @param amount amount to withdraw + * @param name description/alias of the address + * @param addressTag Secondary address identifier for coins like XRP,XMR etc. + */ + void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback); + + /** + * Fetch account deposit history. + * + * @param callback the callback that handles the response and returns the deposit history + */ + void getDepositHistory(String asset, BinanceApiCallback callback); + + /** + * Fetch account withdraw history. + * + * @param callback the callback that handles the response and returns the withdraw history + */ + void getWithdrawHistory(String asset, BinanceApiCallback callback); + + /** + * Fetch deposit address. + * + * @param callback the callback that handles the response and returns the deposit address + */ + void getDepositAddress(String asset, BinanceApiCallback callback); + + // User stream endpoints + + /** + * Start a new user data stream. + * + * @param callback the callback that handles the response which contains a listenKey + */ + void startUserDataStream(BinanceApiCallback callback); + + /** + * PING a user data stream to prevent a time out. + * + * @param listenKey listen key that identifies a data stream + * @param callback the callback that handles the response which contains a listenKey + */ + void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback); + + /** + * Close out a new user data stream. + * + * @param listenKey listen key that identifies a data stream + * @param callback the callback that handles the response which contains a listenKey + */ + void closeUserDataStream(String listenKey, BinanceApiCallback callback); } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/BinanceApiCallback.java b/src/main/java/com/binance/api/client/BinanceApiCallback.java old mode 100644 new mode 100755 index f492cc1da..3112bd793 --- a/src/main/java/com/binance/api/client/BinanceApiCallback.java +++ b/src/main/java/com/binance/api/client/BinanceApiCallback.java @@ -1,24 +1,24 @@ -package com.binance.api.client; - -/** - * BinanceApiCallback is a functional interface used together with the BinanceApiAsyncClient to provide a non-blocking REST client. - * - * @param the return type from the callback - */ -@FunctionalInterface -public interface BinanceApiCallback { - - /** - * Called whenever a response comes back from the Binance API. - * - * @param response the expected response object - */ - void onResponse(T response); - - /** - * Called whenever an error occurs. - * - * @param cause the cause of the failure - */ - default void onFailure(Throwable cause) {} +package com.binance.api.client; + +/** + * BinanceApiCallback is a functional interface used together with the BinanceApiAsyncClient to provide a non-blocking REST client. + * + * @param the return type from the callback + */ +@FunctionalInterface +public interface BinanceApiCallback { + + /** + * Called whenever a response comes back from the Binance API. + * + * @param response the expected response object + */ + void onResponse(T response); + + /** + * Called whenever an error occurs. + * + * @param cause the cause of the failure + */ + default void onFailure(Throwable cause) {} } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java old mode 100644 new mode 100755 index 7c05f83bf..a529e237c --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -1,75 +1,88 @@ -package com.binance.api.client; - -import com.binance.api.client.impl.BinanceApiAsyncRestClientImpl; -import com.binance.api.client.impl.BinanceApiRestClientImpl; -import com.binance.api.client.impl.BinanceApiWebSocketClientImpl; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.getSharedClient; - -/** - * A factory for creating BinanceApi client objects. - */ -public class BinanceApiClientFactory { - - /** - * API Key - */ - private String apiKey; - - /** - * Secret. - */ - private String secret; - - /** - * Instantiates a new binance api client factory. - * - * @param apiKey the API key - * @param secret the Secret - */ - private BinanceApiClientFactory(String apiKey, String secret) { - this.apiKey = apiKey; - this.secret = secret; - } - - /** - * New instance. - * - * @param apiKey the API key - * @param secret the Secret - * - * @return the binance api client factory - */ - public static BinanceApiClientFactory newInstance(String apiKey, String secret) { - return new BinanceApiClientFactory(apiKey, secret); - } - - /** - * New instance without authentication. - * - * @return the binance api client factory - */ - public static BinanceApiClientFactory newInstance() { - return new BinanceApiClientFactory(null, null); - } - - /** - * Creates a new synchronous/blocking REST client. - */ - public BinanceApiRestClient newRestClient() { - return new BinanceApiRestClientImpl(apiKey, secret); - } - - /** - * Creates a new asynchronous/non-blocking REST client. - */ - public BinanceApiAsyncRestClient newAsyncRestClient() {return new BinanceApiAsyncRestClientImpl(apiKey, secret); - } - - /** - * Creates a new web socket client used for handling data streams. - */ - public BinanceApiWebSocketClient newWebSocketClient() { - return new BinanceApiWebSocketClientImpl(getSharedClient()); - } -} +package com.binance.api.client; + +import com.binance.api.client.impl.*; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.getSharedClient; + +/** + * A factory for creating BinanceApi client objects. + */ +public class BinanceApiClientFactory { + + /** + * API Key + */ + private String apiKey; + + /** + * Secret. + */ + private String secret; + + /** + * Instantiates a new binance api client factory. + * + * @param apiKey the API key + * @param secret the Secret + */ + private BinanceApiClientFactory(String apiKey, String secret) { + this.apiKey = apiKey; + this.secret = secret; + } + + /** + * New instance. + * + * @param apiKey the API key + * @param secret the Secret + * + * @return the binance api client factory + */ + public static BinanceApiClientFactory newInstance(String apiKey, String secret) { + return new BinanceApiClientFactory(apiKey, secret); + } + + /** + * New instance without authentication. + * + * @return the binance api client factory + */ + public static BinanceApiClientFactory newInstance() { + return new BinanceApiClientFactory(null, null); + } + + /** + * Creates a new synchronous/blocking REST client. + */ + public BinanceApiRestClient newRestClient() { + return new BinanceApiRestClientImpl(apiKey, secret); + } + + /** + * Creates a new asynchronous/non-blocking REST client. + */ + public BinanceApiAsyncRestClient newAsyncRestClient() { + return new BinanceApiAsyncRestClientImpl(apiKey, secret); + } + + /** + * Creates a new asynchronous/non-blocking Margin REST client. + */ + public BinanceApiAsyncMarginRestClient newAsyncMarginRestClient() { + return new BinanceApiAsyncMarginRestClientImpl(apiKey, secret); + } + + /** + * Creates a new synchronous/blocking Margin REST client. + */ + public BinanceApiMarginRestClient newMarginRestClient() { + return new BinanceApiMarginRestClientImpl(apiKey, secret); + } + + /** + * Creates a new web socket client used for handling data streams. + */ + public BinanceApiWebSocketClient newWebSocketClient() { + return new BinanceApiWebSocketClientImpl(getSharedClient()); + } +} diff --git a/src/main/java/com/binance/api/client/BinanceApiError.java b/src/main/java/com/binance/api/client/BinanceApiError.java old mode 100644 new mode 100755 index c5adc184e..b0d98ab8c --- a/src/main/java/com/binance/api/client/BinanceApiError.java +++ b/src/main/java/com/binance/api/client/BinanceApiError.java @@ -1,44 +1,44 @@ -package com.binance.api.client; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Binance API error object. - */ -public class BinanceApiError { - - /** - * Error code. - */ - private int code; - - /** - * Error message. - */ - private String msg; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("code", code) - .append("msg", msg) - .toString(); - } -} +package com.binance.api.client; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Binance API error object. + */ +public class BinanceApiError { + + /** + * Error code. + */ + private int code; + + /** + * Error message. + */ + private String msg; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("code", code) + .append("msg", msg) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java new file mode 100755 index 000000000..3e146ee39 --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -0,0 +1,103 @@ +package com.binance.api.client; + +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import java.util.List; + +public interface BinanceApiMarginRestClient { + /** + * Get current margin account information using default parameters. + */ + MarginAccount getAccount(); + + /** + * Get all open orders on margin account for a symbol. + * + * @param orderRequest order request parameters + */ + List getOpenOrders(OrderRequest orderRequest); + + /** + * Send in a new margin order. + * + * @param order the new order to submit. + * @return a response containing details about the newly placed order. + */ + NewOrderResponse newOrder(NewOrder order); + + /** + * Cancel an active margin order. + * + * @param cancelOrderRequest order status request parameters + */ + CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); + + /** + * Check margin order's status. + * @param orderStatusRequest order status request options/filters + * + * @return an order + */ + Order getOrderStatus(OrderStatusRequest orderStatusRequest); + + /** + * Get margin trades for a specific symbol. + * + * @param symbol symbol to get trades from + * @return a list of trades + */ + List getMyTrades(String symbol); + + // User stream endpoints + + /** + * Start a new user data stream. + * + * @return a listen key that can be used with data streams + */ + String startUserDataStream(); + + /** + * PING a user data stream to prevent a time out. + * + * @param listenKey listen key that identifies a data stream + */ + void keepAliveUserDataStream(String listenKey); + + /** + * Execute transfer between spot account and margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + MarginTransaction transfer(String asset, String amount, TransferType type); + + /** + * Apply for a loan + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + MarginTransaction borrow(String asset, String amount); + + /** + * Repay loan for margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + MarginTransaction repay(String asset, String amount); + + /** + * Query loan record + * @param asset asset to query + * @param txId the tranId in POST /sapi/v1/margin/loan + * @return loan records + */ + LoanQueryResult queryLoan(String asset, String txId); +} diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java old mode 100644 new mode 100755 index e405d4a7f..82a6a2be9 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -1,298 +1,298 @@ -package com.binance.api.client; - -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -/** - * Binance API façade, supporting synchronous/blocking access Binance's REST API. - */ -public interface BinanceApiRestClient { - - // General endpoints - - /** - * Test connectivity to the Rest API. - */ - void ping(); - - /** - * Test connectivity to the Rest API and get the current server time. - * - * @return current server time. - */ - Long getServerTime(); - - /** - * @return Current exchange trading rules and symbol information - */ - ExchangeInfo getExchangeInfo(); - - /** - * @return All the supported assets and whether or not they can be withdrawn. - */ - List getAllAssets(); - - // Market Data endpoints - - /** - * Get order book of a symbol. - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit depth of the order book (max 100) - */ - OrderBook getOrderBook(String symbol, Integer limit); - - /** - * Get recent trades (up to last 500). Weight: 1 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - */ - List getTrades(String symbol, Integer limit); - - /** - * Get older trades. Weight: 5 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - * @param fromId TradeId to fetch from. Default gets most recent trades. - */ - List getHistoricalTrades(String symbol, Integer limit, Long fromId); - - /** - * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with - * the same price will have the quantity aggregated. - * - * If both startTime and endTime are sent, limitshould not - * be sent AND the distance between startTime and endTime must be less than 24 hours. - * - * @param symbol symbol to aggregate (mandatory) - * @param fromId ID to get aggregate trades from INCLUSIVE (optional) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). - * @return a list of aggregate trades for the given symbol - */ - List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime); - - /** - * Return the most recent aggregate trades for symbol - * - * @see #getAggTrades(String, String, Integer, Long, Long) - */ - List getAggTrades(String symbol); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @param symbol symbol to aggregate (mandatory) - * @param interval candlestick interval (mandatory) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). - * @return a candlestick bar for the given symbol and interval - */ - List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @see #getCandlestickBars(String, CandlestickInterval, Integer, Long, Long) - */ - List getCandlestickBars(String symbol, CandlestickInterval interval); - - /** - * Get 24 hour price change statistics. - * - * @param symbol ticker symbol (e.g. ETHBTC) - */ - TickerStatistics get24HrPriceStatistics(String symbol); - - /** - * Get 24 hour price change statistics for all symbols. - */ - List getAll24HrPriceStatistics(); - - /** - * Get Latest price for all symbols. - */ - List getAllPrices(); - - /** - * Get latest price for symbol. - * - * @param symbol ticker symbol (e.g. ETHBTC) - */ - TickerPrice getPrice(String symbol); - - /** - * Get best price/qty on the order book for all symbols. - */ - List getBookTickers(); - - // Account endpoints - - /** - * Send in a new order. - * - * @param order the new order to submit. - * @return a response containing details about the newly placed order. - */ - NewOrderResponse newOrder(NewOrder order); - - /** - * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. - * - * @param order the new TEST order to submit. - */ - void newOrderTest(NewOrder order); - - /** - * Check an order's status. - * @param orderStatusRequest order status request options/filters - * - * @return an order - */ - Order getOrderStatus(OrderStatusRequest orderStatusRequest); - - /** - * Cancel an active order. - * - * @param cancelOrderRequest order status request parameters - */ - CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); - - /** - * Get all open orders on a symbol. - * - * @param orderRequest order request parameters - * @return a list of all account open orders on a symbol. - */ - List getOpenOrders(OrderRequest orderRequest); - - /** - * Get all account orders; active, canceled, or filled. - * - * @param orderRequest order request parameters - * @return a list of all account orders - */ - List getAllOrders(AllOrdersRequest orderRequest); - - /** - * Get current account information. - */ - Account getAccount(Long recvWindow, Long timestamp); - - /** - * Get current account information using default parameters. - */ - Account getAccount(); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @param fromId TradeId to fetch from. Default gets most recent trades. - * @return a list of trades - */ - List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @return a list of trades - */ - List getMyTrades(String symbol, Integer limit); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @return a list of trades - */ - List getMyTrades(String symbol); - - /** - * Submit a withdraw request. - * - * Enable Withdrawals option has to be active in the API settings. - * - * @param asset asset symbol to withdraw - * @param address address to withdraw to - * @param amount amount to withdraw - * @param name description/alias of the address - * @param addressTag Secondary address identifier for coins like XRP,XMR etc. - */ - WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag); - - /** - * Fetch account deposit history. - * - * @return deposit history, containing a list of deposits - */ - DepositHistory getDepositHistory(String asset); - - /** - * Fetch account withdraw history. - * - * @return withdraw history, containing a list of withdrawals - */ - WithdrawHistory getWithdrawHistory(String asset); - - /** - * Fetch deposit address. - * - * @return deposit address for a given asset. - */ - DepositAddress getDepositAddress(String asset); - - // User stream endpoints - - /** - * Start a new user data stream. - * - * @return a listen key that can be used with data streams - */ - String startUserDataStream(); - - /** - * PING a user data stream to prevent a time out. - * - * @param listenKey listen key that identifies a data stream - */ - void keepAliveUserDataStream(String listenKey); - - /** - * Close out a new user data stream. - * - * @param listenKey listen key that identifies a data stream - */ - void closeUserDataStream(String listenKey); -} +package com.binance.api.client; + +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +/** + * Binance API façade, supporting synchronous/blocking access Binance's REST API. + */ +public interface BinanceApiRestClient { + + // General endpoints + + /** + * Test connectivity to the Rest API. + */ + void ping(); + + /** + * Test connectivity to the Rest API and get the current server time. + * + * @return current server time. + */ + Long getServerTime(); + + /** + * @return Current exchange trading rules and symbol information + */ + ExchangeInfo getExchangeInfo(); + + /** + * @return All the supported assets and whether or not they can be withdrawn. + */ + List getAllAssets(); + + // Market Data endpoints + + /** + * Get order book of a symbol. + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit depth of the order book (max 100) + */ + OrderBook getOrderBook(String symbol, Integer limit); + + /** + * Get recent trades (up to last 500). Weight: 1 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + */ + List getTrades(String symbol, Integer limit); + + /** + * Get older trades. Weight: 5 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + * @param fromId TradeId to fetch from. Default gets most recent trades. + */ + List getHistoricalTrades(String symbol, Integer limit, Long fromId); + + /** + * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with + * the same price will have the quantity aggregated. + * + * If both startTime and endTime are sent, limitshould not + * be sent AND the distance between startTime and endTime must be less than 24 hours. + * + * @param symbol symbol to aggregate (mandatory) + * @param fromId ID to get aggregate trades from INCLUSIVE (optional) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). + * @return a list of aggregate trades for the given symbol + */ + List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime); + + /** + * Return the most recent aggregate trades for symbol + * + * @see #getAggTrades(String, String, Integer, Long, Long) + */ + List getAggTrades(String symbol); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @param symbol symbol to aggregate (mandatory) + * @param interval candlestick interval (mandatory) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). + * @return a candlestick bar for the given symbol and interval + */ + List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @see #getCandlestickBars(String, CandlestickInterval, Integer, Long, Long) + */ + List getCandlestickBars(String symbol, CandlestickInterval interval); + + /** + * Get 24 hour price change statistics. + * + * @param symbol ticker symbol (e.g. ETHBTC) + */ + TickerStatistics get24HrPriceStatistics(String symbol); + + /** + * Get 24 hour price change statistics for all symbols. + */ + List getAll24HrPriceStatistics(); + + /** + * Get Latest price for all symbols. + */ + List getAllPrices(); + + /** + * Get latest price for symbol. + * + * @param symbol ticker symbol (e.g. ETHBTC) + */ + TickerPrice getPrice(String symbol); + + /** + * Get best price/qty on the order book for all symbols. + */ + List getBookTickers(); + + // Account endpoints + + /** + * Send in a new order. + * + * @param order the new order to submit. + * @return a response containing details about the newly placed order. + */ + NewOrderResponse newOrder(NewOrder order); + + /** + * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. + * + * @param order the new TEST order to submit. + */ + void newOrderTest(NewOrder order); + + /** + * Check an order's status. + * @param orderStatusRequest order status request options/filters + * + * @return an order + */ + Order getOrderStatus(OrderStatusRequest orderStatusRequest); + + /** + * Cancel an active order. + * + * @param cancelOrderRequest order status request parameters + */ + CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); + + /** + * Get all open orders on a symbol. + * + * @param orderRequest order request parameters + * @return a list of all account open orders on a symbol. + */ + List getOpenOrders(OrderRequest orderRequest); + + /** + * Get all account orders; active, canceled, or filled. + * + * @param orderRequest order request parameters + * @return a list of all account orders + */ + List getAllOrders(AllOrdersRequest orderRequest); + + /** + * Get current account information. + */ + Account getAccount(Long recvWindow, Long timestamp); + + /** + * Get current account information using default parameters. + */ + Account getAccount(); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @param fromId TradeId to fetch from. Default gets most recent trades. + * @return a list of trades + */ + List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @return a list of trades + */ + List getMyTrades(String symbol, Integer limit); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @return a list of trades + */ + List getMyTrades(String symbol); + + /** + * Submit a withdraw request. + * + * Enable Withdrawals option has to be active in the API settings. + * + * @param asset asset symbol to withdraw + * @param address address to withdraw to + * @param amount amount to withdraw + * @param name description/alias of the address + * @param addressTag Secondary address identifier for coins like XRP,XMR etc. + */ + WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag); + + /** + * Fetch account deposit history. + * + * @return deposit history, containing a list of deposits + */ + DepositHistory getDepositHistory(String asset); + + /** + * Fetch account withdraw history. + * + * @return withdraw history, containing a list of withdrawals + */ + WithdrawHistory getWithdrawHistory(String asset); + + /** + * Fetch deposit address. + * + * @return deposit address for a given asset. + */ + DepositAddress getDepositAddress(String asset); + + // User stream endpoints + + /** + * Start a new user data stream. + * + * @return a listen key that can be used with data streams + */ + String startUserDataStream(); + + /** + * PING a user data stream to prevent a time out. + * + * @param listenKey listen key that identifies a data stream + */ + void keepAliveUserDataStream(String listenKey); + + /** + * Close out a new user data stream. + * + * @param listenKey listen key that identifies a data stream + */ + void closeUserDataStream(String listenKey); +} diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java old mode 100644 new mode 100755 index 7961efc49..ba78819ac --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -1,68 +1,68 @@ -package com.binance.api.client; - -import com.binance.api.client.domain.event.AggTradeEvent; -import com.binance.api.client.domain.event.AllMarketTickersEvent; -import com.binance.api.client.domain.event.CandlestickEvent; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; -import com.binance.api.client.domain.market.CandlestickInterval; - -import java.io.Closeable; -import java.util.List; - -/** - * Binance API data streaming façade, supporting streaming of events through web sockets. - */ -public interface BinanceApiWebSocketClient extends Closeable { - - /** - * Open a new web socket to receive {@link DepthEvent depthEvents} on a callback. - * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onDepthEvent(String symbols, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link CandlestickEvent candlestickEvents} on a callback. - * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param interval the interval of the candles tick events required - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link AggTradeEvent aggTradeEvents} on a callback. - * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link UserDataUpdateEvent userDataUpdateEvents} on a callback. - * - * @param listenKey the listen key to subscribe to. - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link AllMarketTickersEvent allMarketTickersEvents} on a callback. - * - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onAllMarketTickersEvent(BinanceApiCallback> callback); - - /** - * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. - */ - @Deprecated - void close(); -} +package com.binance.api.client; + +import com.binance.api.client.domain.event.AggTradeEvent; +import com.binance.api.client.domain.event.AllMarketTickersEvent; +import com.binance.api.client.domain.event.CandlestickEvent; +import com.binance.api.client.domain.event.DepthEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.binance.api.client.domain.market.CandlestickInterval; + +import java.io.Closeable; +import java.util.List; + +/** + * Binance API data streaming façade, supporting streaming of events through web sockets. + */ +public interface BinanceApiWebSocketClient extends Closeable { + + /** + * Open a new web socket to receive {@link DepthEvent depthEvents} on a callback. + * + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onDepthEvent(String symbols, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link CandlestickEvent candlestickEvents} on a callback. + * + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param interval the interval of the candles tick events required + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link AggTradeEvent aggTradeEvents} on a callback. + * + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link UserDataUpdateEvent userDataUpdateEvents} on a callback. + * + * @param listenKey the listen key to subscribe to. + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link AllMarketTickersEvent allMarketTickersEvents} on a callback. + * + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onAllMarketTickersEvent(BinanceApiCallback> callback); + + /** + * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. + */ + @Deprecated + void close(); +} diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java old mode 100644 new mode 100755 index bcc39452d..7d829f119 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -1,53 +1,58 @@ -package com.binance.api.client.constant; - -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * Constants used throughout Binance's API. - */ -public class BinanceApiConstants { - - /** - * REST API base URL. - */ - public static final String API_BASE_URL = "https://api.binance.com"; - - /** - * Streaming API base URL. - */ - public static final String WS_API_BASE_URL = "wss://stream.binance.com:9443/ws"; - - /** - * Asset info base URL. - */ - public static final String ASSET_INFO_API_BASE_URL = "https://www.binance.com/"; - - /** - * HTTP Header to be used for API-KEY authentication. - */ - public static final String API_KEY_HEADER = "X-MBX-APIKEY"; - - /** - * Decorator to indicate that an endpoint requires an API key. - */ - public static final String ENDPOINT_SECURITY_TYPE_APIKEY = "APIKEY"; - public static final String ENDPOINT_SECURITY_TYPE_APIKEY_HEADER = ENDPOINT_SECURITY_TYPE_APIKEY + ": #"; - - /** - * Decorator to indicate that an endpoint requires a signature. - */ - public static final String ENDPOINT_SECURITY_TYPE_SIGNED = "SIGNED"; - public static final String ENDPOINT_SECURITY_TYPE_SIGNED_HEADER = ENDPOINT_SECURITY_TYPE_SIGNED + ": #"; - - /** - * Default receiving window. - */ - public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; - - /** - * Default ToStringStyle used by toString methods. - * Override this to change the output format of the overridden toString methods. - * - Example ToStringStyle.JSON_STYLE - */ - public static ToStringStyle TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; -} +package com.binance.api.client.constant; + +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * Constants used throughout Binance's API. + */ +public class BinanceApiConstants { + + /** + * REST API base URL. + */ + public static final String API_BASE_URL = "https://api.binance.com"; + + /** + * Streaming API base URL. + */ + public static final String WS_API_BASE_URL = "wss://stream.binance.com:9443/ws"; + + /** + * Asset info base URL. + */ + public static final String ASSET_INFO_API_BASE_URL = "https://www.binance.com/"; + + /** + * HTTP Header to be used for API-KEY authentication. + */ + public static final String API_KEY_HEADER = "X-MBX-APIKEY"; + + /** + * Decorator to indicate that an endpoint requires an API key. + */ + public static final String ENDPOINT_SECURITY_TYPE_APIKEY = "APIKEY"; + public static final String ENDPOINT_SECURITY_TYPE_APIKEY_HEADER = ENDPOINT_SECURITY_TYPE_APIKEY + ": #"; + + /** + * Decorator to indicate that an endpoint requires a signature. + */ + public static final String ENDPOINT_SECURITY_TYPE_SIGNED = "SIGNED"; + public static final String ENDPOINT_SECURITY_TYPE_SIGNED_HEADER = ENDPOINT_SECURITY_TYPE_SIGNED + ": #"; + + /** + * Default receiving window. + */ + public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; + + /** + * Default margin receiving window. + */ + public static final long DEFAULT_MARGIN_RECEIVING_WINDOW = 5_000L; + + /** + * Default ToStringStyle used by toString methods. + * Override this to change the output format of the overridden toString methods. + * - Example ToStringStyle.JSON_STYLE + */ + public static ToStringStyle TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; +} diff --git a/src/main/java/com/binance/api/client/domain/ExecutionType.java b/src/main/java/com/binance/api/client/domain/ExecutionType.java old mode 100644 new mode 100755 index 4da14d863..1e2a5e4f8 --- a/src/main/java/com/binance/api/client/domain/ExecutionType.java +++ b/src/main/java/com/binance/api/client/domain/ExecutionType.java @@ -1,16 +1,16 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Order execution type. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum ExecutionType { - NEW, - CANCELED, - REPLACED, - REJECTED, - TRADE, - EXPIRED +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Order execution type. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum ExecutionType { + NEW, + CANCELED, + REPLACED, + REJECTED, + TRADE, + EXPIRED } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/LoanStatus.java b/src/main/java/com/binance/api/client/domain/LoanStatus.java new file mode 100755 index 000000000..802e9981b --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/LoanStatus.java @@ -0,0 +1,11 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a submitted order. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum LoanStatus { + PENDING, CONFIRMED, FAILED +} diff --git a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java old mode 100644 new mode 100755 index ff9374e8a..52a1e3990 --- a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java +++ b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java @@ -1,21 +1,21 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Order reject reason values. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderRejectReason { - NONE, - UNKNOWN_INSTRUMENT, - MARKET_CLOSED, - PRICE_QTY_EXCEED_HARD_LIMITS, - UNKNOWN_ORDER, - DUPLICATE_ORDER, - UNKNOWN_ACCOUNT, - INSUFFICIENT_BALANCE, - ACCOUNT_INACTIVE, - ACCOUNT_CANNOT_SETTLE, - ORDER_WOULD_TRIGGER_IMMEDIATELY +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Order reject reason values. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderRejectReason { + NONE, + UNKNOWN_INSTRUMENT, + MARKET_CLOSED, + PRICE_QTY_EXCEED_HARD_LIMITS, + UNKNOWN_ORDER, + DUPLICATE_ORDER, + UNKNOWN_ACCOUNT, + INSUFFICIENT_BALANCE, + ACCOUNT_INACTIVE, + ACCOUNT_CANNOT_SETTLE, + ORDER_WOULD_TRIGGER_IMMEDIATELY } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/OrderSide.java b/src/main/java/com/binance/api/client/domain/OrderSide.java old mode 100644 new mode 100755 index db74f9373..2f01d92db --- a/src/main/java/com/binance/api/client/domain/OrderSide.java +++ b/src/main/java/com/binance/api/client/domain/OrderSide.java @@ -1,12 +1,12 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Buy/Sell order side. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderSide { - BUY, - SELL -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Buy/Sell order side. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderSide { + BUY, + SELL +} diff --git a/src/main/java/com/binance/api/client/domain/OrderStatus.java b/src/main/java/com/binance/api/client/domain/OrderStatus.java old mode 100644 new mode 100755 index 81656c722..7b15e980b --- a/src/main/java/com/binance/api/client/domain/OrderStatus.java +++ b/src/main/java/com/binance/api/client/domain/OrderStatus.java @@ -1,17 +1,17 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Status of a submitted order. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderStatus { - NEW, - PARTIALLY_FILLED, - FILLED, - CANCELED, - PENDING_CANCEL, - REJECTED, - EXPIRED -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a submitted order. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderStatus { + NEW, + PARTIALLY_FILLED, + FILLED, + CANCELED, + PENDING_CANCEL, + REJECTED, + EXPIRED +} diff --git a/src/main/java/com/binance/api/client/domain/OrderType.java b/src/main/java/com/binance/api/client/domain/OrderType.java old mode 100644 new mode 100755 index 11d484e5e..78ee6b6fe --- a/src/main/java/com/binance/api/client/domain/OrderType.java +++ b/src/main/java/com/binance/api/client/domain/OrderType.java @@ -1,17 +1,17 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Type of order to submit to the system. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderType { - LIMIT, - MARKET, - STOP_LOSS, - STOP_LOSS_LIMIT, - TAKE_PROFIT, - TAKE_PROFIT_LIMIT, - LIMIT_MAKER -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Type of order to submit to the system. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderType { + LIMIT, + MARKET, + STOP_LOSS, + STOP_LOSS_LIMIT, + TAKE_PROFIT, + TAKE_PROFIT_LIMIT, + LIMIT_MAKER +} diff --git a/src/main/java/com/binance/api/client/domain/TimeInForce.java b/src/main/java/com/binance/api/client/domain/TimeInForce.java old mode 100644 new mode 100755 index 2d2f50db1..83043ce7f --- a/src/main/java/com/binance/api/client/domain/TimeInForce.java +++ b/src/main/java/com/binance/api/client/domain/TimeInForce.java @@ -1,19 +1,19 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Time in force to indicate how long an order will remain active before it is executed or expires. - * - * GTC (Good-Til-Canceled) orders are effective until they are executed or canceled. - * IOC (Immediate or Cancel) orders fills all or part of an order immediately and cancels the remaining part of the order. - * FOK (Fill or Kill) orders fills all in its entirety, otherwise, the entire order will be cancelled. - * - * @see http://www.investopedia.com/terms/t/timeinforce.asp - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum TimeInForce { - GTC, - IOC, - FOK -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Time in force to indicate how long an order will remain active before it is executed or expires. + * + * GTC (Good-Til-Canceled) orders are effective until they are executed or canceled. + * IOC (Immediate or Cancel) orders fills all or part of an order immediately and cancels the remaining part of the order. + * FOK (Fill or Kill) orders fills all in its entirety, otherwise, the entire order will be cancelled. + * + * @see http://www.investopedia.com/terms/t/timeinforce.asp + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum TimeInForce { + GTC, + IOC, + FOK +} diff --git a/src/main/java/com/binance/api/client/domain/TransferType.java b/src/main/java/com/binance/api/client/domain/TransferType.java new file mode 100755 index 000000000..7d39d18a7 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/TransferType.java @@ -0,0 +1,21 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a submitted order. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum TransferType { + SPOT_TO_MARGIN("1"), MARGIN_TO_SPOT("2"); + + private String value; + + TransferType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Account.java b/src/main/java/com/binance/api/client/domain/account/Account.java old mode 100644 new mode 100755 index e14edaeaa..4356bfccb --- a/src/main/java/com/binance/api/client/domain/account/Account.java +++ b/src/main/java/com/binance/api/client/domain/account/Account.java @@ -1,165 +1,165 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Account information. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Account { - - /** - * Maker commission. - */ - private int makerCommission; - - /** - * Taker commission. - */ - private int takerCommission; - - /** - * Buyer commission. - */ - private int buyerCommission; - - /** - * Seller commission. - */ - private int sellerCommission; - - /** - * Whether or not this account can trade. - */ - private boolean canTrade; - - /** - * Whether or not it is possible to withdraw from this account. - */ - private boolean canWithdraw; - - /** - * Whether or not it is possible to deposit into this account. - */ - private boolean canDeposit; - - /** - * Last account update time. - */ - private long updateTime; - - /** - * List of asset balances of this account. - */ - private List balances; - - public int getMakerCommission() { - return makerCommission; - } - - public void setMakerCommission(int makerCommission) { - this.makerCommission = makerCommission; - } - - public int getTakerCommission() { - return takerCommission; - } - - public void setTakerCommission(int takerCommission) { - this.takerCommission = takerCommission; - } - - public int getBuyerCommission() { - return buyerCommission; - } - - public void setBuyerCommission(int buyerCommission) { - this.buyerCommission = buyerCommission; - } - - public int getSellerCommission() { - return sellerCommission; - } - - public void setSellerCommission(int sellerCommission) { - this.sellerCommission = sellerCommission; - } - - public boolean isCanTrade() { - return canTrade; - } - - public void setCanTrade(boolean canTrade) { - this.canTrade = canTrade; - } - - public boolean isCanWithdraw() { - return canWithdraw; - } - - public void setCanWithdraw(boolean canWithdraw) { - this.canWithdraw = canWithdraw; - } - - public boolean isCanDeposit() { - return canDeposit; - } - - public void setCanDeposit(boolean canDeposit) { - this.canDeposit = canDeposit; - } - - public long getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(long updateTime) { - this.updateTime = updateTime; - } - - public List getBalances() { - return balances; - } - - public void setBalances(List balances) { - this.balances = balances; - } - - /** - * Returns the asset balance for a given symbol. - * - * @param symbol asset symbol to obtain the balances from - * @return an asset balance for the given symbol which can be 0 in case the symbol has no balance in the account - */ - public AssetBalance getAssetBalance(String symbol) { - for (AssetBalance assetBalance : balances) { - if (symbol.equals(assetBalance.getAsset())) { - return assetBalance; - } - } - AssetBalance emptyBalance = new AssetBalance(); - emptyBalance.setAsset(symbol); - emptyBalance.setFree("0"); - emptyBalance.setLocked("0"); - return emptyBalance; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("makerCommission", makerCommission) - .append("takerCommission", takerCommission) - .append("buyerCommission", buyerCommission) - .append("sellerCommission", sellerCommission) - .append("canTrade", canTrade) - .append("canWithdraw", canWithdraw) - .append("canDeposit", canDeposit) - .append("updateTime", updateTime) - .append("balances", balances) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Account information. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Account { + + /** + * Maker commission. + */ + private int makerCommission; + + /** + * Taker commission. + */ + private int takerCommission; + + /** + * Buyer commission. + */ + private int buyerCommission; + + /** + * Seller commission. + */ + private int sellerCommission; + + /** + * Whether or not this account can trade. + */ + private boolean canTrade; + + /** + * Whether or not it is possible to withdraw from this account. + */ + private boolean canWithdraw; + + /** + * Whether or not it is possible to deposit into this account. + */ + private boolean canDeposit; + + /** + * Last account update time. + */ + private long updateTime; + + /** + * List of asset balances of this account. + */ + private List balances; + + public int getMakerCommission() { + return makerCommission; + } + + public void setMakerCommission(int makerCommission) { + this.makerCommission = makerCommission; + } + + public int getTakerCommission() { + return takerCommission; + } + + public void setTakerCommission(int takerCommission) { + this.takerCommission = takerCommission; + } + + public int getBuyerCommission() { + return buyerCommission; + } + + public void setBuyerCommission(int buyerCommission) { + this.buyerCommission = buyerCommission; + } + + public int getSellerCommission() { + return sellerCommission; + } + + public void setSellerCommission(int sellerCommission) { + this.sellerCommission = sellerCommission; + } + + public boolean isCanTrade() { + return canTrade; + } + + public void setCanTrade(boolean canTrade) { + this.canTrade = canTrade; + } + + public boolean isCanWithdraw() { + return canWithdraw; + } + + public void setCanWithdraw(boolean canWithdraw) { + this.canWithdraw = canWithdraw; + } + + public boolean isCanDeposit() { + return canDeposit; + } + + public void setCanDeposit(boolean canDeposit) { + this.canDeposit = canDeposit; + } + + public long getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(long updateTime) { + this.updateTime = updateTime; + } + + public List getBalances() { + return balances; + } + + public void setBalances(List balances) { + this.balances = balances; + } + + /** + * Returns the asset balance for a given symbol. + * + * @param symbol asset symbol to obtain the balances from + * @return an asset balance for the given symbol which can be 0 in case the symbol has no balance in the account + */ + public AssetBalance getAssetBalance(String symbol) { + for (AssetBalance assetBalance : balances) { + if (symbol.equals(assetBalance.getAsset())) { + return assetBalance; + } + } + AssetBalance emptyBalance = new AssetBalance(); + emptyBalance.setAsset(symbol); + emptyBalance.setFree("0"); + emptyBalance.setLocked("0"); + return emptyBalance; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("makerCommission", makerCommission) + .append("takerCommission", takerCommission) + .append("buyerCommission", buyerCommission) + .append("sellerCommission", sellerCommission) + .append("canTrade", canTrade) + .append("canWithdraw", canWithdraw) + .append("canDeposit", canDeposit) + .append("updateTime", updateTime) + .append("balances", balances) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/AssetBalance.java b/src/main/java/com/binance/api/client/domain/account/AssetBalance.java old mode 100644 new mode 100755 index 3dae789ec..1d75d6307 --- a/src/main/java/com/binance/api/client/domain/account/AssetBalance.java +++ b/src/main/java/com/binance/api/client/domain/account/AssetBalance.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An asset balance in an Account. - * - * @see Account - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AssetBalance { - - /** - * Asset symbol. - */ - private String asset; - - /** - * Available balance. - */ - private String free; - - /** - * Locked by open orders. - */ - private String locked; - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - public String getFree() { - return free; - } - - public void setFree(String free) { - this.free = free; - } - - public String getLocked() { - return locked; - } - - public void setLocked(String locked) { - this.locked = locked; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("asset", asset) - .append("free", free) - .append("locked", locked) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An asset balance in an Account. + * + * @see Account + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AssetBalance { + + /** + * Asset symbol. + */ + private String asset; + + /** + * Available balance. + */ + private String free; + + /** + * Locked by open orders. + */ + private String locked; + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getFree() { + return free; + } + + public void setFree(String free) { + this.free = free; + } + + public String getLocked() { + return locked; + } + + public void setLocked(String locked) { + this.locked = locked; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("asset", asset) + .append("free", free) + .append("locked", locked) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Deposit.java b/src/main/java/com/binance/api/client/domain/account/Deposit.java old mode 100644 new mode 100755 index 14e8f779f..bfddd85e1 --- a/src/main/java/com/binance/api/client/domain/account/Deposit.java +++ b/src/main/java/com/binance/api/client/domain/account/Deposit.java @@ -1,88 +1,88 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A deposit that was done to a Binance account. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Deposit { - - /** - * Amount deposited. - */ - private String amount; - - /** - * Symbol. - */ - private String asset; - - /** - * Deposit time. - */ - private String insertTime; - - /** - * Transaction id - */ - private String txId; - - /** - * (0:pending,1:success) - */ - private int status; - - public String getAmount() { - return amount; - } - - public void setAmount(String amount) { - this.amount = amount; - } - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - public String getInsertTime() { - return insertTime; - } - - public void setInsertTime(String insertTime) { - this.insertTime = insertTime; - } - - public String getTxId() { - return txId; - } - - public void setTxId(String txId) { - this.txId = txId; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("amount", amount) - .append("asset", asset) - .append("insertTime", insertTime) - .append("txId", txId) - .append("status", status) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A deposit that was done to a Binance account. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Deposit { + + /** + * Amount deposited. + */ + private String amount; + + /** + * Symbol. + */ + private String asset; + + /** + * Deposit time. + */ + private String insertTime; + + /** + * Transaction id + */ + private String txId; + + /** + * (0:pending,1:success) + */ + private int status; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getInsertTime() { + return insertTime; + } + + public void setInsertTime(String insertTime) { + this.insertTime = insertTime; + } + + public String getTxId() { + return txId; + } + + public void setTxId(String txId) { + this.txId = txId; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("amount", amount) + .append("asset", asset) + .append("insertTime", insertTime) + .append("txId", txId) + .append("status", status) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/DepositAddress.java b/src/main/java/com/binance/api/client/domain/account/DepositAddress.java old mode 100644 new mode 100755 index 0aba6dc05..b13eb0dec --- a/src/main/java/com/binance/api/client/domain/account/DepositAddress.java +++ b/src/main/java/com/binance/api/client/domain/account/DepositAddress.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A deposit address for a given asset. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class DepositAddress { - - private String address; - - private boolean success; - - private String addressTag; - - private String asset; - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getAddressTag() { - return addressTag; - } - - public void setAddressTag(String addressTag) { - this.addressTag = addressTag; - } - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("address", address) - .append("success", success) - .append("addressTag", addressTag) - .append("asset", asset) - .toString(); - } +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A deposit address for a given asset. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DepositAddress { + + private String address; + + private boolean success; + + private String addressTag; + + private String asset; + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getAddressTag() { + return addressTag; + } + + public void setAddressTag(String addressTag) { + this.addressTag = addressTag; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("address", address) + .append("success", success) + .append("addressTag", addressTag) + .append("asset", asset) + .toString(); + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/DepositHistory.java b/src/main/java/com/binance/api/client/domain/account/DepositHistory.java old mode 100644 new mode 100755 index 4ac86ee7c..fc8d814e8 --- a/src/main/java/com/binance/api/client/domain/account/DepositHistory.java +++ b/src/main/java/com/binance/api/client/domain/account/DepositHistory.java @@ -1,57 +1,57 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * History of account deposits. - * - * @see Deposit - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class DepositHistory { - - @JsonProperty("depositList") - private List depositList; - - private boolean success; - - private String msg; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public List getDepositList() { - return depositList; - } - - public void setDepositList(List depositList) { - this.depositList = depositList; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("depositList", depositList) - .append("success", success) - .append("msg", msg) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * History of account deposits. + * + * @see Deposit + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DepositHistory { + + @JsonProperty("depositList") + private List depositList; + + private boolean success; + + private String msg; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public List getDepositList() { + return depositList; + } + + public void setDepositList(List depositList) { + this.depositList = depositList; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("depositList", depositList) + .append("success", success) + .append("msg", msg) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Loan.java b/src/main/java/com/binance/api/client/domain/account/Loan.java new file mode 100755 index 000000000..5424c9b17 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Loan.java @@ -0,0 +1,51 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.LoanStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents an executed trade history item. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Loan { + + private String asset; + private String principal; + private long timestamp; + private LoanStatus status; + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getPrincipal() { + return principal; + } + + public void setPrincipal(String principal) { + this.principal = principal; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public LoanStatus getStatus() { + return status; + } + + public void setStatus(LoanStatus status) { + this.status = status; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java b/src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java new file mode 100755 index 000000000..46a696531 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java @@ -0,0 +1,33 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * History of account withdrawals. + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class LoanQueryResult { + + private int total; + private List rows; + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + public List getRows() { + return rows; + } + + public void setRows(List rows) { + this.rows = rows; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginAccount.java b/src/main/java/com/binance/api/client/domain/account/MarginAccount.java new file mode 100755 index 000000000..86bd64f27 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginAccount.java @@ -0,0 +1,121 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Account information. + */ +@JsonIgnoreProperties +public class MarginAccount { + + private boolean borrowEnabled; + + private String marginLevel; + + private String totalAssetOfBtc; + + private String totalLiabilityOfBtc; + + private String totalNetAssetOfBtc; + + private boolean tradeEnabled; + + private boolean transferEnabled; + + private List userAssets; + + public boolean isBorrowEnabled() { + return borrowEnabled; + } + + public void setBorrowEnabled(boolean borrowEnabled) { + this.borrowEnabled = borrowEnabled; + } + + public String getMarginLevel() { + return marginLevel; + } + + public void setMarginLevel(String marginLevel) { + this.marginLevel = marginLevel; + } + + public String getTotalAssetOfBtc() { + return totalAssetOfBtc; + } + + public void setTotalAssetOfBtc(String totalAssetOfBtc) { + this.totalAssetOfBtc = totalAssetOfBtc; + } + + public String getTotalLiabilityOfBtc() { + return totalLiabilityOfBtc; + } + + public void setTotalLiabilityOfBtc(String totalLiabilityOfBtc) { + this.totalLiabilityOfBtc = totalLiabilityOfBtc; + } + + public String getTotalNetAssetOfBtc() { + return totalNetAssetOfBtc; + } + + public void setTotalNetAssetOfBtc(String totalNetAssetOfBtc) { + this.totalNetAssetOfBtc = totalNetAssetOfBtc; + } + + public boolean isTradeEnabled() { + return tradeEnabled; + } + + public void setTradeEnabled(boolean tradeEnabled) { + this.tradeEnabled = tradeEnabled; + } + + public boolean isTransferEnabled() { + return transferEnabled; + } + + public void setTransferEnabled(boolean transferEnabled) { + this.transferEnabled = transferEnabled; + } + + public List getUserAssets() { + return userAssets; + } + + public void setUserAssets(List userAssets) { + this.userAssets = userAssets; + } + + /** + * Returns the asset balance for a given symbol. + * + * @param symbol asset symbol to obtain the balances from + * @return an asset balance for the given symbol which can be 0 in case the symbol has no balance in the account + */ + public MarginAssetBalance getAssetBalance(final String symbol) { + return userAssets.stream() + .filter(marginAssetBalance -> marginAssetBalance.getAsset().equals(symbol)) + .findFirst() + .orElse(MarginAssetBalance.of(symbol)); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("borrowEnabled", borrowEnabled) + .append("marginLevel", marginLevel) + .append("totalAssetOfBtc", totalAssetOfBtc) + .append("totalLiabilityOfBtc", totalLiabilityOfBtc) + .append("totalNetAssetOfBtc", totalNetAssetOfBtc) + .append("tradeEnabled", tradeEnabled) + .append("transferEnabled", transferEnabled) + .append("userAssets", userAssets) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java b/src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java new file mode 100755 index 000000000..db949e851 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java @@ -0,0 +1,103 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An asset balance in an Account. + * + * @see Account + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class MarginAssetBalance { + + public static MarginAssetBalance of(final String asset) { + final MarginAssetBalance marginAssetBalance = new MarginAssetBalance(); + + marginAssetBalance.setAsset(asset); + + return marginAssetBalance; + } + + /** + * Asset symbol. + */ + private String asset; + + private String borrowed = "0"; + + /** + * Available balance. + */ + private String free = "0"; + + private String interest = "0"; + + /** + * Locked by open orders. + */ + private String locked = "0"; + + private String netAsset = "0"; + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getBorrowed() { + return borrowed; + } + + public void setBorrowed(String borrowed) { + this.borrowed = borrowed; + } + + public String getFree() { + return free; + } + + public void setFree(String free) { + this.free = free; + } + + public String getInterest() { + return interest; + } + + public void setInterest(String interest) { + this.interest = interest; + } + + public String getLocked() { + return locked; + } + + public void setLocked(String locked) { + this.locked = locked; + } + + public String getNetAsset() { + return netAsset; + } + + public void setNetAsset(String netAsset) { + this.netAsset = netAsset; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("asset", asset) + .append("borrowed", borrowed) + .append("free", free) + .append("interest", interest) + .append("locked", locked) + .append("netAsset", netAsset) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java b/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java new file mode 100755 index 000000000..116439379 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java @@ -0,0 +1,29 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * MarginTransaction information. + */ +@JsonIgnoreProperties +public class MarginTransaction { + + private String tranId; + + public String getTranId() { + return tranId; + } + + public void setTranId(String tranId) { + this.tranId = tranId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("transactionId", tranId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrder.java b/src/main/java/com/binance/api/client/domain/account/NewOrder.java old mode 100644 new mode 100755 index 221c07d36..19d951b63 --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -1,259 +1,259 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A trade order to enter or exit a position. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class NewOrder { - - /** - * Symbol to place the order on. - */ - private String symbol; - - /** - * Buy/Sell order side. - */ - private OrderSide side; - - /** - * Type of order. - */ - private OrderType type; - - /** - * Time in force to indicate how long will the order remain active. - */ - private TimeInForce timeInForce; - - /** - * Quantity. - */ - private String quantity; - - /** - * Price. - */ - private String price; - - /** - * A unique id for the order. Automatically generated if not sent. - */ - private String newClientOrderId; - - /** - * Used with stop orders. - */ - private String stopPrice; - - /** - * Used with iceberg orders. - */ - private String icebergQty; - - /** - * Set the response JSON. ACK, RESULT, or FULL; default: RESULT. - */ - private NewOrderResponseType newOrderRespType; - - /** - * Receiving window. - */ - private Long recvWindow; - - /** - * Order timestamp. - */ - private long timestamp; - - /** - * Creates a new order with all required parameters. - */ - public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity) { - this.symbol = symbol; - this.side = side; - this.type = type; - this.timeInForce = timeInForce; - this.quantity = quantity; - this.newOrderRespType = NewOrderResponseType.RESULT; - this.timestamp = System.currentTimeMillis(); - this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; - } - - /** - * Creates a new order with all required parameters plus price, which is optional for MARKET orders. - */ - public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity, String price) { - this(symbol, side, type, timeInForce, quantity); - this.price = price; - } - - public String getSymbol() { - return symbol; - } - - public NewOrder symbol(String symbol) { - this.symbol = symbol; - return this; - } - - public OrderSide getSide() { - return side; - } - - public NewOrder side(OrderSide side) { - this.side = side; - return this; - } - - public OrderType getType() { - return type; - } - - public NewOrder type(OrderType type) { - this.type = type; - return this; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public NewOrder timeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - return this; - } - - public String getQuantity() { - return quantity; - } - - public NewOrder quantity(String quantity) { - this.quantity = quantity; - return this; - } - - public String getPrice() { - return price; - } - - public NewOrder price(String price) { - this.price = price; - return this; - } - - public String getNewClientOrderId() { - return newClientOrderId; - } - - public NewOrder newClientOrderId(String newClientOrderId) { - this.newClientOrderId = newClientOrderId; - return this; - } - - public String getStopPrice() { - return stopPrice; - } - - public NewOrder stopPrice(String stopPrice) { - this.stopPrice = stopPrice; - return this; - } - - public String getIcebergQty() { - return icebergQty; - } - - public NewOrder icebergQty(String icebergQty) { - this.icebergQty = icebergQty; - return this; - } - - public NewOrderResponseType getNewOrderRespType() { - return newOrderRespType; - } - - public NewOrder newOrderRespType(NewOrderResponseType newOrderRespType) { - this.newOrderRespType = newOrderRespType; - return this; - } - - public Long getRecvWindow() { - return recvWindow; - } - - public NewOrder recvWindow(Long recvWindow) { - this.recvWindow = recvWindow; - return this; - } - - public long getTimestamp() { - return timestamp; - } - - public NewOrder timestamp(long timestamp) { - this.timestamp = timestamp; - return this; - } - - /** - * Places a MARKET buy order for the given quantity. - * - * @return a new order which is pre-configured with MARKET as the order type and BUY as the order side. - */ - public static NewOrder marketBuy(String symbol, String quantity) { - return new NewOrder(symbol, OrderSide.BUY, OrderType.MARKET, null, quantity); - } - - /** - * Places a MARKET sell order for the given quantity. - * - * @return a new order which is pre-configured with MARKET as the order type and SELL as the order side. - */ - public static NewOrder marketSell(String symbol, String quantity) { - return new NewOrder(symbol, OrderSide.SELL, OrderType.MARKET, null, quantity); - } - - /** - * Places a LIMIT buy order for the given quantity and price. - * - * @return a new order which is pre-configured with LIMIT as the order type and BUY as the order side. - */ - public static NewOrder limitBuy(String symbol, TimeInForce timeInForce, String quantity, String price) { - return new NewOrder(symbol, OrderSide.BUY, OrderType.LIMIT, timeInForce, quantity, price); - } - - /** - * Places a LIMIT sell order for the given quantity and price. - * - * @return a new order which is pre-configured with LIMIT as the order type and SELL as the order side. - */ - public static NewOrder limitSell(String symbol, TimeInForce timeInForce, String quantity, String price) { - return new NewOrder(symbol, OrderSide.SELL, OrderType.LIMIT, timeInForce, quantity, price); - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("side", side) - .append("type", type) - .append("timeInForce", timeInForce) - .append("quantity", quantity) - .append("price", price) - .append("newClientOrderId", newClientOrderId) - .append("stopPrice", stopPrice) - .append("icebergQty", icebergQty) - .append("newOrderRespType", newOrderRespType) - .append("recvWindow", recvWindow) - .append("timestamp", timestamp) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A trade order to enter or exit a position. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOrder { + + /** + * Symbol to place the order on. + */ + private String symbol; + + /** + * Buy/Sell order side. + */ + private OrderSide side; + + /** + * Type of order. + */ + private OrderType type; + + /** + * Time in force to indicate how long will the order remain active. + */ + private TimeInForce timeInForce; + + /** + * Quantity. + */ + private String quantity; + + /** + * Price. + */ + private String price; + + /** + * A unique id for the order. Automatically generated if not sent. + */ + private String newClientOrderId; + + /** + * Used with stop orders. + */ + private String stopPrice; + + /** + * Used with iceberg orders. + */ + private String icebergQty; + + /** + * Set the response JSON. ACK, RESULT, or FULL; default: RESULT. + */ + private NewOrderResponseType newOrderRespType; + + /** + * Receiving window. + */ + private Long recvWindow; + + /** + * Order timestamp. + */ + private long timestamp; + + /** + * Creates a new order with all required parameters. + */ + public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity) { + this.symbol = symbol; + this.side = side; + this.type = type; + this.timeInForce = timeInForce; + this.quantity = quantity; + this.newOrderRespType = NewOrderResponseType.RESULT; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + /** + * Creates a new order with all required parameters plus price, which is optional for MARKET orders. + */ + public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity, String price) { + this(symbol, side, type, timeInForce, quantity); + this.price = price; + } + + public String getSymbol() { + return symbol; + } + + public NewOrder symbol(String symbol) { + this.symbol = symbol; + return this; + } + + public OrderSide getSide() { + return side; + } + + public NewOrder side(OrderSide side) { + this.side = side; + return this; + } + + public OrderType getType() { + return type; + } + + public NewOrder type(OrderType type) { + this.type = type; + return this; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public NewOrder timeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + return this; + } + + public String getQuantity() { + return quantity; + } + + public NewOrder quantity(String quantity) { + this.quantity = quantity; + return this; + } + + public String getPrice() { + return price; + } + + public NewOrder price(String price) { + this.price = price; + return this; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public NewOrder newClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + return this; + } + + public String getStopPrice() { + return stopPrice; + } + + public NewOrder stopPrice(String stopPrice) { + this.stopPrice = stopPrice; + return this; + } + + public String getIcebergQty() { + return icebergQty; + } + + public NewOrder icebergQty(String icebergQty) { + this.icebergQty = icebergQty; + return this; + } + + public NewOrderResponseType getNewOrderRespType() { + return newOrderRespType; + } + + public NewOrder newOrderRespType(NewOrderResponseType newOrderRespType) { + this.newOrderRespType = newOrderRespType; + return this; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public NewOrder recvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + return this; + } + + public long getTimestamp() { + return timestamp; + } + + public NewOrder timestamp(long timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Places a MARKET buy order for the given quantity. + * + * @return a new order which is pre-configured with MARKET as the order type and BUY as the order side. + */ + public static NewOrder marketBuy(String symbol, String quantity) { + return new NewOrder(symbol, OrderSide.BUY, OrderType.MARKET, null, quantity); + } + + /** + * Places a MARKET sell order for the given quantity. + * + * @return a new order which is pre-configured with MARKET as the order type and SELL as the order side. + */ + public static NewOrder marketSell(String symbol, String quantity) { + return new NewOrder(symbol, OrderSide.SELL, OrderType.MARKET, null, quantity); + } + + /** + * Places a LIMIT buy order for the given quantity and price. + * + * @return a new order which is pre-configured with LIMIT as the order type and BUY as the order side. + */ + public static NewOrder limitBuy(String symbol, TimeInForce timeInForce, String quantity, String price) { + return new NewOrder(symbol, OrderSide.BUY, OrderType.LIMIT, timeInForce, quantity, price); + } + + /** + * Places a LIMIT sell order for the given quantity and price. + * + * @return a new order which is pre-configured with LIMIT as the order type and SELL as the order side. + */ + public static NewOrder limitSell(String symbol, TimeInForce timeInForce, String quantity, String price) { + return new NewOrder(symbol, OrderSide.SELL, OrderType.LIMIT, timeInForce, quantity, price); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("side", side) + .append("type", type) + .append("timeInForce", timeInForce) + .append("quantity", quantity) + .append("price", price) + .append("newClientOrderId", newClientOrderId) + .append("stopPrice", stopPrice) + .append("icebergQty", icebergQty) + .append("newOrderRespType", newOrderRespType) + .append("recvWindow", recvWindow) + .append("timestamp", timestamp) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java old mode 100644 new mode 100755 index 281e0361e..a1aa9fb12 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java @@ -1,188 +1,188 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * Response returned when placing a new order on the system. - * - * @see NewOrder for the request - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class NewOrderResponse { - - /** - * Order symbol. - */ - private String symbol; - - /** - * Order id. - */ - private Long orderId; - - /** - * This will be either a generated one, or the newClientOrderId parameter - * which was passed when creating the new order. - */ - private String clientOrderId; - - private String price; - - private String origQty; - - private String executedQty; - - private String cummulativeQuoteQty; - - private OrderStatus status; - - private TimeInForce timeInForce; - - private OrderType type; - - private OrderSide side; - - // @JsonSetter(nulls = Nulls.AS_EMPTY) - private List fills; - - /** - * Transact time for this order. - */ - private Long transactTime; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - - public String getClientOrderId() { - return clientOrderId; - } - - public void setClientOrderId(String clientOrderId) { - this.clientOrderId = clientOrderId; - } - - public Long getTransactTime() { - return transactTime; - } - - public void setTransactTime(Long transactTime) { - this.transactTime = transactTime; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getOrigQty() { - return origQty; - } - - public void setOrigQty(String origQty) { - this.origQty = origQty; - } - - public String getExecutedQty() { - return executedQty; - } - - public void setExecutedQty(String executedQty) { - this.executedQty = executedQty; - } - - public String getCummulativeQuoteQty() { - return cummulativeQuoteQty; - } - - public void setCummulativeQuoteQty(String cummulativeQuoteQty) { - this.cummulativeQuoteQty = cummulativeQuoteQty; - } - - public OrderStatus getStatus() { - return status; - } - - public void setStatus(OrderStatus status) { - this.status = status; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public void setTimeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - } - - public OrderType getType() { - return type; - } - - public void setType(OrderType type) { - this.type = type; - } - - public OrderSide getSide() { - return side; - } - - public void setSide(OrderSide side) { - this.side = side; - } - - public List getFills() { - return fills; - } - - public void setFills(List fills) { - this.fills = fills; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("orderId", orderId) - .append("clientOrderId", clientOrderId) - .append("transactTime", transactTime) - .append("price", price) - .append("origQty", origQty) - .append("executedQty", executedQty) - .append("status", status) - .append("timeInForce", timeInForce) - .append("type", type) - .append("side", side) - .append("fills", Optional.ofNullable(fills).orElse(Collections.emptyList()) - .stream() - .map(Object::toString) - .collect(Collectors.joining(", "))) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Response returned when placing a new order on the system. + * + * @see NewOrder for the request + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOrderResponse { + + /** + * Order symbol. + */ + private String symbol; + + /** + * Order id. + */ + private Long orderId; + + /** + * This will be either a generated one, or the newClientOrderId parameter + * which was passed when creating the new order. + */ + private String clientOrderId; + + private String price; + + private String origQty; + + private String executedQty; + + private String cummulativeQuoteQty; + + private OrderStatus status; + + private TimeInForce timeInForce; + + private OrderType type; + + private OrderSide side; + + // @JsonSetter(nulls = Nulls.AS_EMPTY) + private List fills; + + /** + * Transact time for this order. + */ + private Long transactTime; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + public Long getTransactTime() { + return transactTime; + } + + public void setTransactTime(Long transactTime) { + this.transactTime = transactTime; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getOrigQty() { + return origQty; + } + + public void setOrigQty(String origQty) { + this.origQty = origQty; + } + + public String getExecutedQty() { + return executedQty; + } + + public void setExecutedQty(String executedQty) { + this.executedQty = executedQty; + } + + public String getCummulativeQuoteQty() { + return cummulativeQuoteQty; + } + + public void setCummulativeQuoteQty(String cummulativeQuoteQty) { + this.cummulativeQuoteQty = cummulativeQuoteQty; + } + + public OrderStatus getStatus() { + return status; + } + + public void setStatus(OrderStatus status) { + this.status = status; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public List getFills() { + return fills; + } + + public void setFills(List fills) { + this.fills = fills; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .append("transactTime", transactTime) + .append("price", price) + .append("origQty", origQty) + .append("executedQty", executedQty) + .append("status", status) + .append("timeInForce", timeInForce) + .append("type", type) + .append("side", side) + .append("fills", Optional.ofNullable(fills).orElse(Collections.emptyList()) + .stream() + .map(Object::toString) + .collect(Collectors.joining(", "))) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java old mode 100644 new mode 100755 index 836a571d5..fe1d00e55 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java @@ -1,15 +1,15 @@ -package com.binance.api.client.domain.account; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Desired response type of NewOrder requests. - * @see NewOrderResponse - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum NewOrderResponseType { - ACK, - RESULT, - FULL -} - +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Desired response type of NewOrder requests. + * @see NewOrderResponse + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum NewOrderResponseType { + ACK, + RESULT, + FULL +} + diff --git a/src/main/java/com/binance/api/client/domain/account/Order.java b/src/main/java/com/binance/api/client/domain/account/Order.java old mode 100644 new mode 100755 index 88beb54d7..a5eef58a4 --- a/src/main/java/com/binance/api/client/domain/account/Order.java +++ b/src/main/java/com/binance/api/client/domain/account/Order.java @@ -1,218 +1,218 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Trade order information. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - /** - * Symbol that the order was put on. - */ - private String symbol; - - /** - * Order id. - */ - private Long orderId; - - /** - * Client order id. - */ - private String clientOrderId; - - /** - * Price. - */ - private String price; - - /** - * Original quantity. - */ - private String origQty; - - /** - * Original quantity. - */ - private String executedQty; - - /** - * Order status. - */ - private OrderStatus status; - - /** - * Time in force to indicate how long will the order remain active. - */ - private TimeInForce timeInForce; - - /** - * Type of order. - */ - private OrderType type; - - /** - * Buy/Sell order side. - */ - private OrderSide side; - - /** - * Used with stop orders. - */ - private String stopPrice; - - /** - * Used with iceberg orders. - */ - private String icebergQty; - - /** - * Order timestamp. - */ - private long time; - - /** - * Used to calculate the average price - */ - private String cummulativeQuoteQty; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - - public String getClientOrderId() { - return clientOrderId; - } - - public void setClientOrderId(String clientOrderId) { - this.clientOrderId = clientOrderId; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getOrigQty() { - return origQty; - } - - public void setOrigQty(String origQty) { - this.origQty = origQty; - } - - public String getExecutedQty() { - return executedQty; - } - - public void setExecutedQty(String executedQty) { - this.executedQty = executedQty; - } - - public OrderStatus getStatus() { - return status; - } - - public void setStatus(OrderStatus status) { - this.status = status; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public void setTimeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - } - - public OrderType getType() { - return type; - } - - public void setType(OrderType type) { - this.type = type; - } - - public OrderSide getSide() { - return side; - } - - public void setSide(OrderSide side) { - this.side = side; - } - - public String getStopPrice() { - return stopPrice; - } - - public void setStopPrice(String stopPrice) { - this.stopPrice = stopPrice; - } - - public String getIcebergQty() { - return icebergQty; - } - - public void setIcebergQty(String icebergQty) { - this.icebergQty = icebergQty; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public String getCummulativeQuoteQty() { - return cummulativeQuoteQty; - } - - public void setCummulativeQuoteQty(String cummulativeQuoteQty) { - this.cummulativeQuoteQty = cummulativeQuoteQty; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("orderId", orderId) - .append("clientOrderId", clientOrderId) - .append("price", price) - .append("origQty", origQty) - .append("executedQty", executedQty) - .append("status", status) - .append("timeInForce", timeInForce) - .append("type", type) - .append("side", side) - .append("stopPrice", stopPrice) - .append("icebergQty", icebergQty) - .append("time", time) - .append("cummulativeQuoteQty", cummulativeQuoteQty) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Trade order information. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Order { + + /** + * Symbol that the order was put on. + */ + private String symbol; + + /** + * Order id. + */ + private Long orderId; + + /** + * Client order id. + */ + private String clientOrderId; + + /** + * Price. + */ + private String price; + + /** + * Original quantity. + */ + private String origQty; + + /** + * Original quantity. + */ + private String executedQty; + + /** + * Order status. + */ + private OrderStatus status; + + /** + * Time in force to indicate how long will the order remain active. + */ + private TimeInForce timeInForce; + + /** + * Type of order. + */ + private OrderType type; + + /** + * Buy/Sell order side. + */ + private OrderSide side; + + /** + * Used with stop orders. + */ + private String stopPrice; + + /** + * Used with iceberg orders. + */ + private String icebergQty; + + /** + * Order timestamp. + */ + private long time; + + /** + * Used to calculate the average price + */ + private String cummulativeQuoteQty; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getOrigQty() { + return origQty; + } + + public void setOrigQty(String origQty) { + this.origQty = origQty; + } + + public String getExecutedQty() { + return executedQty; + } + + public void setExecutedQty(String executedQty) { + this.executedQty = executedQty; + } + + public OrderStatus getStatus() { + return status; + } + + public void setStatus(OrderStatus status) { + this.status = status; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public String getStopPrice() { + return stopPrice; + } + + public void setStopPrice(String stopPrice) { + this.stopPrice = stopPrice; + } + + public String getIcebergQty() { + return icebergQty; + } + + public void setIcebergQty(String icebergQty) { + this.icebergQty = icebergQty; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public String getCummulativeQuoteQty() { + return cummulativeQuoteQty; + } + + public void setCummulativeQuoteQty(String cummulativeQuoteQty) { + this.cummulativeQuoteQty = cummulativeQuoteQty; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .append("price", price) + .append("origQty", origQty) + .append("executedQty", executedQty) + .append("status", status) + .append("timeInForce", timeInForce) + .append("type", type) + .append("side", side) + .append("stopPrice", stopPrice) + .append("icebergQty", icebergQty) + .append("time", time) + .append("cummulativeQuoteQty", cummulativeQuoteQty) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Trade.java b/src/main/java/com/binance/api/client/domain/account/Trade.java old mode 100644 new mode 100755 index aa38a17b6..903805b28 --- a/src/main/java/com/binance/api/client/domain/account/Trade.java +++ b/src/main/java/com/binance/api/client/domain/account/Trade.java @@ -1,188 +1,188 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents an executed trade. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Trade { - - /** - * Trade id. - */ - private Long id; - - /** - * Price. - */ - private String price; - - /** - * Quantity. - */ - private String qty; - - - /** - * Quote quantity for the trade (price * qty). - */ - private String quoteQty; - - /** - * Commission. - */ - private String commission; - - /** - * Asset on which commission is taken - */ - private String commissionAsset; - - /** - * Trade execution time. - */ - private long time; - - /** - * The symbol of the trade. - */ - private String symbol; - - @JsonProperty("isBuyer") - private boolean buyer; - - @JsonProperty("isMaker") - private boolean maker; - - @JsonProperty("isBestMatch") - private boolean bestMatch; - - private String orderId; - - public Long getId() { - return id; - } - - @JsonSetter("id") - public void setId(Long id) { - this.id = id; - } - - @JsonSetter("tradeId") - public void setTradeId(Long id) { - if (this.id == null) { - setId(id); - } - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQty() { - return qty; - } - - public void setQty(String qty) { - this.qty = qty; - } - - public String getQuoteQty() { - return quoteQty; - } - - public void setQuoteQty(String quoteQty) { - this.quoteQty = quoteQty; - } - - public String getCommission() { - return commission; - } - - public void setCommission(String commission) { - this.commission = commission; - } - - public String getCommissionAsset() { - return commissionAsset; - } - - public void setCommissionAsset(String commissionAsset) { - this.commissionAsset = commissionAsset; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public boolean isBuyer() { - return buyer; - } - - public void setBuyer(boolean buyer) { - this.buyer = buyer; - } - - public boolean isMaker() { - return maker; - } - - public void setMaker(boolean maker) { - this.maker = maker; - } - - public boolean isBestMatch() { - return bestMatch; - } - - public void setBestMatch(boolean bestMatch) { - this.bestMatch = bestMatch; - } - - public String getOrderId() { - return orderId; - } - - public void setOrderId(String orderId) { - this.orderId = orderId; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("id", id) - .append("symbol", symbol) - .append("price", price) - .append("qty", qty) - .append("quoteQty", quoteQty) - .append("commission", commission) - .append("commissionAsset", commissionAsset) - .append("time", time) - .append("buyer", buyer) - .append("maker", maker) - .append("bestMatch", bestMatch) - .append("orderId", orderId) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents an executed trade. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Trade { + + /** + * Trade id. + */ + private Long id; + + /** + * Price. + */ + private String price; + + /** + * Quantity. + */ + private String qty; + + + /** + * Quote quantity for the trade (price * qty). + */ + private String quoteQty; + + /** + * Commission. + */ + private String commission; + + /** + * Asset on which commission is taken + */ + private String commissionAsset; + + /** + * Trade execution time. + */ + private long time; + + /** + * The symbol of the trade. + */ + private String symbol; + + @JsonProperty("isBuyer") + private boolean buyer; + + @JsonProperty("isMaker") + private boolean maker; + + @JsonProperty("isBestMatch") + private boolean bestMatch; + + private String orderId; + + public Long getId() { + return id; + } + + @JsonSetter("id") + public void setId(Long id) { + this.id = id; + } + + @JsonSetter("tradeId") + public void setTradeId(Long id) { + if (this.id == null) { + setId(id); + } + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQty() { + return qty; + } + + public void setQty(String qty) { + this.qty = qty; + } + + public String getQuoteQty() { + return quoteQty; + } + + public void setQuoteQty(String quoteQty) { + this.quoteQty = quoteQty; + } + + public String getCommission() { + return commission; + } + + public void setCommission(String commission) { + this.commission = commission; + } + + public String getCommissionAsset() { + return commissionAsset; + } + + public void setCommissionAsset(String commissionAsset) { + this.commissionAsset = commissionAsset; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public boolean isBuyer() { + return buyer; + } + + public void setBuyer(boolean buyer) { + this.buyer = buyer; + } + + public boolean isMaker() { + return maker; + } + + public void setMaker(boolean maker) { + this.maker = maker; + } + + public boolean isBestMatch() { + return bestMatch; + } + + public void setBestMatch(boolean bestMatch) { + this.bestMatch = bestMatch; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("id", id) + .append("symbol", symbol) + .append("price", price) + .append("qty", qty) + .append("quoteQty", quoteQty) + .append("commission", commission) + .append("commissionAsset", commissionAsset) + .append("time", time) + .append("buyer", buyer) + .append("maker", maker) + .append("bestMatch", bestMatch) + .append("orderId", orderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java b/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java old mode 100644 new mode 100755 index 68d017754..babc10760 --- a/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java +++ b/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java @@ -1,104 +1,104 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents an executed trade history item. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class TradeHistoryItem { - /** - * Trade id. - */ - private long id; - - /** - * Price. - */ - private String price; - - /** - * Quantity. - */ - private String qty; - - /** - * Trade execution time. - */ - private long time; - - /** - * Is buyer maker ? - */ - @JsonProperty("isBuyerMaker") - private boolean isBuyerMaker; - - /** - * Is best match ? - */ - @JsonProperty("isBestMatch") - private boolean isBestMatch; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQty() { - return qty; - } - - public void setQty(String qty) { - this.qty = qty; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public boolean isBuyerMaker() { - return isBuyerMaker; - } - - public void setBuyerMaker(boolean buyerMaker) { - isBuyerMaker = buyerMaker; - } - - public boolean isBestMatch() { - return isBestMatch; - } - - public void setBestMatch(boolean bestMatch) { - isBestMatch = bestMatch; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("id", id) - .append("price", price) - .append("qty", qty) - .append("time", time) - .append("isBuyerMaker", isBuyerMaker) - .append("isBestMatch", isBestMatch) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents an executed trade history item. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TradeHistoryItem { + /** + * Trade id. + */ + private long id; + + /** + * Price. + */ + private String price; + + /** + * Quantity. + */ + private String qty; + + /** + * Trade execution time. + */ + private long time; + + /** + * Is buyer maker ? + */ + @JsonProperty("isBuyerMaker") + private boolean isBuyerMaker; + + /** + * Is best match ? + */ + @JsonProperty("isBestMatch") + private boolean isBestMatch; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQty() { + return qty; + } + + public void setQty(String qty) { + this.qty = qty; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public boolean isBuyerMaker() { + return isBuyerMaker; + } + + public void setBuyerMaker(boolean buyerMaker) { + isBuyerMaker = buyerMaker; + } + + public boolean isBestMatch() { + return isBestMatch; + } + + public void setBestMatch(boolean bestMatch) { + isBestMatch = bestMatch; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("id", id) + .append("price", price) + .append("qty", qty) + .append("time", time) + .append("isBuyerMaker", isBuyerMaker) + .append("isBestMatch", isBestMatch) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Withdraw.java b/src/main/java/com/binance/api/client/domain/account/Withdraw.java old mode 100644 new mode 100755 index 9d6858fdd..69635ee99 --- a/src/main/java/com/binance/api/client/domain/account/Withdraw.java +++ b/src/main/java/com/binance/api/client/domain/account/Withdraw.java @@ -1,124 +1,124 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A withdraw that was done to a Binance account. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Withdraw { - - /** - * Amount withdrawn. - */ - private String amount; - - /** - * Destination address. - */ - private String address; - - /** - * Symbol. - */ - private String asset; - - private String applyTime; - - private String successTime; - - /** - * Transaction id. - */ - private String txId; - - /** - * Id. - */ - private String id; - - /** - * (0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6:Completed) - */ - private int status; - - public String getAmount() { - return amount; - } - - public void setAmount(String amount) { - this.amount = amount; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - public String getApplyTime() { - return applyTime; - } - - public void setApplyTime(String applyTime) { - this.applyTime = applyTime; - } - - public String getSuccessTime() { - return successTime; - } - - public void setSuccessTime(String successTime) { - this.successTime = successTime; - } - - public String getTxId() { - return txId; - } - - public void setTxId(String txId) { - this.txId = txId; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("amount", amount) - .append("address", address) - .append("asset", asset) - .append("applyTime", applyTime) - .append("successTime", successTime) - .append("txId", txId) - .append("id", id) - .append("status", status) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A withdraw that was done to a Binance account. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Withdraw { + + /** + * Amount withdrawn. + */ + private String amount; + + /** + * Destination address. + */ + private String address; + + /** + * Symbol. + */ + private String asset; + + private String applyTime; + + private String successTime; + + /** + * Transaction id. + */ + private String txId; + + /** + * Id. + */ + private String id; + + /** + * (0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6:Completed) + */ + private int status; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getApplyTime() { + return applyTime; + } + + public void setApplyTime(String applyTime) { + this.applyTime = applyTime; + } + + public String getSuccessTime() { + return successTime; + } + + public void setSuccessTime(String successTime) { + this.successTime = successTime; + } + + public String getTxId() { + return txId; + } + + public void setTxId(String txId) { + this.txId = txId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("amount", amount) + .append("address", address) + .append("asset", asset) + .append("applyTime", applyTime) + .append("successTime", successTime) + .append("txId", txId) + .append("id", id) + .append("status", status) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java b/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java old mode 100644 new mode 100755 index 3a3d50f12..df57f89a5 --- a/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java +++ b/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * History of account withdrawals. - * - * @see Withdraw - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class WithdrawHistory { - - private List withdrawList; - - private boolean success; - - public List getWithdrawList() { - return withdrawList; - } - - public void setWithdrawList(List withdrawList) { - this.withdrawList = withdrawList; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("withdrawList", withdrawList) - .append("success", success) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * History of account withdrawals. + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class WithdrawHistory { + + private List withdrawList; + + private boolean success; + + public List getWithdrawList() { + return withdrawList; + } + + public void setWithdrawList(List withdrawList) { + this.withdrawList = withdrawList; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("withdrawList", withdrawList) + .append("success", success) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java b/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java old mode 100644 new mode 100755 index fac00deba..b9ebded80 --- a/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java +++ b/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * A withdraw result that was done to a Binance account. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class WithdrawResult { - - /** - * Withdraw message. - */ - private String msg; - - /** - * Withdraw success. - */ - private boolean success; - - /** - * Withdraw id. - */ - private String id; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String toString() { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("msg", msg) - .append("success", success) - .append("id", id) - .toString(); - } - - -} +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * A withdraw result that was done to a Binance account. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class WithdrawResult { + + /** + * Withdraw message. + */ + private String msg; + + /** + * Withdraw success. + */ + private boolean success; + + /** + * Withdraw id. + */ + private String id; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + .append("msg", msg) + .append("success", success) + .append("id", id) + .toString(); + } + + +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java b/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java old mode 100644 new mode 100755 index 9a7c455d6..d58fca1da --- a/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java @@ -1,47 +1,47 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A specialized order request with additional filters. - */ -public class AllOrdersRequest extends OrderRequest { - - private static final Integer DEFAULT_LIMIT = 500; - - private Long orderId; - - private Integer limit; - - public AllOrdersRequest(String symbol) { - super(symbol); - this.limit = DEFAULT_LIMIT; - } - - public Long getOrderId() { - return orderId; - } - - public AllOrdersRequest orderId(Long orderId) { - this.orderId = orderId; - return this; - } - - public Integer getLimit() { - return limit; - } - - public AllOrdersRequest limit(Integer limit) { - this.limit = limit; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("orderId", orderId) - .append("limit", limit) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A specialized order request with additional filters. + */ +public class AllOrdersRequest extends OrderRequest { + + private static final Integer DEFAULT_LIMIT = 500; + + private Long orderId; + + private Integer limit; + + public AllOrdersRequest(String symbol) { + super(symbol); + this.limit = DEFAULT_LIMIT; + } + + public Long getOrderId() { + return orderId; + } + + public AllOrdersRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + + public Integer getLimit() { + return limit; + } + + public AllOrdersRequest limit(Integer limit) { + this.limit = limit; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderId", orderId) + .append("limit", limit) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java old mode 100644 new mode 100755 index 010e23ef8..2dc89c725 --- a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java @@ -1,65 +1,65 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Request object for canceling an order. - */ -public class CancelOrderRequest extends OrderRequest { - - private Long orderId; - - private String origClientOrderId; - - public CancelOrderRequest(String symbol, Long orderId) { - super(symbol); - this.orderId = orderId; - } - - public CancelOrderRequest(String symbol, String origClientOrderId) { - super(symbol); - this.origClientOrderId = origClientOrderId; - } - - /** - * Used to uniquely identify this cancel. Automatically generated by default. - */ - private String newClientOrderId; - - public Long getOrderId() { - return orderId; - } - - public CancelOrderRequest orderId(Long orderId) { - this.orderId = orderId; - return this; - } - - public String getOrigClientOrderId() { - return origClientOrderId; - } - - public CancelOrderRequest origClientOrderId(String origClientOrderId) { - this.origClientOrderId = origClientOrderId; - return this; - } - - public String getNewClientOrderId() { - return newClientOrderId; - } - - public CancelOrderRequest newClientOrderId(String newClientOrderId) { - this.newClientOrderId = newClientOrderId; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("orderId", orderId) - .append("origClientOrderId", origClientOrderId) - .append("newClientOrderId", newClientOrderId) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Request object for canceling an order. + */ +public class CancelOrderRequest extends OrderRequest { + + private Long orderId; + + private String origClientOrderId; + + public CancelOrderRequest(String symbol, Long orderId) { + super(symbol); + this.orderId = orderId; + } + + public CancelOrderRequest(String symbol, String origClientOrderId) { + super(symbol); + this.origClientOrderId = origClientOrderId; + } + + /** + * Used to uniquely identify this cancel. Automatically generated by default. + */ + private String newClientOrderId; + + public Long getOrderId() { + return orderId; + } + + public CancelOrderRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public CancelOrderRequest origClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public CancelOrderRequest newClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderId", orderId) + .append("origClientOrderId", origClientOrderId) + .append("newClientOrderId", newClientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java old mode 100644 new mode 100755 index 7b96a01eb..0399aea2b --- a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java @@ -1,77 +1,77 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Response object returned when an order is canceled. - * - * @see CancelOrderRequest for the request - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class CancelOrderResponse { - - private String symbol; - - private String origClientOrderId; - - private String orderId; - - private String clientOrderId; - - private String status; - private String executedQty; - - public String getSymbol() { - return symbol; - } - - public CancelOrderResponse setSymbol(String symbol) { - this.symbol = symbol; - return this; - } - - public String getOrigClientOrderId() { - return origClientOrderId; - } - - public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { - this.origClientOrderId = origClientOrderId; - return this; - } - - public String getStatus() { - return status; - } - public String getExecutedQty() { - return executedQty; - } - - public String getOrderId() { - return orderId; - } - public CancelOrderResponse setOrderId(String orderId) { - this.orderId = orderId; - return this; - } - - public String getClientOrderId() { - return clientOrderId; - } - - public CancelOrderResponse setClientOrderId(String clientOrderId) { - this.clientOrderId = clientOrderId; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("origClientOrderId", origClientOrderId) - .append("orderId", orderId) - .append("clientOrderId", clientOrderId) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Response object returned when an order is canceled. + * + * @see CancelOrderRequest for the request + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class CancelOrderResponse { + + private String symbol; + + private String origClientOrderId; + + private String orderId; + + private String clientOrderId; + + private String status; + private String executedQty; + + public String getSymbol() { + return symbol; + } + + public CancelOrderResponse setSymbol(String symbol) { + this.symbol = symbol; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + public String getStatus() { + return status; + } + public String getExecutedQty() { + return executedQty; + } + + public String getOrderId() { + return orderId; + } + public CancelOrderResponse setOrderId(String orderId) { + this.orderId = orderId; + return this; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public CancelOrderResponse setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("origClientOrderId", origClientOrderId) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java b/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java old mode 100644 new mode 100755 index c890a01d9..cad6033e3 --- a/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java @@ -1,55 +1,55 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Base request parameters for order-related methods. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderRequest { - - private final String symbol; - - private Long recvWindow; - - private Long timestamp; - - public OrderRequest(String symbol) { - this.symbol = symbol; - this.timestamp = System.currentTimeMillis(); - this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; - } - - public String getSymbol() { - return symbol; - } - - public Long getRecvWindow() { - return recvWindow; - } - - public OrderRequest recvWindow(Long recvWindow) { - this.recvWindow = recvWindow; - return this; - } - - public Long getTimestamp() { - return timestamp; - } - - public OrderRequest timestamp(Long timestamp) { - this.timestamp = timestamp; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("recvWindow", recvWindow) - .append("timestamp", timestamp) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Base request parameters for order-related methods. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderRequest { + + private final String symbol; + + private Long recvWindow; + + private Long timestamp; + + public OrderRequest(String symbol) { + this.symbol = symbol; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + public String getSymbol() { + return symbol; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public OrderRequest recvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + return this; + } + + public Long getTimestamp() { + return timestamp; + } + + public OrderRequest timestamp(Long timestamp) { + this.timestamp = timestamp; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("recvWindow", recvWindow) + .append("timestamp", timestamp) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java b/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java old mode 100644 new mode 100755 index 497eed1b2..bde5326d2 --- a/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java @@ -1,50 +1,50 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A specialized order request with additional filters. - */ -public class OrderStatusRequest extends OrderRequest { - - private Long orderId; - - private String origClientOrderId; - - public OrderStatusRequest(String symbol, Long orderId) { - super(symbol); - this.orderId = orderId; - } - - public OrderStatusRequest(String symbol, String origClientOrderId) { - super(symbol); - this.origClientOrderId = origClientOrderId; - } - - public Long getOrderId() { - return orderId; - } - - public OrderStatusRequest orderId(Long orderId) { - this.orderId = orderId; - return this; - } - - public String getOrigClientOrderId() { - return origClientOrderId; - } - - public OrderStatusRequest origClientOrderId(String origClientOrderId) { - this.origClientOrderId = origClientOrderId; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("orderId", orderId) - .append("origClientOrderId", origClientOrderId) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A specialized order request with additional filters. + */ +public class OrderStatusRequest extends OrderRequest { + + private Long orderId; + + private String origClientOrderId; + + public OrderStatusRequest(String symbol, Long orderId) { + super(symbol); + this.orderId = orderId; + } + + public OrderStatusRequest(String symbol, String origClientOrderId) { + super(symbol); + this.origClientOrderId = origClientOrderId; + } + + public Long getOrderId() { + return orderId; + } + + public OrderStatusRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public OrderStatusRequest origClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderId", orderId) + .append("origClientOrderId", origClientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java old mode 100644 new mode 100755 index 4deefdbad..e5a28c6e8 --- a/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java @@ -1,64 +1,64 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.AssetBalance; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Account update event which will reflect the current position/balances of the account. - * - * This event is embedded as part of a user data update event. - * - * @see UserDataUpdateEvent - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AccountUpdateEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("B") - @JsonDeserialize(contentUsing = AssetBalanceDeserializer.class) - private List balances; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public List getBalances() { - return balances; - } - - public void setBalances(List balances) { - this.balances = balances; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("balances", balances) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.account.AssetBalance; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Account update event which will reflect the current position/balances of the account. + * + * This event is embedded as part of a user data update event. + * + * @see UserDataUpdateEvent + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AccountUpdateEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("B") + @JsonDeserialize(contentUsing = AssetBalanceDeserializer.class) + private List balances; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public List getBalances() { + return balances; + } + + public void setBalances(List balances) { + this.balances = balances; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("balances", balances) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java b/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java old mode 100644 new mode 100755 index 5f608a415..87089cb75 --- a/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java @@ -1,57 +1,57 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.market.AggTrade; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An aggregated trade event for a symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AggTradeEvent extends AggTrade { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("s") - private String symbol; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("aggTrade", super.toString()) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.market.AggTrade; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An aggregated trade event for a symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AggTradeEvent extends AggTrade { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("s") + private String symbol; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("aggTrade", super.toString()) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java b/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java old mode 100644 new mode 100755 index 85a14db29..459157a8b --- a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java @@ -1,294 +1,294 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AllMarketTickersEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("s") - private String symbol; - - @JsonProperty("p") - private String priceChange; - - @JsonProperty("P") - private String priceChangePercent; - - @JsonProperty("w") - private String weightedAveragePrice; - - @JsonProperty("x") - private String previousDaysClosePrice; - - @JsonProperty("c") - private String currentDaysClosePrice; - - @JsonProperty("Q") - private String closeTradesQuantity; - - @JsonProperty("b") - private String bestBidPrice; - - @JsonProperty("B") - private String bestBidQuantity; - - @JsonProperty("a") - private String bestAskPrice; - - @JsonProperty("A") - private String bestAskQuantity; - - @JsonProperty("o") - private String openPrice; - - @JsonProperty("h") - private String highPrice; - - @JsonProperty("l") - private String lowPrice; - - @JsonProperty("v") - private String totalTradedBaseAssetVolume; - - @JsonProperty("q") - private String totalTradedQuoteAssetVolume; - - @JsonProperty("O") - private long statisticesOpenTime; - - @JsonProperty("C") - private long statisticesCloseTime; - - @JsonProperty("F") - private long firstTradeId; - - @JsonProperty("L") - private long lastTradeId; - - @JsonProperty("n") - private long totalNumberOfTrades; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getPriceChange() { - return priceChange; - } - - public void setPriceChange(String priceChange) { - this.priceChange = priceChange; - } - - public String getPriceChangePercent() { - return priceChangePercent; - } - - public void setPriceChangePercent(String priceChangePercent) { - this.priceChangePercent = priceChangePercent; - } - - public String getWeightedAveragePrice() { - return weightedAveragePrice; - } - - public void setWeightedAveragePrice(String weightedAveragePrice) { - this.weightedAveragePrice = weightedAveragePrice; - } - - public String getPreviousDaysClosePrice() { - return previousDaysClosePrice; - } - - public void setPreviousDaysClosePrice(String previousDaysClosePrice) { - this.previousDaysClosePrice = previousDaysClosePrice; - } - - public String getCurrentDaysClosePrice() { - return currentDaysClosePrice; - } - - public void setCurrentDaysClosePrice(String currentDaysClosePrice) { - this.currentDaysClosePrice = currentDaysClosePrice; - } - - public String getCloseTradesQuantity() { - return closeTradesQuantity; - } - - public void setCloseTradesQuantity(String closeTradesQuantity) { - this.closeTradesQuantity = closeTradesQuantity; - } - - public String getBestBidPrice() { - return bestBidPrice; - } - - public void setBestBidPrice(String bestBidPrice) { - this.bestBidPrice = bestBidPrice; - } - - public String getBestBidQuantity() { - return bestBidQuantity; - } - - public void setBestBidQuantity(String bestBidQuantity) { - this.bestBidQuantity = bestBidQuantity; - } - - public String getBestAskPrice() { - return bestAskPrice; - } - - public void setBestAskPrice(String bestAskPrice) { - this.bestAskPrice = bestAskPrice; - } - - public String getBestAskQuantity() { - return bestAskQuantity; - } - - public void setBestAskQuantity(String bestAskQuantity) { - this.bestAskQuantity = bestAskQuantity; - } - - public String getOpenPrice() { - return openPrice; - } - - public void setOpenPrice(String openPrice) { - this.openPrice = openPrice; - } - - public String getHighPrice() { - return highPrice; - } - - public void setHighPrice(String highPrice) { - this.highPrice = highPrice; - } - - public String getLowPrice() { - return lowPrice; - } - - public void setLowPrice(String lowPrice) { - this.lowPrice = lowPrice; - } - - public String getTotalTradedBaseAssetVolume() { - return totalTradedBaseAssetVolume; - } - - public void setTotalTradedBaseAssetVolume(String totalTradedBaseAssetVolume) { - this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; - } - - public String getTotalTradedQuoteAssetVolume() { - return totalTradedQuoteAssetVolume; - } - - public void setTotalTradedQuoteAssetVolume(String totalTradedQuoteAssetVolume) { - this.totalTradedQuoteAssetVolume = totalTradedQuoteAssetVolume; - } - - public long getStatisticesOpenTime() { - return statisticesOpenTime; - } - - public void setStatisticesOpenTime(long statisticesOpenTime) { - this.statisticesOpenTime = statisticesOpenTime; - } - - public long getStatisticesCloseTime() { - return statisticesCloseTime; - } - - public void setStatisticesCloseTime(long statisticesCloseTime) { - this.statisticesCloseTime = statisticesCloseTime; - } - - public long getFirstTradeId() { - return firstTradeId; - } - - public void setFirstTradeId(long firstTradeId) { - this.firstTradeId = firstTradeId; - } - - public long getLastTradeId() { - return lastTradeId; - } - - public void setLastTradeId(long lastTradeId) { - this.lastTradeId = lastTradeId; - } - - public long getTotalNumberOfTrades() { - return totalNumberOfTrades; - } - - public void setTotalNumberOfTrades(long totalNumberOfTrades) { - this.totalNumberOfTrades = totalNumberOfTrades; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("priceChange", priceChange) - .append("priceChangePercent", priceChangePercent) - .append("weightedAveragePrice", weightedAveragePrice) - .append("previousDaysClosePrice", previousDaysClosePrice) - .append("currentDaysClosePrice", currentDaysClosePrice) - .append("closeTradesQuantity", closeTradesQuantity) - .append("bestBidPrice", bestBidPrice) - .append("bestBidQuantity", bestBidQuantity) - .append("bestAskPrice", bestAskPrice) - .append("bestAskQuantity", bestAskQuantity) - .append("openPrice", openPrice) - .append("highPrice", highPrice) - .append("lowPrice", lowPrice) - .append("totalTradedBaseAssetVolume", totalTradedBaseAssetVolume) - .append("totalTradedQuoteAssetVolume", totalTradedQuoteAssetVolume) - .append("statisticesOpenTime", statisticesOpenTime) - .append("statisticesCloseTime", statisticesCloseTime) - .append("firstTradeId", firstTradeId) - .append("lastTradeId", lastTradeId) - .append("totalNumberOfTrades", totalNumberOfTrades) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AllMarketTickersEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("p") + private String priceChange; + + @JsonProperty("P") + private String priceChangePercent; + + @JsonProperty("w") + private String weightedAveragePrice; + + @JsonProperty("x") + private String previousDaysClosePrice; + + @JsonProperty("c") + private String currentDaysClosePrice; + + @JsonProperty("Q") + private String closeTradesQuantity; + + @JsonProperty("b") + private String bestBidPrice; + + @JsonProperty("B") + private String bestBidQuantity; + + @JsonProperty("a") + private String bestAskPrice; + + @JsonProperty("A") + private String bestAskQuantity; + + @JsonProperty("o") + private String openPrice; + + @JsonProperty("h") + private String highPrice; + + @JsonProperty("l") + private String lowPrice; + + @JsonProperty("v") + private String totalTradedBaseAssetVolume; + + @JsonProperty("q") + private String totalTradedQuoteAssetVolume; + + @JsonProperty("O") + private long statisticesOpenTime; + + @JsonProperty("C") + private long statisticesCloseTime; + + @JsonProperty("F") + private long firstTradeId; + + @JsonProperty("L") + private long lastTradeId; + + @JsonProperty("n") + private long totalNumberOfTrades; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getPriceChange() { + return priceChange; + } + + public void setPriceChange(String priceChange) { + this.priceChange = priceChange; + } + + public String getPriceChangePercent() { + return priceChangePercent; + } + + public void setPriceChangePercent(String priceChangePercent) { + this.priceChangePercent = priceChangePercent; + } + + public String getWeightedAveragePrice() { + return weightedAveragePrice; + } + + public void setWeightedAveragePrice(String weightedAveragePrice) { + this.weightedAveragePrice = weightedAveragePrice; + } + + public String getPreviousDaysClosePrice() { + return previousDaysClosePrice; + } + + public void setPreviousDaysClosePrice(String previousDaysClosePrice) { + this.previousDaysClosePrice = previousDaysClosePrice; + } + + public String getCurrentDaysClosePrice() { + return currentDaysClosePrice; + } + + public void setCurrentDaysClosePrice(String currentDaysClosePrice) { + this.currentDaysClosePrice = currentDaysClosePrice; + } + + public String getCloseTradesQuantity() { + return closeTradesQuantity; + } + + public void setCloseTradesQuantity(String closeTradesQuantity) { + this.closeTradesQuantity = closeTradesQuantity; + } + + public String getBestBidPrice() { + return bestBidPrice; + } + + public void setBestBidPrice(String bestBidPrice) { + this.bestBidPrice = bestBidPrice; + } + + public String getBestBidQuantity() { + return bestBidQuantity; + } + + public void setBestBidQuantity(String bestBidQuantity) { + this.bestBidQuantity = bestBidQuantity; + } + + public String getBestAskPrice() { + return bestAskPrice; + } + + public void setBestAskPrice(String bestAskPrice) { + this.bestAskPrice = bestAskPrice; + } + + public String getBestAskQuantity() { + return bestAskQuantity; + } + + public void setBestAskQuantity(String bestAskQuantity) { + this.bestAskQuantity = bestAskQuantity; + } + + public String getOpenPrice() { + return openPrice; + } + + public void setOpenPrice(String openPrice) { + this.openPrice = openPrice; + } + + public String getHighPrice() { + return highPrice; + } + + public void setHighPrice(String highPrice) { + this.highPrice = highPrice; + } + + public String getLowPrice() { + return lowPrice; + } + + public void setLowPrice(String lowPrice) { + this.lowPrice = lowPrice; + } + + public String getTotalTradedBaseAssetVolume() { + return totalTradedBaseAssetVolume; + } + + public void setTotalTradedBaseAssetVolume(String totalTradedBaseAssetVolume) { + this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; + } + + public String getTotalTradedQuoteAssetVolume() { + return totalTradedQuoteAssetVolume; + } + + public void setTotalTradedQuoteAssetVolume(String totalTradedQuoteAssetVolume) { + this.totalTradedQuoteAssetVolume = totalTradedQuoteAssetVolume; + } + + public long getStatisticesOpenTime() { + return statisticesOpenTime; + } + + public void setStatisticesOpenTime(long statisticesOpenTime) { + this.statisticesOpenTime = statisticesOpenTime; + } + + public long getStatisticesCloseTime() { + return statisticesCloseTime; + } + + public void setStatisticesCloseTime(long statisticesCloseTime) { + this.statisticesCloseTime = statisticesCloseTime; + } + + public long getFirstTradeId() { + return firstTradeId; + } + + public void setFirstTradeId(long firstTradeId) { + this.firstTradeId = firstTradeId; + } + + public long getLastTradeId() { + return lastTradeId; + } + + public void setLastTradeId(long lastTradeId) { + this.lastTradeId = lastTradeId; + } + + public long getTotalNumberOfTrades() { + return totalNumberOfTrades; + } + + public void setTotalNumberOfTrades(long totalNumberOfTrades) { + this.totalNumberOfTrades = totalNumberOfTrades; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("priceChange", priceChange) + .append("priceChangePercent", priceChangePercent) + .append("weightedAveragePrice", weightedAveragePrice) + .append("previousDaysClosePrice", previousDaysClosePrice) + .append("currentDaysClosePrice", currentDaysClosePrice) + .append("closeTradesQuantity", closeTradesQuantity) + .append("bestBidPrice", bestBidPrice) + .append("bestBidQuantity", bestBidQuantity) + .append("bestAskPrice", bestAskPrice) + .append("bestAskQuantity", bestAskQuantity) + .append("openPrice", openPrice) + .append("highPrice", highPrice) + .append("lowPrice", lowPrice) + .append("totalTradedBaseAssetVolume", totalTradedBaseAssetVolume) + .append("totalTradedQuoteAssetVolume", totalTradedQuoteAssetVolume) + .append("statisticesOpenTime", statisticesOpenTime) + .append("statisticesCloseTime", statisticesCloseTime) + .append("firstTradeId", firstTradeId) + .append("lastTradeId", lastTradeId) + .append("totalNumberOfTrades", totalNumberOfTrades) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java b/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java old mode 100644 new mode 100755 index d54703f71..f8953a4c6 --- a/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java @@ -1,32 +1,32 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.domain.account.AssetBalance; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; - -/** - * Custom deserializer for an AssetBalance, since the streaming API returns an object in the format {"a":"symbol","f":"free","l":"locked"}, - * which is different than the format used in the REST API. - */ -public class AssetBalanceDeserializer extends JsonDeserializer { - - @Override - public AssetBalance deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - final String asset = node.get("a").asText(); - final String free = node.get("f").asText(); - final String locked = node.get("l").asText(); - - AssetBalance assetBalance = new AssetBalance(); - assetBalance.setAsset(asset); - assetBalance.setFree(free); - assetBalance.setLocked(locked); - return assetBalance; - } +package com.binance.api.client.domain.event; + +import com.binance.api.client.domain.account.AssetBalance; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; + +/** + * Custom deserializer for an AssetBalance, since the streaming API returns an object in the format {"a":"symbol","f":"free","l":"locked"}, + * which is different than the format used in the REST API. + */ +public class AssetBalanceDeserializer extends JsonDeserializer { + + @Override + public AssetBalance deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + final String asset = node.get("a").asText(); + final String free = node.get("f").asText(); + final String locked = node.get("l").asText(); + + AssetBalance assetBalance = new AssetBalance(); + assetBalance.setAsset(asset); + assetBalance.setFree(free); + assetBalance.setLocked(locked); + return assetBalance; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java b/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java old mode 100644 new mode 100755 index 1019eb6f3..f7c04b3df --- a/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java @@ -1,221 +1,221 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An interval candlestick for a symbol providing informations on price that can be used to produce candlestick charts. - */ -@JsonDeserialize(using = CandlestickEventDeserializer.class) -@JsonSerialize(using = CandlestickEventSerializer.class) -@JsonIgnoreProperties(ignoreUnknown = true) -public class CandlestickEvent { - - private String eventType; - - private long eventTime; - - private String symbol; - - private Long openTime; - - private String open; - - private String high; - - private String low; - - private String close; - - private String volume; - - private Long closeTime; - - private String intervalId; - - private Long firstTradeId; - - private Long lastTradeId; - - private String quoteAssetVolume; - - private Long numberOfTrades; - - private String takerBuyBaseAssetVolume; - - private String takerBuyQuoteAssetVolume; - - private Boolean isBarFinal; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public Long getOpenTime() { - return openTime; - } - - public void setOpenTime(Long openTime) { - this.openTime = openTime; - } - - public String getOpen() { - return open; - } - - public void setOpen(String open) { - this.open = open; - } - - public String getHigh() { - return high; - } - - public void setHigh(String high) { - this.high = high; - } - - public String getLow() { - return low; - } - - public void setLow(String low) { - this.low = low; - } - - public String getClose() { - return close; - } - - public void setClose(String close) { - this.close = close; - } - - public String getVolume() { - return volume; - } - - public void setVolume(String volume) { - this.volume = volume; - } - - public Long getCloseTime() { - return closeTime; - } - - public void setCloseTime(Long closeTime) { - this.closeTime = closeTime; - } - - public String getIntervalId() { - return intervalId; - } - - public void setIntervalId(String intervalId) { - this.intervalId = intervalId; - } - - public Long getFirstTradeId() { - return firstTradeId; - } - - public void setFirstTradeId(Long firstTradeId) { - this.firstTradeId = firstTradeId; - } - - public Long getLastTradeId() { - return lastTradeId; - } - - public void setLastTradeId(Long lastTradeId) { - this.lastTradeId = lastTradeId; - } - - public String getQuoteAssetVolume() { - return quoteAssetVolume; - } - - public void setQuoteAssetVolume(String quoteAssetVolume) { - this.quoteAssetVolume = quoteAssetVolume; - } - - public Long getNumberOfTrades() { - return numberOfTrades; - } - - public void setNumberOfTrades(Long numberOfTrades) { - this.numberOfTrades = numberOfTrades; - } - - public String getTakerBuyBaseAssetVolume() { - return takerBuyBaseAssetVolume; - } - - public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { - this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; - } - - public String getTakerBuyQuoteAssetVolume() { - return takerBuyQuoteAssetVolume; - } - - public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { - this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; - } - - public Boolean getBarFinal() { - return isBarFinal; - } - - public void setBarFinal(Boolean barFinal) { - isBarFinal = barFinal; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("openTime", openTime) - .append("open", open) - .append("high", high) - .append("low", low) - .append("close", close) - .append("volume", volume) - .append("closeTime", closeTime) - .append("intervalId", intervalId) - .append("firstTradeId", firstTradeId) - .append("lastTradeId", lastTradeId) - .append("quoteAssetVolume", quoteAssetVolume) - .append("numberOfTrades", numberOfTrades) - .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) - .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) - .append("isBarFinal", isBarFinal) - .toString(); - } +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An interval candlestick for a symbol providing informations on price that can be used to produce candlestick charts. + */ +@JsonDeserialize(using = CandlestickEventDeserializer.class) +@JsonSerialize(using = CandlestickEventSerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public class CandlestickEvent { + + private String eventType; + + private long eventTime; + + private String symbol; + + private Long openTime; + + private String open; + + private String high; + + private String low; + + private String close; + + private String volume; + + private Long closeTime; + + private String intervalId; + + private Long firstTradeId; + + private Long lastTradeId; + + private String quoteAssetVolume; + + private Long numberOfTrades; + + private String takerBuyBaseAssetVolume; + + private String takerBuyQuoteAssetVolume; + + private Boolean isBarFinal; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOpenTime() { + return openTime; + } + + public void setOpenTime(Long openTime) { + this.openTime = openTime; + } + + public String getOpen() { + return open; + } + + public void setOpen(String open) { + this.open = open; + } + + public String getHigh() { + return high; + } + + public void setHigh(String high) { + this.high = high; + } + + public String getLow() { + return low; + } + + public void setLow(String low) { + this.low = low; + } + + public String getClose() { + return close; + } + + public void setClose(String close) { + this.close = close; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public Long getCloseTime() { + return closeTime; + } + + public void setCloseTime(Long closeTime) { + this.closeTime = closeTime; + } + + public String getIntervalId() { + return intervalId; + } + + public void setIntervalId(String intervalId) { + this.intervalId = intervalId; + } + + public Long getFirstTradeId() { + return firstTradeId; + } + + public void setFirstTradeId(Long firstTradeId) { + this.firstTradeId = firstTradeId; + } + + public Long getLastTradeId() { + return lastTradeId; + } + + public void setLastTradeId(Long lastTradeId) { + this.lastTradeId = lastTradeId; + } + + public String getQuoteAssetVolume() { + return quoteAssetVolume; + } + + public void setQuoteAssetVolume(String quoteAssetVolume) { + this.quoteAssetVolume = quoteAssetVolume; + } + + public Long getNumberOfTrades() { + return numberOfTrades; + } + + public void setNumberOfTrades(Long numberOfTrades) { + this.numberOfTrades = numberOfTrades; + } + + public String getTakerBuyBaseAssetVolume() { + return takerBuyBaseAssetVolume; + } + + public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { + this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; + } + + public String getTakerBuyQuoteAssetVolume() { + return takerBuyQuoteAssetVolume; + } + + public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { + this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; + } + + public Boolean getBarFinal() { + return isBarFinal; + } + + public void setBarFinal(Boolean barFinal) { + isBarFinal = barFinal; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("openTime", openTime) + .append("open", open) + .append("high", high) + .append("low", low) + .append("close", close) + .append("volume", volume) + .append("closeTime", closeTime) + .append("intervalId", intervalId) + .append("firstTradeId", firstTradeId) + .append("lastTradeId", lastTradeId) + .append("quoteAssetVolume", quoteAssetVolume) + .append("numberOfTrades", numberOfTrades) + .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) + .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) + .append("isBarFinal", isBarFinal) + .toString(); + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java b/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java old mode 100644 new mode 100755 index b8665e448..7792fc73a --- a/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java @@ -1,50 +1,50 @@ -package com.binance.api.client.domain.event; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; - -/** - * Custom deserializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. - * - * @see CandlestickEvent - */ -public class CandlestickEventDeserializer extends JsonDeserializer { - - @Override - public CandlestickEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - - CandlestickEvent candlestickEvent = new CandlestickEvent(); - - // Parse header - candlestickEvent.setEventType(node.get("e").asText()); - candlestickEvent.setEventTime(node.get("E").asLong()); - candlestickEvent.setSymbol(node.get("s").asText()); - - // Parse candlestick data - JsonNode candlestickNode = node.get("k"); - candlestickEvent.setOpenTime(candlestickNode.get("t").asLong()); - candlestickEvent.setCloseTime(candlestickNode.get("T").asLong()); - candlestickEvent.setIntervalId(candlestickNode.get("i").asText()); - candlestickEvent.setFirstTradeId(candlestickNode.get("f").asLong()); - candlestickEvent.setLastTradeId(candlestickNode.get("L").asLong()); - candlestickEvent.setOpen(candlestickNode.get("o").asText()); - candlestickEvent.setClose(candlestickNode.get("c").asText()); - candlestickEvent.setHigh(candlestickNode.get("h").asText()); - candlestickEvent.setLow(candlestickNode.get("l").asText()); - candlestickEvent.setVolume(candlestickNode.get("v").asText()); - candlestickEvent.setNumberOfTrades(candlestickNode.get("n").asLong()); - candlestickEvent.setBarFinal(candlestickNode.get("x").asBoolean()); - candlestickEvent.setQuoteAssetVolume(candlestickNode.get("q").asText()); - candlestickEvent.setTakerBuyBaseAssetVolume(candlestickNode.get("V").asText()); - candlestickEvent.setTakerBuyQuoteAssetVolume(candlestickNode.get("Q").asText()); - - return candlestickEvent; - } +package com.binance.api.client.domain.event; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; + +/** + * Custom deserializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. + * + * @see CandlestickEvent + */ +public class CandlestickEventDeserializer extends JsonDeserializer { + + @Override + public CandlestickEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + + CandlestickEvent candlestickEvent = new CandlestickEvent(); + + // Parse header + candlestickEvent.setEventType(node.get("e").asText()); + candlestickEvent.setEventTime(node.get("E").asLong()); + candlestickEvent.setSymbol(node.get("s").asText()); + + // Parse candlestick data + JsonNode candlestickNode = node.get("k"); + candlestickEvent.setOpenTime(candlestickNode.get("t").asLong()); + candlestickEvent.setCloseTime(candlestickNode.get("T").asLong()); + candlestickEvent.setIntervalId(candlestickNode.get("i").asText()); + candlestickEvent.setFirstTradeId(candlestickNode.get("f").asLong()); + candlestickEvent.setLastTradeId(candlestickNode.get("L").asLong()); + candlestickEvent.setOpen(candlestickNode.get("o").asText()); + candlestickEvent.setClose(candlestickNode.get("c").asText()); + candlestickEvent.setHigh(candlestickNode.get("h").asText()); + candlestickEvent.setLow(candlestickNode.get("l").asText()); + candlestickEvent.setVolume(candlestickNode.get("v").asText()); + candlestickEvent.setNumberOfTrades(candlestickNode.get("n").asLong()); + candlestickEvent.setBarFinal(candlestickNode.get("x").asBoolean()); + candlestickEvent.setQuoteAssetVolume(candlestickNode.get("q").asText()); + candlestickEvent.setTakerBuyBaseAssetVolume(candlestickNode.get("V").asText()); + candlestickEvent.setTakerBuyQuoteAssetVolume(candlestickNode.get("Q").asText()); + + return candlestickEvent; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java b/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java old mode 100644 new mode 100755 index 34f03370e..2ceb99956 --- a/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java +++ b/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.event; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.JsonSerializer; - -import java.io.IOException; - -/** - * Custom serializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. - * - * @see CandlestickEvent - */ -public class CandlestickEventSerializer extends JsonSerializer { - - @Override - public void serialize(CandlestickEvent candlestickEvent, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - - // Write header - gen.writeStringField("e", candlestickEvent.getEventType()); - gen.writeNumberField("E", candlestickEvent.getEventTime()); - gen.writeStringField("s", candlestickEvent.getSymbol()); - - // Write candlestick data - gen.writeObjectFieldStart("k"); - gen.writeNumberField("t", candlestickEvent.getOpenTime()); - gen.writeNumberField("T", candlestickEvent.getCloseTime()); - gen.writeStringField("i", candlestickEvent.getIntervalId()); - gen.writeNumberField("f", candlestickEvent.getFirstTradeId()); - gen.writeNumberField("L", candlestickEvent.getLastTradeId()); - gen.writeStringField("o", candlestickEvent.getOpen()); - gen.writeStringField("c", candlestickEvent.getClose()); - gen.writeStringField("h", candlestickEvent.getHigh()); - gen.writeStringField("l", candlestickEvent.getLow()); - gen.writeStringField("v", candlestickEvent.getVolume()); - gen.writeNumberField("n", candlestickEvent.getNumberOfTrades()); - gen.writeBooleanField("x", candlestickEvent.getBarFinal()); - gen.writeStringField("q", candlestickEvent.getQuoteAssetVolume()); - gen.writeStringField("V", candlestickEvent.getTakerBuyBaseAssetVolume()); - gen.writeStringField("Q", candlestickEvent.getTakerBuyQuoteAssetVolume()); - gen.writeEndObject(); - } -} +package com.binance.api.client.domain.event; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.JsonSerializer; + +import java.io.IOException; + +/** + * Custom serializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. + * + * @see CandlestickEvent + */ +public class CandlestickEventSerializer extends JsonSerializer { + + @Override + public void serialize(CandlestickEvent candlestickEvent, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + + // Write header + gen.writeStringField("e", candlestickEvent.getEventType()); + gen.writeNumberField("E", candlestickEvent.getEventTime()); + gen.writeStringField("s", candlestickEvent.getSymbol()); + + // Write candlestick data + gen.writeObjectFieldStart("k"); + gen.writeNumberField("t", candlestickEvent.getOpenTime()); + gen.writeNumberField("T", candlestickEvent.getCloseTime()); + gen.writeStringField("i", candlestickEvent.getIntervalId()); + gen.writeNumberField("f", candlestickEvent.getFirstTradeId()); + gen.writeNumberField("L", candlestickEvent.getLastTradeId()); + gen.writeStringField("o", candlestickEvent.getOpen()); + gen.writeStringField("c", candlestickEvent.getClose()); + gen.writeStringField("h", candlestickEvent.getHigh()); + gen.writeStringField("l", candlestickEvent.getLow()); + gen.writeStringField("v", candlestickEvent.getVolume()); + gen.writeNumberField("n", candlestickEvent.getNumberOfTrades()); + gen.writeBooleanField("x", candlestickEvent.getBarFinal()); + gen.writeStringField("q", candlestickEvent.getQuoteAssetVolume()); + gen.writeStringField("V", candlestickEvent.getTakerBuyBaseAssetVolume()); + gen.writeStringField("Q", candlestickEvent.getTakerBuyQuoteAssetVolume()); + gen.writeEndObject(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/DepthEvent.java b/src/main/java/com/binance/api/client/domain/event/DepthEvent.java old mode 100644 new mode 100755 index 4dfe6a77a..0d24ffcf7 --- a/src/main/java/com/binance/api/client/domain/event/DepthEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/DepthEvent.java @@ -1,131 +1,131 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.market.OrderBookEntry; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Depth delta event for a symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class DepthEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("s") - private String symbol; - - @JsonProperty("U") - private long firstUpdateId; - - /** - * updateId to sync up with updateid in /api/v1/depth - */ - @JsonProperty("u") - private long finalUpdateId; - - /** - * Bid depth delta. - */ - @JsonProperty("b") - private List bids; - - /** - * Ask depth delta. - */ - @JsonProperty("a") - private List asks; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public long getFirstUpdateId() { - return firstUpdateId; - } - - public void setFirstUpdateId(final long firstUpdateId) { - this.firstUpdateId = firstUpdateId; - } - - public long getFinalUpdateId() { - return finalUpdateId; - } - - public void setFinalUpdateId(long finalUpdateId) { - this.finalUpdateId = finalUpdateId; - } - - /** - * @deprecated Use {@link #getFinalUpdateId} - */ - @Deprecated - public long getUpdateId() { - return finalUpdateId; - } - - /** - * @deprecated Use {@link #setFinalUpdateId} - */ - @Deprecated - public void setUpdateId(long updateId) { - this.finalUpdateId = updateId; - } - - public List getBids() { - return bids; - } - - public void setBids(List bids) { - this.bids = bids; - } - - public List getAsks() { - return asks; - } - - public void setAsks(List asks) { - this.asks = asks; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("firstUpdateId", firstUpdateId) - .append("finalUpdateId", finalUpdateId) - .append("bids", bids) - .append("asks", asks) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.market.OrderBookEntry; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Depth delta event for a symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DepthEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("U") + private long firstUpdateId; + + /** + * updateId to sync up with updateid in /api/v1/depth + */ + @JsonProperty("u") + private long finalUpdateId; + + /** + * Bid depth delta. + */ + @JsonProperty("b") + private List bids; + + /** + * Ask depth delta. + */ + @JsonProperty("a") + private List asks; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public long getFirstUpdateId() { + return firstUpdateId; + } + + public void setFirstUpdateId(final long firstUpdateId) { + this.firstUpdateId = firstUpdateId; + } + + public long getFinalUpdateId() { + return finalUpdateId; + } + + public void setFinalUpdateId(long finalUpdateId) { + this.finalUpdateId = finalUpdateId; + } + + /** + * @deprecated Use {@link #getFinalUpdateId} + */ + @Deprecated + public long getUpdateId() { + return finalUpdateId; + } + + /** + * @deprecated Use {@link #setFinalUpdateId} + */ + @Deprecated + public void setUpdateId(long updateId) { + this.finalUpdateId = updateId; + } + + public List getBids() { + return bids; + } + + public void setBids(List bids) { + this.bids = bids; + } + + public List getAsks() { + return asks; + } + + public void setAsks(List asks) { + this.asks = asks; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("firstUpdateId", firstUpdateId) + .append("finalUpdateId", finalUpdateId) + .append("bids", bids) + .append("asks", asks) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/ListenKey.java b/src/main/java/com/binance/api/client/domain/event/ListenKey.java old mode 100644 new mode 100755 index cfce64396..a5ab73977 --- a/src/main/java/com/binance/api/client/domain/event/ListenKey.java +++ b/src/main/java/com/binance/api/client/domain/event/ListenKey.java @@ -1,25 +1,25 @@ -package com.binance.api.client.domain.event; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Dummy type to wrap a listen key from a server response. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ListenKey { - - private String listenKey; - - public String getListenKey() { - return listenKey; - } - - public void setListenKey(String listenKey) { - this.listenKey = listenKey; - } - - @Override - public String toString() { - return listenKey; - } -} +package com.binance.api.client.domain.event; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Dummy type to wrap a listen key from a server response. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ListenKey { + + private String listenKey; + + public String getListenKey() { + return listenKey; + } + + public void setListenKey(String listenKey) { + this.listenKey = listenKey; + } + + @Override + public String toString() { + return listenKey; + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java old mode 100644 new mode 100755 index cf7ab86e3..4b6c4319e --- a/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java @@ -1,318 +1,318 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.ExecutionType; -import com.binance.api.client.domain.OrderRejectReason; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Order or trade report update event. - * - * This event is embedded as part of a user data update event. - * - * @see UserDataUpdateEvent - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderTradeUpdateEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private Long eventTime; - - @JsonProperty("s") - private String symbol; - - @JsonProperty("c") - private String newClientOrderId; - - /** - * Buy/Sell order side. - */ - @JsonProperty("S") - private OrderSide side; - - /** - * Type of order. - */ - @JsonProperty("o") - private OrderType type; - - /** - * Time in force to indicate how long will the order remain active. - */ - @JsonProperty("f") - private TimeInForce timeInForce; - - /** - * Original quantity in the order. - */ - @JsonProperty("q") - private String originalQuantity; - - /** - * Price. - */ - @JsonProperty("p") - private String price; - - /** - * Type of execution. - */ - @JsonProperty("x") - private ExecutionType executionType; - - /** - * Status of the order. - */ - @JsonProperty("X") - private OrderStatus orderStatus; - - /** - * Reason why the order was rejected. - */ - @JsonProperty("r") - private OrderRejectReason orderRejectReason; - - /** - * Order id. - */ - @JsonProperty("i") - private Long orderId; - - /** - * Quantity of the last filled trade. - */ - @JsonProperty("l") - private String quantityLastFilledTrade; - - /** - * Accumulated quantity of filled trades on this order. - */ - @JsonProperty("z") - private String accumulatedQuantity; - - /** - * Price of last filled trade. - */ - @JsonProperty("L") - private String priceOfLastFilledTrade; - - /** - * Commission. - */ - @JsonProperty("n") - private String commission; - - /** - * Asset on which commission is taken - */ - @JsonProperty("N") - private String commissionAsset; - - /** - * Order/trade time. - */ - @JsonProperty("T") - private Long orderTradeTime; - - /** - * Trade id. - */ - @JsonProperty("t") - private Long tradeId; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public Long getEventTime() { - return eventTime; - } - - public void setEventTime(Long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getNewClientOrderId() { - return newClientOrderId; - } - - public void setNewClientOrderId(String newClientOrderId) { - this.newClientOrderId = newClientOrderId; - } - - public OrderSide getSide() { - return side; - } - - public void setSide(OrderSide side) { - this.side = side; - } - - public OrderType getType() { - return type; - } - - public void setType(OrderType type) { - this.type = type; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public void setTimeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - } - - public String getOriginalQuantity() { - return originalQuantity; - } - - public void setOriginalQuantity(String originalQuantity) { - this.originalQuantity = originalQuantity; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public ExecutionType getExecutionType() { - return executionType; - } - - public void setExecutionType(ExecutionType executionType) { - this.executionType = executionType; - } - - public OrderStatus getOrderStatus() { - return orderStatus; - } - - public void setOrderStatus(OrderStatus orderStatus) { - this.orderStatus = orderStatus; - } - - public OrderRejectReason getOrderRejectReason() { - return orderRejectReason; - } - - public void setOrderRejectReason(OrderRejectReason orderRejectReason) { - this.orderRejectReason = orderRejectReason; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - - public String getQuantityLastFilledTrade() { - return quantityLastFilledTrade; - } - - public void setQuantityLastFilledTrade(String quantityLastFilledTrade) { - this.quantityLastFilledTrade = quantityLastFilledTrade; - } - - public String getAccumulatedQuantity() { - return accumulatedQuantity; - } - - public void setAccumulatedQuantity(String accumulatedQuantity) { - this.accumulatedQuantity = accumulatedQuantity; - } - - public String getPriceOfLastFilledTrade() { - return priceOfLastFilledTrade; - } - - public void setPriceOfLastFilledTrade(String priceOfLastFilledTrade) { - this.priceOfLastFilledTrade = priceOfLastFilledTrade; - } - - public String getCommission() { - return commission; - } - - public void setCommission(String commission) { - this.commission = commission; - } - - public String getCommissionAsset() { - return commissionAsset; - } - - public void setCommissionAsset(String commissionAsset) { - this.commissionAsset = commissionAsset; - } - - public Long getOrderTradeTime() { - return orderTradeTime; - } - - public void setOrderTradeTime(Long orderTradeTime) { - this.orderTradeTime = orderTradeTime; - } - - public Long getTradeId() { - return tradeId; - } - - public void setTradeId(Long tradeId) { - this.tradeId = tradeId; - } - - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("newClientOrderId", newClientOrderId) - .append("side", side) - .append("type", type) - .append("timeInForce", timeInForce) - .append("originalQuantity", originalQuantity) - .append("price", price) - .append("executionType", executionType) - .append("orderStatus", orderStatus) - .append("orderRejectReason", orderRejectReason) - .append("orderId", orderId) - .append("quantityLastFilledTrade", quantityLastFilledTrade) - .append("accumulatedQuantity", accumulatedQuantity) - .append("priceOfLastFilledTrade", priceOfLastFilledTrade) - .append("commission", commission) - .append("commissionAsset", commissionAsset) - .append("orderTradeTime", orderTradeTime) - .append("tradeId", tradeId) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.ExecutionType; +import com.binance.api.client.domain.OrderRejectReason; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Order or trade report update event. + * + * This event is embedded as part of a user data update event. + * + * @see UserDataUpdateEvent + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderTradeUpdateEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private Long eventTime; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("c") + private String newClientOrderId; + + /** + * Buy/Sell order side. + */ + @JsonProperty("S") + private OrderSide side; + + /** + * Type of order. + */ + @JsonProperty("o") + private OrderType type; + + /** + * Time in force to indicate how long will the order remain active. + */ + @JsonProperty("f") + private TimeInForce timeInForce; + + /** + * Original quantity in the order. + */ + @JsonProperty("q") + private String originalQuantity; + + /** + * Price. + */ + @JsonProperty("p") + private String price; + + /** + * Type of execution. + */ + @JsonProperty("x") + private ExecutionType executionType; + + /** + * Status of the order. + */ + @JsonProperty("X") + private OrderStatus orderStatus; + + /** + * Reason why the order was rejected. + */ + @JsonProperty("r") + private OrderRejectReason orderRejectReason; + + /** + * Order id. + */ + @JsonProperty("i") + private Long orderId; + + /** + * Quantity of the last filled trade. + */ + @JsonProperty("l") + private String quantityLastFilledTrade; + + /** + * Accumulated quantity of filled trades on this order. + */ + @JsonProperty("z") + private String accumulatedQuantity; + + /** + * Price of last filled trade. + */ + @JsonProperty("L") + private String priceOfLastFilledTrade; + + /** + * Commission. + */ + @JsonProperty("n") + private String commission; + + /** + * Asset on which commission is taken + */ + @JsonProperty("N") + private String commissionAsset; + + /** + * Order/trade time. + */ + @JsonProperty("T") + private Long orderTradeTime; + + /** + * Trade id. + */ + @JsonProperty("t") + private Long tradeId; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public Long getEventTime() { + return eventTime; + } + + public void setEventTime(Long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public void setNewClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public String getOriginalQuantity() { + return originalQuantity; + } + + public void setOriginalQuantity(String originalQuantity) { + this.originalQuantity = originalQuantity; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public ExecutionType getExecutionType() { + return executionType; + } + + public void setExecutionType(ExecutionType executionType) { + this.executionType = executionType; + } + + public OrderStatus getOrderStatus() { + return orderStatus; + } + + public void setOrderStatus(OrderStatus orderStatus) { + this.orderStatus = orderStatus; + } + + public OrderRejectReason getOrderRejectReason() { + return orderRejectReason; + } + + public void setOrderRejectReason(OrderRejectReason orderRejectReason) { + this.orderRejectReason = orderRejectReason; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } + + public String getQuantityLastFilledTrade() { + return quantityLastFilledTrade; + } + + public void setQuantityLastFilledTrade(String quantityLastFilledTrade) { + this.quantityLastFilledTrade = quantityLastFilledTrade; + } + + public String getAccumulatedQuantity() { + return accumulatedQuantity; + } + + public void setAccumulatedQuantity(String accumulatedQuantity) { + this.accumulatedQuantity = accumulatedQuantity; + } + + public String getPriceOfLastFilledTrade() { + return priceOfLastFilledTrade; + } + + public void setPriceOfLastFilledTrade(String priceOfLastFilledTrade) { + this.priceOfLastFilledTrade = priceOfLastFilledTrade; + } + + public String getCommission() { + return commission; + } + + public void setCommission(String commission) { + this.commission = commission; + } + + public String getCommissionAsset() { + return commissionAsset; + } + + public void setCommissionAsset(String commissionAsset) { + this.commissionAsset = commissionAsset; + } + + public Long getOrderTradeTime() { + return orderTradeTime; + } + + public void setOrderTradeTime(Long orderTradeTime) { + this.orderTradeTime = orderTradeTime; + } + + public Long getTradeId() { + return tradeId; + } + + public void setTradeId(Long tradeId) { + this.tradeId = tradeId; + } + + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("newClientOrderId", newClientOrderId) + .append("side", side) + .append("type", type) + .append("timeInForce", timeInForce) + .append("originalQuantity", originalQuantity) + .append("price", price) + .append("executionType", executionType) + .append("orderStatus", orderStatus) + .append("orderRejectReason", orderRejectReason) + .append("orderId", orderId) + .append("quantityLastFilledTrade", quantityLastFilledTrade) + .append("accumulatedQuantity", accumulatedQuantity) + .append("priceOfLastFilledTrade", priceOfLastFilledTrade) + .append("commission", commission) + .append("commissionAsset", commissionAsset) + .append("orderTradeTime", orderTradeTime) + .append("tradeId", tradeId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java old mode 100644 new mode 100755 index e0cd92bf2..f9d3f7bf9 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java @@ -1,100 +1,100 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * User data update event which can be of two types: - * - * 1) outboundAccountInfo, whenever there is a change in the account (e.g. balance of an asset) - * 2) outboundAccountPosition, the change in account balances caused by an event. - * 3) executionReport, whenever there is a trade or an order - */ -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonDeserialize(using = UserDataUpdateEventDeserializer.class) -public class UserDataUpdateEvent { - - private UserDataUpdateEventType eventType; - - private long eventTime; - - private AccountUpdateEvent accountUpdateEvent; - - private OrderTradeUpdateEvent orderTradeUpdateEvent; - - public UserDataUpdateEventType getEventType() { - return eventType; - } - - public void setEventType(UserDataUpdateEventType eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public AccountUpdateEvent getAccountUpdateEvent() { - return accountUpdateEvent; - } - - public void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { - this.accountUpdateEvent = accountUpdateEvent; - } - - public OrderTradeUpdateEvent getOrderTradeUpdateEvent() { - return orderTradeUpdateEvent; - } - - public void setOrderTradeUpdateEvent(OrderTradeUpdateEvent orderTradeUpdateEvent) { - this.orderTradeUpdateEvent = orderTradeUpdateEvent; - } - - @Override - public String toString() { - ToStringBuilder sb = new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime); - if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { - sb.append("accountUpdateEvent", accountUpdateEvent); - } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { - sb.append("accountPositionUpdateEvent", accountUpdateEvent); - } else { - sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); - } - return sb.toString(); - } - - public enum UserDataUpdateEventType { - ACCOUNT_UPDATE("outboundAccountInfo"), - ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), - ORDER_TRADE_UPDATE("executionReport"); - - private final String eventTypeId; - - UserDataUpdateEventType(String eventTypeId) { - this.eventTypeId = eventTypeId; - } - - public String getEventTypeId() { - return eventTypeId; - } - - public static UserDataUpdateEventType fromEventTypeId(String eventTypeId) { - if (ACCOUNT_UPDATE.eventTypeId.equals(eventTypeId)) { - return ACCOUNT_UPDATE; - } else if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { - return ORDER_TRADE_UPDATE; - } else if (ACCOUNT_POSITION_UPDATE.eventTypeId.equals(eventTypeId)) { - return ACCOUNT_POSITION_UPDATE; - } - throw new IllegalArgumentException("Unrecognized user data update event type id: " + eventTypeId); - } - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * User data update event which can be of two types: + * + * 1) outboundAccountInfo, whenever there is a change in the account (e.g. balance of an asset) + * 2) outboundAccountPosition, the change in account balances caused by an event. + * 3) executionReport, whenever there is a trade or an order + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonDeserialize(using = UserDataUpdateEventDeserializer.class) +public class UserDataUpdateEvent { + + private UserDataUpdateEventType eventType; + + private long eventTime; + + private AccountUpdateEvent accountUpdateEvent; + + private OrderTradeUpdateEvent orderTradeUpdateEvent; + + public UserDataUpdateEventType getEventType() { + return eventType; + } + + public void setEventType(UserDataUpdateEventType eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public AccountUpdateEvent getAccountUpdateEvent() { + return accountUpdateEvent; + } + + public void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { + this.accountUpdateEvent = accountUpdateEvent; + } + + public OrderTradeUpdateEvent getOrderTradeUpdateEvent() { + return orderTradeUpdateEvent; + } + + public void setOrderTradeUpdateEvent(OrderTradeUpdateEvent orderTradeUpdateEvent) { + this.orderTradeUpdateEvent = orderTradeUpdateEvent; + } + + @Override + public String toString() { + ToStringBuilder sb = new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime); + if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { + sb.append("accountUpdateEvent", accountUpdateEvent); + } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + sb.append("accountPositionUpdateEvent", accountUpdateEvent); + } else { + sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); + } + return sb.toString(); + } + + public enum UserDataUpdateEventType { + ACCOUNT_UPDATE("outboundAccountInfo"), + ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), + ORDER_TRADE_UPDATE("executionReport"); + + private final String eventTypeId; + + UserDataUpdateEventType(String eventTypeId) { + this.eventTypeId = eventTypeId; + } + + public String getEventTypeId() { + return eventTypeId; + } + + public static UserDataUpdateEventType fromEventTypeId(String eventTypeId) { + if (ACCOUNT_UPDATE.eventTypeId.equals(eventTypeId)) { + return ACCOUNT_UPDATE; + } else if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { + return ORDER_TRADE_UPDATE; + } else if (ACCOUNT_POSITION_UPDATE.eventTypeId.equals(eventTypeId)) { + return ACCOUNT_POSITION_UPDATE; + } + throw new IllegalArgumentException("Unrecognized user data update event type id: " + eventTypeId); + } + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java old mode 100644 new mode 100755 index 8ef548e39..45d4829df --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java @@ -1,60 +1,60 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; -import com.binance.api.client.exception.BinanceApiException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; - -/** - * Custom deserializer for a User Data stream event, since the API can return two different responses in this stream. - * @see UserDataUpdateEvent - */ -public class UserDataUpdateEventDeserializer extends JsonDeserializer { - - private ObjectMapper mapper; - - @Override - public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - - if (mapper == null){ - mapper = new ObjectMapper(); - } - - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - String json = node.toString(); - - final String eventTypeId = node.get("e").asText(); - final Long eventTime = node.get("E").asLong(); - UserDataUpdateEventType userDataUpdateEventType = UserDataUpdateEventType.fromEventTypeId(eventTypeId); - - UserDataUpdateEvent userDataUpdateEvent = new UserDataUpdateEvent(); - userDataUpdateEvent.setEventType(userDataUpdateEventType); - userDataUpdateEvent.setEventTime(eventTime); - - if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE || - userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { - AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); - userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); - } else { // userDataUpdateEventType == UserDataUpdateEventType.ORDER_TRADE_UPDATE - OrderTradeUpdateEvent orderTradeUpdateEvent = getUserDataUpdateEventDetail(json, OrderTradeUpdateEvent.class, mapper); - userDataUpdateEvent.setOrderTradeUpdateEvent(orderTradeUpdateEvent); - } - - return userDataUpdateEvent; - } - - public T getUserDataUpdateEventDetail(String json, Class clazz, ObjectMapper mapper) { - try { - return mapper.readValue(json, clazz); - } catch (IOException e) { - throw new BinanceApiException(e); - } - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; +import com.binance.api.client.exception.BinanceApiException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; + +/** + * Custom deserializer for a User Data stream event, since the API can return two different responses in this stream. + * @see UserDataUpdateEvent + */ +public class UserDataUpdateEventDeserializer extends JsonDeserializer { + + private ObjectMapper mapper; + + @Override + public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + + if (mapper == null){ + mapper = new ObjectMapper(); + } + + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + String json = node.toString(); + + final String eventTypeId = node.get("e").asText(); + final Long eventTime = node.get("E").asLong(); + UserDataUpdateEventType userDataUpdateEventType = UserDataUpdateEventType.fromEventTypeId(eventTypeId); + + UserDataUpdateEvent userDataUpdateEvent = new UserDataUpdateEvent(); + userDataUpdateEvent.setEventType(userDataUpdateEventType); + userDataUpdateEvent.setEventTime(eventTime); + + if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE || + userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); + userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); + } else { // userDataUpdateEventType == UserDataUpdateEventType.ORDER_TRADE_UPDATE + OrderTradeUpdateEvent orderTradeUpdateEvent = getUserDataUpdateEventDetail(json, OrderTradeUpdateEvent.class, mapper); + userDataUpdateEvent.setOrderTradeUpdateEvent(orderTradeUpdateEvent); + } + + return userDataUpdateEvent; + } + + public T getUserDataUpdateEventDetail(String json, Class clazz, ObjectMapper mapper) { + try { + return mapper.readValue(json, clazz); + } catch (IOException e) { + throw new BinanceApiException(e); + } + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/Asset.java b/src/main/java/com/binance/api/client/domain/general/Asset.java old mode 100644 new mode 100755 index 4a286acc6..715190f31 --- a/src/main/java/com/binance/api/client/domain/general/Asset.java +++ b/src/main/java/com/binance/api/client/domain/general/Asset.java @@ -1,123 +1,123 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An asset Binance supports. - */ - @JsonIgnoreProperties(ignoreUnknown = true) - public class Asset { - - @JsonProperty("id") - private String id; - - @JsonProperty("assetCode") - private String assetCode; - - @JsonProperty("assetName") - private String assetName; - - @JsonProperty("unit") - private String unit; - - @JsonProperty("transactionFee") - private String transactionFee; - - @JsonProperty("commissionRate") - private String commissionRate; - - @JsonProperty("freeAuditWithdrawAmt") - private String freeAuditWithdrawAmount; - - @JsonProperty("freeUserChargeAmount") - private String freeUserChargeAmount; - - @JsonProperty("minProductWithdraw") - private String minProductWithdraw; - - @JsonProperty("withdrawIntegerMultiple") - private String withdrawIntegerMultiple; - - @JsonProperty("confirmTimes") - private long confirmTimes; - - @JsonProperty("enableWithdraw") - private boolean enableWithdraw; - - @JsonProperty("isLegalMoney") - private boolean isLegalMoney; - - public String getId() { - return id; - } - - public String getAssetCode() { - return assetCode; - } - - public String getAssetName() { - return assetName; - } - - public String getUnit() { - return unit; - } - - public String getTransactionFee() { - return transactionFee; - } - - public String getCommissionRate() { - return commissionRate; - } - - public String getFreeAuditWithdrawAmount() { - return freeAuditWithdrawAmount; - } - - public String getFreeUserChargeAmount() { - return freeUserChargeAmount; - } - - public String minProductWithdraw() { - return minProductWithdraw; - } - - public String getWithdrawIntegerMultiple() { - return withdrawIntegerMultiple; - } - - public long getConfirmTimes() { - return confirmTimes; - } - - public boolean canWithraw() { - return enableWithdraw; - } - - public boolean isLegalMoney() { - return isLegalMoney; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("id", id) - .append("assetCode", assetCode) - .append("assetName", assetName) - .append("unit", unit) - .append("transactionFee", transactionFee) - .append("commissionRate", commissionRate) - .append("freeAuditWithdrawAmount", freeAuditWithdrawAmount) - .append("freeUserChargeAmount", freeUserChargeAmount) - .append("minProductWithdraw", minProductWithdraw) - .append("withdrawIntegerMultiple", withdrawIntegerMultiple) - .append("confirmTimes", confirmTimes) - .append("enableWithdraw", enableWithdraw) - .append("isLegalMoney", isLegalMoney) - .toString(); - } - } +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An asset Binance supports. + */ + @JsonIgnoreProperties(ignoreUnknown = true) + public class Asset { + + @JsonProperty("id") + private String id; + + @JsonProperty("assetCode") + private String assetCode; + + @JsonProperty("assetName") + private String assetName; + + @JsonProperty("unit") + private String unit; + + @JsonProperty("transactionFee") + private String transactionFee; + + @JsonProperty("commissionRate") + private String commissionRate; + + @JsonProperty("freeAuditWithdrawAmt") + private String freeAuditWithdrawAmount; + + @JsonProperty("freeUserChargeAmount") + private String freeUserChargeAmount; + + @JsonProperty("minProductWithdraw") + private String minProductWithdraw; + + @JsonProperty("withdrawIntegerMultiple") + private String withdrawIntegerMultiple; + + @JsonProperty("confirmTimes") + private long confirmTimes; + + @JsonProperty("enableWithdraw") + private boolean enableWithdraw; + + @JsonProperty("isLegalMoney") + private boolean isLegalMoney; + + public String getId() { + return id; + } + + public String getAssetCode() { + return assetCode; + } + + public String getAssetName() { + return assetName; + } + + public String getUnit() { + return unit; + } + + public String getTransactionFee() { + return transactionFee; + } + + public String getCommissionRate() { + return commissionRate; + } + + public String getFreeAuditWithdrawAmount() { + return freeAuditWithdrawAmount; + } + + public String getFreeUserChargeAmount() { + return freeUserChargeAmount; + } + + public String minProductWithdraw() { + return minProductWithdraw; + } + + public String getWithdrawIntegerMultiple() { + return withdrawIntegerMultiple; + } + + public long getConfirmTimes() { + return confirmTimes; + } + + public boolean canWithraw() { + return enableWithdraw; + } + + public boolean isLegalMoney() { + return isLegalMoney; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("id", id) + .append("assetCode", assetCode) + .append("assetName", assetName) + .append("unit", unit) + .append("transactionFee", transactionFee) + .append("commissionRate", commissionRate) + .append("freeAuditWithdrawAmount", freeAuditWithdrawAmount) + .append("freeUserChargeAmount", freeUserChargeAmount) + .append("minProductWithdraw", minProductWithdraw) + .append("withdrawIntegerMultiple", withdrawIntegerMultiple) + .append("confirmTimes", confirmTimes) + .append("enableWithdraw", enableWithdraw) + .append("isLegalMoney", isLegalMoney) + .toString(); + } + } diff --git a/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java b/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java old mode 100644 new mode 100755 index e492111a8..e367deaef --- a/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java +++ b/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Exchange Filters define trading rules an exchange. - * - * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on the exchange. Note that both "algo" orders and normal orders are counted for this filter. - * - * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on the exchange. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ExchangeFilter { - - private FilterType filterType; - - private Integer limit; - - public FilterType getFilterType() { - return filterType; - } - - public void setFilterType(FilterType filterType) { - this.filterType = filterType; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("filterType", filterType) - .append("limit", limit) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Exchange Filters define trading rules an exchange. + * + * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on the exchange. Note that both "algo" orders and normal orders are counted for this filter. + * + * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on the exchange. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ExchangeFilter { + + private FilterType filterType; + + private Integer limit; + + public FilterType getFilterType() { + return filterType; + } + + public void setFilterType(FilterType filterType) { + this.filterType = filterType; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("filterType", filterType) + .append("limit", limit) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java b/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java old mode 100644 new mode 100755 index ab88f3c5c..b12c1d20c --- a/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java +++ b/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java @@ -1,78 +1,78 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.exception.BinanceApiException; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Current exchange trading rules and symbol information. - * https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ExchangeInfo { - - private String timezone; - - private Long serverTime; - - private List rateLimits; - - // private List exchangeFilters; - - private List symbols; - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public Long getServerTime() { - return serverTime; - } - - public void setServerTime(Long serverTime) { - this.serverTime = serverTime; - } - - public List getRateLimits() { - return rateLimits; - } - - public void setRateLimits(List rateLimits) { - this.rateLimits = rateLimits; - } - - public List getSymbols() { - return symbols; - } - - public void setSymbols(List symbols) { - this.symbols = symbols; - } - - /** - * @param symbol the symbol to obtain information for (e.g. ETHBTC) - * @return symbol exchange information - */ - public SymbolInfo getSymbolInfo(String symbol) { - return symbols.stream().filter(symbolInfo -> symbolInfo.getSymbol().equals(symbol)) - .findFirst() - .orElseThrow(() -> new BinanceApiException("Unable to obtain information for symbol " + symbol)); - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("timezone", timezone) - .append("serverTime", serverTime) - .append("rateLimits", rateLimits) - .append("symbols", symbols) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.exception.BinanceApiException; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Current exchange trading rules and symbol information. + * https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ExchangeInfo { + + private String timezone; + + private Long serverTime; + + private List rateLimits; + + // private List exchangeFilters; + + private List symbols; + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public Long getServerTime() { + return serverTime; + } + + public void setServerTime(Long serverTime) { + this.serverTime = serverTime; + } + + public List getRateLimits() { + return rateLimits; + } + + public void setRateLimits(List rateLimits) { + this.rateLimits = rateLimits; + } + + public List getSymbols() { + return symbols; + } + + public void setSymbols(List symbols) { + this.symbols = symbols; + } + + /** + * @param symbol the symbol to obtain information for (e.g. ETHBTC) + * @return symbol exchange information + */ + public SymbolInfo getSymbolInfo(String symbol) { + return symbols.stream().filter(symbolInfo -> symbolInfo.getSymbol().equals(symbol)) + .findFirst() + .orElseThrow(() -> new BinanceApiException("Unable to obtain information for symbol " + symbol)); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("timezone", timezone) + .append("serverTime", serverTime) + .append("rateLimits", rateLimits) + .append("symbols", symbols) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java old mode 100644 new mode 100755 index 1959f8ec5..8dd26c46a --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -1,25 +1,25 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum FilterType { - // Symbol - PRICE_FILTER, - LOT_SIZE, - MIN_NOTIONAL, - MAX_NUM_ORDERS, - MAX_ALGO_ORDERS, - MAX_NUM_ALGO_ORDERS, - ICEBERG_PARTS, - PERCENT_PRICE, - MARKET_LOT_SIZE, - MAX_NUM_ICEBERG_ORDERS, - - // Exchange - EXCHANGE_MAX_NUM_ORDERS, - EXCHANGE_MAX_ALGO_ORDERS -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum FilterType { + // Symbol + PRICE_FILTER, + LOT_SIZE, + MIN_NOTIONAL, + MAX_NUM_ORDERS, + MAX_ALGO_ORDERS, + MAX_NUM_ALGO_ORDERS, + ICEBERG_PARTS, + PERCENT_PRICE, + MARKET_LOT_SIZE, + MAX_NUM_ICEBERG_ORDERS, + + // Exchange + EXCHANGE_MAX_NUM_ORDERS, + EXCHANGE_MAX_ALGO_ORDERS +} diff --git a/src/main/java/com/binance/api/client/domain/general/RateLimit.java b/src/main/java/com/binance/api/client/domain/general/RateLimit.java old mode 100644 new mode 100755 index e8d963c33..253f4e36a --- a/src/main/java/com/binance/api/client/domain/general/RateLimit.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimit.java @@ -1,51 +1,51 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Rate limits. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class RateLimit { - - private RateLimitType rateLimitType; - - private RateLimitInterval interval; - - private Integer limit; - - public RateLimitType getRateLimitType() { - return rateLimitType; - } - - public void setRateLimitType(RateLimitType rateLimitType) { - this.rateLimitType = rateLimitType; - } - - public RateLimitInterval getInterval() { - return interval; - } - - public void setInterval(RateLimitInterval interval) { - this.interval = interval; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("rateLimitType", rateLimitType) - .append("interval", interval) - .append("limit", limit) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Rate limits. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class RateLimit { + + private RateLimitType rateLimitType; + + private RateLimitInterval interval; + + private Integer limit; + + public RateLimitType getRateLimitType() { + return rateLimitType; + } + + public void setRateLimitType(RateLimitType rateLimitType) { + this.rateLimitType = rateLimitType; + } + + public RateLimitInterval getInterval() { + return interval; + } + + public void setInterval(RateLimitInterval interval) { + this.interval = interval; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("rateLimitType", rateLimitType) + .append("interval", interval) + .append("limit", limit) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java b/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java old mode 100644 new mode 100755 index 0c8f65fca..30edd34a4 --- a/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java @@ -1,13 +1,13 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Rate limit intervals. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum RateLimitInterval { - SECOND, - MINUTE, - DAY +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Rate limit intervals. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum RateLimitInterval { + SECOND, + MINUTE, + DAY } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/general/RateLimitType.java b/src/main/java/com/binance/api/client/domain/general/RateLimitType.java old mode 100644 new mode 100755 index db43d5d39..25775dab5 --- a/src/main/java/com/binance/api/client/domain/general/RateLimitType.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimitType.java @@ -1,12 +1,12 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Rate limiters. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum RateLimitType { - REQUEST_WEIGHT, - ORDERS -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Rate limiters. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum RateLimitType { + REQUEST_WEIGHT, + ORDERS +} diff --git a/src/main/java/com/binance/api/client/domain/general/ServerTime.java b/src/main/java/com/binance/api/client/domain/general/ServerTime.java old mode 100644 new mode 100755 index ec4880313..828ea342b --- a/src/main/java/com/binance/api/client/domain/general/ServerTime.java +++ b/src/main/java/com/binance/api/client/domain/general/ServerTime.java @@ -1,24 +1,24 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Time of the server running Binance's REST API. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ServerTime { - private Long serverTime; - - public Long getServerTime() { - return serverTime; - } - - public void setServerTime(Long serverTime) { - this.serverTime = serverTime; - } - - @Override - public String toString() { - return String.valueOf(serverTime); - } -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Time of the server running Binance's REST API. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServerTime { + private Long serverTime; + + public Long getServerTime() { + return serverTime; + } + + public void setServerTime(Long serverTime) { + this.serverTime = serverTime; + } + + @Override + public String toString() { + return String.valueOf(serverTime); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java b/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java old mode 100644 new mode 100755 index 068e0ba28..e6a8b98c8 --- a/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java @@ -1,160 +1,160 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. - * - * The PRICE_FILTER defines the price rules for a symbol. - * - * The LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for a symbol. - * - * The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. - * - * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. - * - * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class SymbolFilter { - - // PRICE_FILTER - - private FilterType filterType; - - /** - * Defines the minimum price/stopPrice allowed. - */ - private String minPrice; - - /** - * Defines the maximum price/stopPrice allowed. - */ - private String maxPrice; - - /** - * Defines the intervals that a price/stopPrice can be increased/decreased by. - */ - private String tickSize; - - - // LOT_SIZE - - /** - * Defines the minimum quantity/icebergQty allowed. - */ - private String minQty; - - /** - * Defines the maximum quantity/icebergQty allowed. - */ - private String maxQty; - - /** - * Defines the intervals that a quantity/icebergQty can be increased/decreased by. - */ - private String stepSize; - - // MIN_NOTIONAL - - /** - * Defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. - */ - private String minNotional; - - - // MAX_NUM_ALGO_ORDERS - - /** - * Defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - */ - private String maxNumAlgoOrders; - - /** - * MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. - * MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - * ICEBERG_PARTS filter defines the maximum parts an iceberg order can have. The number of ICEBERG_PARTS is defined as CEIL(qty / icebergQty). - */ - private String limit; - - public FilterType getFilterType() { - return filterType; - } - - public void setFilterType(FilterType filterType) { - this.filterType = filterType; - } - - public String getMinPrice() { - return minPrice; - } - - public void setMinPrice(String minPrice) { - this.minPrice = minPrice; - } - - public String getMaxPrice() { - return maxPrice; - } - - public void setMaxPrice(String maxPrice) { - this.maxPrice = maxPrice; - } - - public String getTickSize() { - return tickSize; - } - - public void setTickSize(String tickSize) { - this.tickSize = tickSize; - } - - public String getMinQty() { - return minQty; - } - - public void setMinQty(String minQty) { - this.minQty = minQty; - } - - public String getMaxQty() { - return maxQty; - } - - public void setMaxQty(String maxQty) { - this.maxQty = maxQty; - } - - public String getStepSize() { - return stepSize; - } - - public void setStepSize(String stepSize) { - this.stepSize = stepSize; - } - - public String getMinNotional() { - return minNotional; - } - - public void setMinNotional(String minNotional) { - this.minNotional = minNotional; - } - - public String getMaxNumAlgoOrders() { - return maxNumAlgoOrders; - } - - public SymbolFilter setMaxNumAlgoOrders(String maxNumAlgoOrders) { - this.maxNumAlgoOrders = maxNumAlgoOrders; - return this; - } - - public String getLimit() { - return limit; - } - - public void setLimit(String limit) { - this.limit = limit; - } -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. + * + * The PRICE_FILTER defines the price rules for a symbol. + * + * The LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for a symbol. + * + * The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. + * + * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. + * + * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class SymbolFilter { + + // PRICE_FILTER + + private FilterType filterType; + + /** + * Defines the minimum price/stopPrice allowed. + */ + private String minPrice; + + /** + * Defines the maximum price/stopPrice allowed. + */ + private String maxPrice; + + /** + * Defines the intervals that a price/stopPrice can be increased/decreased by. + */ + private String tickSize; + + + // LOT_SIZE + + /** + * Defines the minimum quantity/icebergQty allowed. + */ + private String minQty; + + /** + * Defines the maximum quantity/icebergQty allowed. + */ + private String maxQty; + + /** + * Defines the intervals that a quantity/icebergQty can be increased/decreased by. + */ + private String stepSize; + + // MIN_NOTIONAL + + /** + * Defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. + */ + private String minNotional; + + + // MAX_NUM_ALGO_ORDERS + + /** + * Defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + */ + private String maxNumAlgoOrders; + + /** + * MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. + * MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + * ICEBERG_PARTS filter defines the maximum parts an iceberg order can have. The number of ICEBERG_PARTS is defined as CEIL(qty / icebergQty). + */ + private String limit; + + public FilterType getFilterType() { + return filterType; + } + + public void setFilterType(FilterType filterType) { + this.filterType = filterType; + } + + public String getMinPrice() { + return minPrice; + } + + public void setMinPrice(String minPrice) { + this.minPrice = minPrice; + } + + public String getMaxPrice() { + return maxPrice; + } + + public void setMaxPrice(String maxPrice) { + this.maxPrice = maxPrice; + } + + public String getTickSize() { + return tickSize; + } + + public void setTickSize(String tickSize) { + this.tickSize = tickSize; + } + + public String getMinQty() { + return minQty; + } + + public void setMinQty(String minQty) { + this.minQty = minQty; + } + + public String getMaxQty() { + return maxQty; + } + + public void setMaxQty(String maxQty) { + this.maxQty = maxQty; + } + + public String getStepSize() { + return stepSize; + } + + public void setStepSize(String stepSize) { + this.stepSize = stepSize; + } + + public String getMinNotional() { + return minNotional; + } + + public void setMinNotional(String minNotional) { + this.minNotional = minNotional; + } + + public String getMaxNumAlgoOrders() { + return maxNumAlgoOrders; + } + + public SymbolFilter setMaxNumAlgoOrders(String maxNumAlgoOrders) { + this.maxNumAlgoOrders = maxNumAlgoOrders; + return this; + } + + public String getLimit() { + return limit; + } + + public void setLimit(String limit) { + this.limit = limit; + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java b/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java old mode 100644 new mode 100755 index 7eed2e97c..72bca07e3 --- a/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java @@ -1,131 +1,131 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderType; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Symbol information (base/quote). - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class SymbolInfo { - - private String symbol; - - private SymbolStatus status; - - private String baseAsset; - - private Integer baseAssetPrecision; - - private String quoteAsset; - - private Integer quotePrecision; - - private List orderTypes; - - private boolean icebergAllowed; - - private List filters; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public SymbolStatus getStatus() { - return status; - } - - public void setStatus(SymbolStatus status) { - this.status = status; - } - - public String getBaseAsset() { - return baseAsset; - } - - public void setBaseAsset(String baseAsset) { - this.baseAsset = baseAsset; - } - - public Integer getBaseAssetPrecision() { - return baseAssetPrecision; - } - - public void setBaseAssetPrecision(Integer baseAssetPrecision) { - this.baseAssetPrecision = baseAssetPrecision; - } - - public String getQuoteAsset() { - return quoteAsset; - } - - public void setQuoteAsset(String quoteAsset) { - this.quoteAsset = quoteAsset; - } - - public Integer getQuotePrecision() { - return quotePrecision; - } - - public void setQuotePrecision(Integer quotePrecision) { - this.quotePrecision = quotePrecision; - } - - public List getOrderTypes() { - return orderTypes; - } - - public void setOrderTypes(List orderTypes) { - this.orderTypes = orderTypes; - } - - public boolean isIcebergAllowed() { - return icebergAllowed; - } - - public void setIcebergAllowed(boolean icebergAllowed) { - this.icebergAllowed = icebergAllowed; - } - - public List getFilters() { - return filters; - } - - public void setFilters(List filters) { - this.filters = filters; - } - - /** - * @param filterType filter type to filter for. - * @return symbol filter information for the provided filter type. - */ - public SymbolFilter getSymbolFilter(FilterType filterType) { - return filters.stream() - .filter(symbolFilter -> symbolFilter.getFilterType() == filterType) - .findFirst() - .get(); - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("status", status) - .append("baseAsset", baseAsset) - .append("baseAssetPrecision", baseAssetPrecision) - .append("quoteAsset", quoteAsset) - .append("quotePrecision", quotePrecision) - .append("orderTypes", orderTypes) - .append("icebergAllowed", icebergAllowed) - .append("filters", filters) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderType; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Symbol information (base/quote). + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class SymbolInfo { + + private String symbol; + + private SymbolStatus status; + + private String baseAsset; + + private Integer baseAssetPrecision; + + private String quoteAsset; + + private Integer quotePrecision; + + private List orderTypes; + + private boolean icebergAllowed; + + private List filters; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public SymbolStatus getStatus() { + return status; + } + + public void setStatus(SymbolStatus status) { + this.status = status; + } + + public String getBaseAsset() { + return baseAsset; + } + + public void setBaseAsset(String baseAsset) { + this.baseAsset = baseAsset; + } + + public Integer getBaseAssetPrecision() { + return baseAssetPrecision; + } + + public void setBaseAssetPrecision(Integer baseAssetPrecision) { + this.baseAssetPrecision = baseAssetPrecision; + } + + public String getQuoteAsset() { + return quoteAsset; + } + + public void setQuoteAsset(String quoteAsset) { + this.quoteAsset = quoteAsset; + } + + public Integer getQuotePrecision() { + return quotePrecision; + } + + public void setQuotePrecision(Integer quotePrecision) { + this.quotePrecision = quotePrecision; + } + + public List getOrderTypes() { + return orderTypes; + } + + public void setOrderTypes(List orderTypes) { + this.orderTypes = orderTypes; + } + + public boolean isIcebergAllowed() { + return icebergAllowed; + } + + public void setIcebergAllowed(boolean icebergAllowed) { + this.icebergAllowed = icebergAllowed; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + /** + * @param filterType filter type to filter for. + * @return symbol filter information for the provided filter type. + */ + public SymbolFilter getSymbolFilter(FilterType filterType) { + return filters.stream() + .filter(symbolFilter -> symbolFilter.getFilterType() == filterType) + .findFirst() + .get(); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("status", status) + .append("baseAsset", baseAsset) + .append("baseAssetPrecision", baseAssetPrecision) + .append("quoteAsset", quoteAsset) + .append("quotePrecision", quotePrecision) + .append("orderTypes", orderTypes) + .append("icebergAllowed", icebergAllowed) + .append("filters", filters) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java b/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java old mode 100644 new mode 100755 index c12647540..77291ee77 --- a/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java @@ -1,17 +1,17 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Status of a symbol on the exchange. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum SymbolStatus { - PRE_TRADING, - TRADING, - POST_TRADING, - END_OF_DAY, - HALT, - AUCTION_MATCH, - BREAK; -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a symbol on the exchange. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SymbolStatus { + PRE_TRADING, + TRADING, + POST_TRADING, + END_OF_DAY, + HALT, + AUCTION_MATCH, + BREAK; +} diff --git a/src/main/java/com/binance/api/client/domain/market/AggTrade.java b/src/main/java/com/binance/api/client/domain/market/AggTrade.java old mode 100644 new mode 100755 index 75d8c0d23..65d135af6 --- a/src/main/java/com/binance/api/client/domain/market/AggTrade.java +++ b/src/main/java/com/binance/api/client/domain/market/AggTrade.java @@ -1,103 +1,103 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An aggregated trade event for a symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AggTrade { - - @JsonProperty("a") - private long aggregatedTradeId; - - @JsonProperty("p") - private String price; - - @JsonProperty("q") - private String quantity; - - @JsonProperty("f") - private long firstBreakdownTradeId; - - @JsonProperty("l") - private long lastBreakdownTradeId; - - @JsonProperty("T") - private long tradeTime; - - @JsonProperty("m") - private boolean isBuyerMaker; - - public long getAggregatedTradeId() { - return aggregatedTradeId; - } - - public void setAggregatedTradeId(long aggregatedTradeId) { - this.aggregatedTradeId = aggregatedTradeId; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQuantity() { - return quantity; - } - - public void setQuantity(String quantity) { - this.quantity = quantity; - } - - public long getFirstBreakdownTradeId() { - return firstBreakdownTradeId; - } - - public void setFirstBreakdownTradeId(long firstBreakdownTradeId) { - this.firstBreakdownTradeId = firstBreakdownTradeId; - } - - public long getLastBreakdownTradeId() { - return lastBreakdownTradeId; - } - - public void setLastBreakdownTradeId(long lastBreakdownTradeId) { - this.lastBreakdownTradeId = lastBreakdownTradeId; - } - - public long getTradeTime() { - return tradeTime; - } - - public void setTradeTime(long tradeTime) { - this.tradeTime = tradeTime; - } - - public boolean isBuyerMaker() { - return isBuyerMaker; - } - - public void setBuyerMaker(boolean buyerMaker) { - isBuyerMaker = buyerMaker; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("aggregatedTradeId", aggregatedTradeId) - .append("price", price) - .append("quantity", quantity) - .append("firstBreakdownTradeId", firstBreakdownTradeId) - .append("lastBreakdownTradeId", lastBreakdownTradeId) - .append("tradeTime", tradeTime) - .append("isBuyerMaker", isBuyerMaker) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An aggregated trade event for a symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AggTrade { + + @JsonProperty("a") + private long aggregatedTradeId; + + @JsonProperty("p") + private String price; + + @JsonProperty("q") + private String quantity; + + @JsonProperty("f") + private long firstBreakdownTradeId; + + @JsonProperty("l") + private long lastBreakdownTradeId; + + @JsonProperty("T") + private long tradeTime; + + @JsonProperty("m") + private boolean isBuyerMaker; + + public long getAggregatedTradeId() { + return aggregatedTradeId; + } + + public void setAggregatedTradeId(long aggregatedTradeId) { + this.aggregatedTradeId = aggregatedTradeId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQuantity() { + return quantity; + } + + public void setQuantity(String quantity) { + this.quantity = quantity; + } + + public long getFirstBreakdownTradeId() { + return firstBreakdownTradeId; + } + + public void setFirstBreakdownTradeId(long firstBreakdownTradeId) { + this.firstBreakdownTradeId = firstBreakdownTradeId; + } + + public long getLastBreakdownTradeId() { + return lastBreakdownTradeId; + } + + public void setLastBreakdownTradeId(long lastBreakdownTradeId) { + this.lastBreakdownTradeId = lastBreakdownTradeId; + } + + public long getTradeTime() { + return tradeTime; + } + + public void setTradeTime(long tradeTime) { + this.tradeTime = tradeTime; + } + + public boolean isBuyerMaker() { + return isBuyerMaker; + } + + public void setBuyerMaker(boolean buyerMaker) { + isBuyerMaker = buyerMaker; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("aggregatedTradeId", aggregatedTradeId) + .append("price", price) + .append("quantity", quantity) + .append("firstBreakdownTradeId", firstBreakdownTradeId) + .append("lastBreakdownTradeId", lastBreakdownTradeId) + .append("tradeTime", tradeTime) + .append("isBuyerMaker", isBuyerMaker) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/BookTicker.java b/src/main/java/com/binance/api/client/domain/market/BookTicker.java old mode 100644 new mode 100755 index 67b007ea8..94b5c7989 --- a/src/main/java/com/binance/api/client/domain/market/BookTicker.java +++ b/src/main/java/com/binance/api/client/domain/market/BookTicker.java @@ -1,88 +1,88 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents the best price/qty on the order book for a given symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class BookTicker { - - /** - * Ticker symbol. - */ - private String symbol; - - /** - * Bid price. - */ - private String bidPrice; - - /** - * Bid quantity - */ - private String bidQty; - - /** - * Ask price. - */ - private String askPrice; - - /** - * Ask quantity. - */ - private String askQty; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getBidPrice() { - return bidPrice; - } - - public void setBidPrice(String bidPrice) { - this.bidPrice = bidPrice; - } - - public String getBidQty() { - return bidQty; - } - - public void setBidQty(String bidQty) { - this.bidQty = bidQty; - } - - public String getAskPrice() { - return askPrice; - } - - public void setAskPrice(String askPrice) { - this.askPrice = askPrice; - } - - public String getAskQty() { - return askQty; - } - - public void setAskQty(String askQty) { - this.askQty = askQty; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("bidPrice", bidPrice) - .append("bidQty", bidQty) - .append("askPrice", askPrice) - .append("askQty", askQty) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents the best price/qty on the order book for a given symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class BookTicker { + + /** + * Ticker symbol. + */ + private String symbol; + + /** + * Bid price. + */ + private String bidPrice; + + /** + * Bid quantity + */ + private String bidQty; + + /** + * Ask price. + */ + private String askPrice; + + /** + * Ask quantity. + */ + private String askQty; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getBidPrice() { + return bidPrice; + } + + public void setBidPrice(String bidPrice) { + this.bidPrice = bidPrice; + } + + public String getBidQty() { + return bidQty; + } + + public void setBidQty(String bidQty) { + this.bidQty = bidQty; + } + + public String getAskPrice() { + return askPrice; + } + + public void setAskPrice(String askPrice) { + this.askPrice = askPrice; + } + + public String getAskQty() { + return askQty; + } + + public void setAskQty(String askQty) { + this.askQty = askQty; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("bidPrice", bidPrice) + .append("bidQty", bidQty) + .append("askPrice", askPrice) + .append("askQty", askQty) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/Candlestick.java b/src/main/java/com/binance/api/client/domain/market/Candlestick.java old mode 100644 new mode 100755 index 275f7cd37..acd1718d3 --- a/src/main/java/com/binance/api/client/domain/market/Candlestick.java +++ b/src/main/java/com/binance/api/client/domain/market/Candlestick.java @@ -1,143 +1,143 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Kline/Candlestick bars for a symbol. Klines are uniquely identified by their open time. - */ -@JsonFormat(shape = JsonFormat.Shape.ARRAY) -@JsonPropertyOrder() -@JsonIgnoreProperties(ignoreUnknown = true) -public class Candlestick { - - private Long openTime; - - private String open; - - private String high; - - private String low; - - private String close; - - private String volume; - - private Long closeTime; - - private String quoteAssetVolume; - - private Long numberOfTrades; - - private String takerBuyBaseAssetVolume; - - private String takerBuyQuoteAssetVolume; - - public Long getOpenTime() { - return openTime; - } - - public void setOpenTime(Long openTime) { - this.openTime = openTime; - } - - public String getOpen() { - return open; - } - - public void setOpen(String open) { - this.open = open; - } - - public String getHigh() { - return high; - } - - public void setHigh(String high) { - this.high = high; - } - - public String getLow() { - return low; - } - - public void setLow(String low) { - this.low = low; - } - - public String getClose() { - return close; - } - - public void setClose(String close) { - this.close = close; - } - - public String getVolume() { - return volume; - } - - public void setVolume(String volume) { - this.volume = volume; - } - - public Long getCloseTime() { - return closeTime; - } - - public void setCloseTime(Long closeTime) { - this.closeTime = closeTime; - } - - public String getQuoteAssetVolume() { - return quoteAssetVolume; - } - - public void setQuoteAssetVolume(String quoteAssetVolume) { - this.quoteAssetVolume = quoteAssetVolume; - } - - public Long getNumberOfTrades() { - return numberOfTrades; - } - - public void setNumberOfTrades(Long numberOfTrades) { - this.numberOfTrades = numberOfTrades; - } - - public String getTakerBuyBaseAssetVolume() { - return takerBuyBaseAssetVolume; - } - - public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { - this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; - } - - public String getTakerBuyQuoteAssetVolume() { - return takerBuyQuoteAssetVolume; - } - - public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { - this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("openTime", openTime) - .append("open", open) - .append("high", high) - .append("low", low) - .append("close", close) - .append("volume", volume) - .append("closeTime", closeTime) - .append("quoteAssetVolume", quoteAssetVolume) - .append("numberOfTrades", numberOfTrades) - .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) - .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Kline/Candlestick bars for a symbol. Klines are uniquely identified by their open time. + */ +@JsonFormat(shape = JsonFormat.Shape.ARRAY) +@JsonPropertyOrder() +@JsonIgnoreProperties(ignoreUnknown = true) +public class Candlestick { + + private Long openTime; + + private String open; + + private String high; + + private String low; + + private String close; + + private String volume; + + private Long closeTime; + + private String quoteAssetVolume; + + private Long numberOfTrades; + + private String takerBuyBaseAssetVolume; + + private String takerBuyQuoteAssetVolume; + + public Long getOpenTime() { + return openTime; + } + + public void setOpenTime(Long openTime) { + this.openTime = openTime; + } + + public String getOpen() { + return open; + } + + public void setOpen(String open) { + this.open = open; + } + + public String getHigh() { + return high; + } + + public void setHigh(String high) { + this.high = high; + } + + public String getLow() { + return low; + } + + public void setLow(String low) { + this.low = low; + } + + public String getClose() { + return close; + } + + public void setClose(String close) { + this.close = close; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public Long getCloseTime() { + return closeTime; + } + + public void setCloseTime(Long closeTime) { + this.closeTime = closeTime; + } + + public String getQuoteAssetVolume() { + return quoteAssetVolume; + } + + public void setQuoteAssetVolume(String quoteAssetVolume) { + this.quoteAssetVolume = quoteAssetVolume; + } + + public Long getNumberOfTrades() { + return numberOfTrades; + } + + public void setNumberOfTrades(Long numberOfTrades) { + this.numberOfTrades = numberOfTrades; + } + + public String getTakerBuyBaseAssetVolume() { + return takerBuyBaseAssetVolume; + } + + public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { + this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; + } + + public String getTakerBuyQuoteAssetVolume() { + return takerBuyQuoteAssetVolume; + } + + public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { + this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("openTime", openTime) + .append("open", open) + .append("high", high) + .append("low", low) + .append("close", close) + .append("volume", volume) + .append("closeTime", closeTime) + .append("quoteAssetVolume", quoteAssetVolume) + .append("numberOfTrades", numberOfTrades) + .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) + .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java b/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java old mode 100644 new mode 100755 index b34334977..577287c86 --- a/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java +++ b/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java @@ -1,36 +1,36 @@ -package com.binance.api.client.domain.market; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Kline/Candlestick intervals. - * m -> minutes; h -> hours; d -> days; w -> weeks; M -> months - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum CandlestickInterval { - ONE_MINUTE("1m"), - THREE_MINUTES("3m"), - FIVE_MINUTES("5m"), - FIFTEEN_MINUTES("15m"), - HALF_HOURLY("30m"), - HOURLY("1h"), - TWO_HOURLY("2h"), - FOUR_HOURLY("4h"), - SIX_HOURLY("6h"), - EIGHT_HOURLY("8h"), - TWELVE_HOURLY("12h"), - DAILY("1d"), - THREE_DAILY("3d"), - WEEKLY("1w"), - MONTHLY("1M"); - - private final String intervalId; - - CandlestickInterval(String intervalId) { - this.intervalId = intervalId; - } - - public String getIntervalId() { - return intervalId; - } -} +package com.binance.api.client.domain.market; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Kline/Candlestick intervals. + * m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum CandlestickInterval { + ONE_MINUTE("1m"), + THREE_MINUTES("3m"), + FIVE_MINUTES("5m"), + FIFTEEN_MINUTES("15m"), + HALF_HOURLY("30m"), + HOURLY("1h"), + TWO_HOURLY("2h"), + FOUR_HOURLY("4h"), + SIX_HOURLY("6h"), + EIGHT_HOURLY("8h"), + TWELVE_HOURLY("12h"), + DAILY("1d"), + THREE_DAILY("3d"), + WEEKLY("1w"), + MONTHLY("1M"); + + private final String intervalId; + + CandlestickInterval(String intervalId) { + this.intervalId = intervalId; + } + + public String getIntervalId() { + return intervalId; + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBook.java b/src/main/java/com/binance/api/client/domain/market/OrderBook.java old mode 100644 new mode 100755 index 98ffb10e1..05f78f62f --- a/src/main/java/com/binance/api/client/domain/market/OrderBook.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBook.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Order book of a symbol in Binance. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderBook { - - /** - * Last update id of this order book. - */ - private long lastUpdateId; - - /** - * List of bids (price/qty). - */ - private List bids; - - /** - * List of asks (price/qty). - */ - private List asks; - - public long getLastUpdateId() { - return lastUpdateId; - } - - public void setLastUpdateId(long lastUpdateId) { - this.lastUpdateId = lastUpdateId; - } - - public List getBids() { - return bids; - } - - public void setBids(List bids) { - this.bids = bids; - } - - public List getAsks() { - return asks; - } - - public void setAsks(List asks) { - this.asks = asks; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("lastUpdateId", lastUpdateId) - .append("bids", bids) - .append("asks", asks) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Order book of a symbol in Binance. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderBook { + + /** + * Last update id of this order book. + */ + private long lastUpdateId; + + /** + * List of bids (price/qty). + */ + private List bids; + + /** + * List of asks (price/qty). + */ + private List asks; + + public long getLastUpdateId() { + return lastUpdateId; + } + + public void setLastUpdateId(long lastUpdateId) { + this.lastUpdateId = lastUpdateId; + } + + public List getBids() { + return bids; + } + + public void setBids(List bids) { + this.bids = bids; + } + + public List getAsks() { + return asks; + } + + public void setAsks(List asks) { + this.asks = asks; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("lastUpdateId", lastUpdateId) + .append("bids", bids) + .append("asks", asks) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java b/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java old mode 100644 new mode 100755 index 7d4d2635b..4e2cb65ea --- a/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An order book entry consisting of price and quantity. - */ -@JsonDeserialize(using = OrderBookEntryDeserializer.class) -@JsonSerialize(using = OrderBookEntrySerializer.class) -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderBookEntry { - - private String price; - private String qty; - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQty() { - return qty; - } - - public void setQty(String qty) { - this.qty = qty; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("price", price) - .append("qty", qty) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An order book entry consisting of price and quantity. + */ +@JsonDeserialize(using = OrderBookEntryDeserializer.class) +@JsonSerialize(using = OrderBookEntrySerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderBookEntry { + + private String price; + private String qty; + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQty() { + return qty; + } + + public void setQty(String qty) { + this.qty = qty; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("price", price) + .append("qty", qty) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java b/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java old mode 100644 new mode 100755 index 0d907d37c..4a65e253b --- a/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java @@ -1,29 +1,29 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.domain.market.OrderBookEntry; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; - -/** - * Custom deserializer for an OrderBookEntry, since the API returns an array in the format [ price, qty, [] ]. - */ -public class OrderBookEntryDeserializer extends JsonDeserializer { - - @Override - public OrderBookEntry deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - final String price = node.get(0).asText(); - final String qty = node.get(1).asText(); - - OrderBookEntry orderBookEntry = new OrderBookEntry(); - orderBookEntry.setPrice(price); - orderBookEntry.setQty(qty); - return orderBookEntry; - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.domain.market.OrderBookEntry; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; + +/** + * Custom deserializer for an OrderBookEntry, since the API returns an array in the format [ price, qty, [] ]. + */ +public class OrderBookEntryDeserializer extends JsonDeserializer { + + @Override + public OrderBookEntry deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + final String price = node.get(0).asText(); + final String qty = node.get(1).asText(); + + OrderBookEntry orderBookEntry = new OrderBookEntry(); + orderBookEntry.setPrice(price); + orderBookEntry.setQty(qty); + return orderBookEntry; + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java b/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java old mode 100644 new mode 100755 index 937892d76..132f8914a --- a/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java @@ -1,21 +1,21 @@ -package com.binance.api.client.domain.market; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.JsonSerializer; - -import java.io.IOException; - -/** - * Custom serializer for an OrderBookEntry. - */ -public class OrderBookEntrySerializer extends JsonSerializer { - - @Override - public void serialize(OrderBookEntry orderBookEntry, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartArray(); - gen.writeString(orderBookEntry.getPrice()); - gen.writeString(orderBookEntry.getQty()); - gen.writeEndArray(); - } -} +package com.binance.api.client.domain.market; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.JsonSerializer; + +import java.io.IOException; + +/** + * Custom serializer for an OrderBookEntry. + */ +public class OrderBookEntrySerializer extends JsonSerializer { + + @Override + public void serialize(OrderBookEntry orderBookEntry, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartArray(); + gen.writeString(orderBookEntry.getPrice()); + gen.writeString(orderBookEntry.getQty()); + gen.writeEndArray(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/TickerPrice.java b/src/main/java/com/binance/api/client/domain/market/TickerPrice.java old mode 100644 new mode 100755 index 2c7a036ac..598893c6d --- a/src/main/java/com/binance/api/client/domain/market/TickerPrice.java +++ b/src/main/java/com/binance/api/client/domain/market/TickerPrice.java @@ -1,46 +1,46 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Wraps a symbol and its corresponding latest price. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class TickerPrice { - - /** - * Ticker symbol. - */ - private String symbol; - - /** - * Latest price. - */ - private String price; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("price", price) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Wraps a symbol and its corresponding latest price. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TickerPrice { + + /** + * Ticker symbol. + */ + private String symbol; + + /** + * Latest price. + */ + private String price; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("price", price) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java b/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java old mode 100644 new mode 100755 index c23069de0..7cd3a08ca --- a/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java +++ b/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java @@ -1,256 +1,256 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * 24 hour price change statistics for a ticker. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class TickerStatistics { - - /** - * Ticker symbol. - */ - private String symbol; - - /** - * Price change during the last 24 hours. - */ - private String priceChange; - - /** - * Price change, in percentage, during the last 24 hours. - */ - private String priceChangePercent; - - /** - * Weighted average price. - */ - private String weightedAvgPrice; - - /** - * Previous close price. - */ - private String prevClosePrice; - - /** - * Last price. - */ - private String lastPrice; - - /** - * Bid price. - */ - private String bidPrice; - - /** - * Ask price. - */ - private String askPrice; - - /** - * Open price 24 hours ago. - */ - private String openPrice; - - /** - * Highest price during the past 24 hours. - */ - private String highPrice; - - /** - * Lowest price during the past 24 hours. - */ - private String lowPrice; - - /** - * Total volume during the past 24 hours. - */ - private String volume; - - /** - * Open time. - */ - private long openTime; - - /** - * Close time. - */ - private long closeTime; - - /** - * First trade id. - */ - private long firstId; - - /** - * Last trade id. - */ - private long lastId; - - /** - * Total number of trades during the last 24 hours. - */ - private long count; - - public String getPriceChange() { - return priceChange; - } - - public void setPriceChange(String priceChange) { - this.priceChange = priceChange; - } - - public String getPriceChangePercent() { - return priceChangePercent; - } - - public void setPriceChangePercent(String priceChangePercent) { - this.priceChangePercent = priceChangePercent; - } - - public String getWeightedAvgPrice() { - return weightedAvgPrice; - } - - public void setWeightedAvgPrice(String weightedAvgPrice) { - this.weightedAvgPrice = weightedAvgPrice; - } - - public String getPrevClosePrice() { - return prevClosePrice; - } - - public void setPrevClosePrice(String prevClosePrice) { - this.prevClosePrice = prevClosePrice; - } - - public String getLastPrice() { - return lastPrice; - } - - public void setLastPrice(String lastPrice) { - this.lastPrice = lastPrice; - } - - public String getBidPrice() { - return bidPrice; - } - - public void setBidPrice(String bidPrice) { - this.bidPrice = bidPrice; - } - - public String getAskPrice() { - return askPrice; - } - - public void setAskPrice(String askPrice) { - this.askPrice = askPrice; - } - - public String getOpenPrice() { - return openPrice; - } - - public void setOpenPrice(String openPrice) { - this.openPrice = openPrice; - } - - public String getHighPrice() { - return highPrice; - } - - public void setHighPrice(String highPrice) { - this.highPrice = highPrice; - } - - public String getLowPrice() { - return lowPrice; - } - - public void setLowPrice(String lowPrice) { - this.lowPrice = lowPrice; - } - - public String getVolume() { - return volume; - } - - public void setVolume(String volume) { - this.volume = volume; - } - - public long getOpenTime() { - return openTime; - } - - public void setOpenTime(long openTime) { - this.openTime = openTime; - } - - public long getCloseTime() { - return closeTime; - } - - public void setCloseTime(long closeTime) { - this.closeTime = closeTime; - } - - public long getFirstId() { - return firstId; - } - - public void setFirstId(long firstId) { - this.firstId = firstId; - } - - public long getLastId() { - return lastId; - } - - public void setLastId(long lastId) { - this.lastId = lastId; - } - - public long getCount() { - return count; - } - - public void setCount(long count) { - this.count = count; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("priceChange", priceChange) - .append("priceChangePercent", priceChangePercent) - .append("weightedAvgPrice", weightedAvgPrice) - .append("prevClosePrice", prevClosePrice) - .append("lastPrice", lastPrice) - .append("bidPrice", bidPrice) - .append("askPrice", askPrice) - .append("openPrice", openPrice) - .append("highPrice", highPrice) - .append("lowPrice", lowPrice) - .append("volume", volume) - .append("openTime", openTime) - .append("closeTime", closeTime) - .append("firstId", firstId) - .append("lastId", lastId) - .append("count", count) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * 24 hour price change statistics for a ticker. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TickerStatistics { + + /** + * Ticker symbol. + */ + private String symbol; + + /** + * Price change during the last 24 hours. + */ + private String priceChange; + + /** + * Price change, in percentage, during the last 24 hours. + */ + private String priceChangePercent; + + /** + * Weighted average price. + */ + private String weightedAvgPrice; + + /** + * Previous close price. + */ + private String prevClosePrice; + + /** + * Last price. + */ + private String lastPrice; + + /** + * Bid price. + */ + private String bidPrice; + + /** + * Ask price. + */ + private String askPrice; + + /** + * Open price 24 hours ago. + */ + private String openPrice; + + /** + * Highest price during the past 24 hours. + */ + private String highPrice; + + /** + * Lowest price during the past 24 hours. + */ + private String lowPrice; + + /** + * Total volume during the past 24 hours. + */ + private String volume; + + /** + * Open time. + */ + private long openTime; + + /** + * Close time. + */ + private long closeTime; + + /** + * First trade id. + */ + private long firstId; + + /** + * Last trade id. + */ + private long lastId; + + /** + * Total number of trades during the last 24 hours. + */ + private long count; + + public String getPriceChange() { + return priceChange; + } + + public void setPriceChange(String priceChange) { + this.priceChange = priceChange; + } + + public String getPriceChangePercent() { + return priceChangePercent; + } + + public void setPriceChangePercent(String priceChangePercent) { + this.priceChangePercent = priceChangePercent; + } + + public String getWeightedAvgPrice() { + return weightedAvgPrice; + } + + public void setWeightedAvgPrice(String weightedAvgPrice) { + this.weightedAvgPrice = weightedAvgPrice; + } + + public String getPrevClosePrice() { + return prevClosePrice; + } + + public void setPrevClosePrice(String prevClosePrice) { + this.prevClosePrice = prevClosePrice; + } + + public String getLastPrice() { + return lastPrice; + } + + public void setLastPrice(String lastPrice) { + this.lastPrice = lastPrice; + } + + public String getBidPrice() { + return bidPrice; + } + + public void setBidPrice(String bidPrice) { + this.bidPrice = bidPrice; + } + + public String getAskPrice() { + return askPrice; + } + + public void setAskPrice(String askPrice) { + this.askPrice = askPrice; + } + + public String getOpenPrice() { + return openPrice; + } + + public void setOpenPrice(String openPrice) { + this.openPrice = openPrice; + } + + public String getHighPrice() { + return highPrice; + } + + public void setHighPrice(String highPrice) { + this.highPrice = highPrice; + } + + public String getLowPrice() { + return lowPrice; + } + + public void setLowPrice(String lowPrice) { + this.lowPrice = lowPrice; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public long getOpenTime() { + return openTime; + } + + public void setOpenTime(long openTime) { + this.openTime = openTime; + } + + public long getCloseTime() { + return closeTime; + } + + public void setCloseTime(long closeTime) { + this.closeTime = closeTime; + } + + public long getFirstId() { + return firstId; + } + + public void setFirstId(long firstId) { + this.firstId = firstId; + } + + public long getLastId() { + return lastId; + } + + public void setLastId(long lastId) { + this.lastId = lastId; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("priceChange", priceChange) + .append("priceChangePercent", priceChangePercent) + .append("weightedAvgPrice", weightedAvgPrice) + .append("prevClosePrice", prevClosePrice) + .append("lastPrice", lastPrice) + .append("bidPrice", bidPrice) + .append("askPrice", askPrice) + .append("openPrice", openPrice) + .append("highPrice", highPrice) + .append("lowPrice", lowPrice) + .append("volume", volume) + .append("openTime", openTime) + .append("closeTime", closeTime) + .append("firstId", firstId) + .append("lastId", lastId) + .append("count", count) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/exception/BinanceApiException.java b/src/main/java/com/binance/api/client/exception/BinanceApiException.java old mode 100644 new mode 100755 index a40d9e7a9..80430fd8d --- a/src/main/java/com/binance/api/client/exception/BinanceApiException.java +++ b/src/main/java/com/binance/api/client/exception/BinanceApiException.java @@ -1,74 +1,74 @@ -package com.binance.api.client.exception; - -import com.binance.api.client.BinanceApiError; - -/** - * An exception which can occur while invoking methods of the Binance API. - */ -public class BinanceApiException extends RuntimeException { - - private static final long serialVersionUID = 3788669840036201041L; -/** - * Error response object returned by Binance API. - */ - private BinanceApiError error; - - /** - * Instantiates a new binance api exception. - * - * @param error an error response object - */ - public BinanceApiException(BinanceApiError error) { - this.error = error; - } - - /** - * Instantiates a new binance api exception. - */ - public BinanceApiException() { - super(); - } - - /** - * Instantiates a new binance api exception. - * - * @param message the message - */ - public BinanceApiException(String message) { - super(message); - } - - /** - * Instantiates a new binance api exception. - * - * @param cause the cause - */ - public BinanceApiException(Throwable cause) { - super(cause); - } - - /** - * Instantiates a new binance api exception. - * - * @param message the message - * @param cause the cause - */ - public BinanceApiException(String message, Throwable cause) { - super(message, cause); - } - - /** - * @return the response error object from Binance API, or null if no response object was returned (e.g. server returned 500). - */ - public BinanceApiError getError() { - return error; - } - - @Override - public String getMessage() { - if (error != null) { - return error.getMsg(); - } - return super.getMessage(); - } -} +package com.binance.api.client.exception; + +import com.binance.api.client.BinanceApiError; + +/** + * An exception which can occur while invoking methods of the Binance API. + */ +public class BinanceApiException extends RuntimeException { + + private static final long serialVersionUID = 3788669840036201041L; +/** + * Error response object returned by Binance API. + */ + private BinanceApiError error; + + /** + * Instantiates a new binance api exception. + * + * @param error an error response object + */ + public BinanceApiException(BinanceApiError error) { + this.error = error; + } + + /** + * Instantiates a new binance api exception. + */ + public BinanceApiException() { + super(); + } + + /** + * Instantiates a new binance api exception. + * + * @param message the message + */ + public BinanceApiException(String message) { + super(message); + } + + /** + * Instantiates a new binance api exception. + * + * @param cause the cause + */ + public BinanceApiException(Throwable cause) { + super(cause); + } + + /** + * Instantiates a new binance api exception. + * + * @param message the message + * @param cause the cause + */ + public BinanceApiException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @return the response error object from Binance API, or null if no response object was returned (e.g. server returned 500). + */ + public BinanceApiError getError() { + return error; + } + + @Override + public String getMessage() { + if (error != null) { + return error.getMsg(); + } + return super.getMessage(); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java new file mode 100755 index 000000000..4514bd314 --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java @@ -0,0 +1,103 @@ +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiAsyncMarginRestClient; +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; + +/** + * Implementation of Binance's Margin REST API using Retrofit with asynchronous/non-blocking method calls. + */ +public class BinanceApiAsyncMarginRestClientImpl implements BinanceApiAsyncMarginRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiAsyncMarginRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + // Margin Account endpoints + + @Override + public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { + binanceApiService.getMarginAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAccount(BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { + binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), + orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void newOrder(NewOrder order, BinanceApiCallback callback) { + binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { + binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { + binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getMyTrades(String symbol, BinanceApiCallback> callback) { + binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // user stream endpoints + + @Override + public void startUserDataStream(BinanceApiCallback callback) { + binanceApiService.startMarginUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { + binanceApiService.keepAliveMarginUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void transfer(String asset, String amount, TransferType type, BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void borrow(String asset, String amount, BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void repay(String asset, String amount, BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.repay(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java old mode 100644 new mode 100755 index 97f02148c..c41cba73a --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -1,242 +1,242 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.event.ListenKey; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.ServerTime; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; - -/** - * Implementation of Binance's REST API using Retrofit with asynchronous/non-blocking method calls. - */ -public class BinanceApiAsyncRestClientImpl implements BinanceApiAsyncRestClient { - - private final BinanceApiService binanceApiService; - - public BinanceApiAsyncRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - // General endpoints - - @Override - public void ping(BinanceApiCallback callback) { - binanceApiService.ping().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getServerTime(BinanceApiCallback callback) { - binanceApiService.getServerTime().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getExchangeInfo(BinanceApiCallback callback) { - binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAllAssets(BinanceApiCallback> callback) { - binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html") - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // Market Data endpoints - - @Override - public void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback) { - binanceApiService.getOrderBook(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getTrades(String symbol, Integer limit, BinanceApiCallback> callback) { - binanceApiService.getTrades(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback) { - binanceApiService.getHistoricalTrades(symbol, limit, fromId).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { - binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAggTrades(String symbol, BinanceApiCallback> callback) { - getAggTrades(symbol, null, null, null, null, callback); - } - - @Override - public void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { - binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback) { - getCandlestickBars(symbol, interval, null, null, null, callback); - } - - @Override - public void get24HrPriceStatistics(String symbol, BinanceApiCallback callback) { - binanceApiService.get24HrPriceStatistics(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAll24HrPriceStatistics(BinanceApiCallback> callback) { - binanceApiService.getAll24HrPriceStatistics().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAllPrices(BinanceApiCallback> callback) { - binanceApiService.getLatestPrices().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getPrice(String symbol , BinanceApiCallback callback) { - binanceApiService.getLatestPrice(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getBookTickers(BinanceApiCallback> callback) { - binanceApiService.getBookTickers().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void newOrder(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void newOrderTest(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // Account endpoints - - @Override - public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { - binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { - binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { - binanceApiService.getOpenOrders(orderRequest.getSymbol(), - orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback) { - binanceApiService.getAllOrders(orderRequest.getSymbol(), - orderRequest.getOrderId(), orderRequest.getLimit(), - orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { - binanceApiService.getAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAccount(BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback) { - binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback) { - getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); - } - - @Override - public void getMyTrades(String symbol, BinanceApiCallback> callback) { - getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); - } - - @Override - public void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback) { - binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getDepositHistory(String asset, BinanceApiCallback callback) { - binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getWithdrawHistory(String asset, BinanceApiCallback callback) { - binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getDepositAddress(String asset, BinanceApiCallback callback) { - binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // User stream endpoints - - @Override - public void startUserDataStream(BinanceApiCallback callback) { - binanceApiService.startUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { - binanceApiService.keepAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void closeUserDataStream(String listenKey, BinanceApiCallback callback) { - binanceApiService.closeAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; + +/** + * Implementation of Binance's REST API using Retrofit with asynchronous/non-blocking method calls. + */ +public class BinanceApiAsyncRestClientImpl implements BinanceApiAsyncRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiAsyncRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + // General endpoints + + @Override + public void ping(BinanceApiCallback callback) { + binanceApiService.ping().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getServerTime(BinanceApiCallback callback) { + binanceApiService.getServerTime().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getExchangeInfo(BinanceApiCallback callback) { + binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAllAssets(BinanceApiCallback> callback) { + binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html") + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // Market Data endpoints + + @Override + public void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback) { + binanceApiService.getOrderBook(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getTrades(String symbol, Integer limit, BinanceApiCallback> callback) { + binanceApiService.getTrades(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback) { + binanceApiService.getHistoricalTrades(symbol, limit, fromId).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { + binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAggTrades(String symbol, BinanceApiCallback> callback) { + getAggTrades(symbol, null, null, null, null, callback); + } + + @Override + public void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { + binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback) { + getCandlestickBars(symbol, interval, null, null, null, callback); + } + + @Override + public void get24HrPriceStatistics(String symbol, BinanceApiCallback callback) { + binanceApiService.get24HrPriceStatistics(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAll24HrPriceStatistics(BinanceApiCallback> callback) { + binanceApiService.getAll24HrPriceStatistics().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAllPrices(BinanceApiCallback> callback) { + binanceApiService.getLatestPrices().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getPrice(String symbol , BinanceApiCallback callback) { + binanceApiService.getLatestPrice(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getBookTickers(BinanceApiCallback> callback) { + binanceApiService.getBookTickers().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void newOrder(NewOrder order, BinanceApiCallback callback) { + binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void newOrderTest(NewOrder order, BinanceApiCallback callback) { + binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // Account endpoints + + @Override + public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { + binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { + binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { + binanceApiService.getOpenOrders(orderRequest.getSymbol(), + orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback) { + binanceApiService.getAllOrders(orderRequest.getSymbol(), + orderRequest.getOrderId(), orderRequest.getLimit(), + orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { + binanceApiService.getAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAccount(BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback) { + binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback) { + getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); + } + + @Override + public void getMyTrades(String symbol, BinanceApiCallback> callback) { + getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); + } + + @Override + public void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback) { + binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getDepositHistory(String asset, BinanceApiCallback callback) { + binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getWithdrawHistory(String asset, BinanceApiCallback callback) { + binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getDepositAddress(String asset, BinanceApiCallback callback) { + binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // User stream endpoints + + @Override + public void startUserDataStream(BinanceApiCallback callback) { + binanceApiService.startUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { + binanceApiService.keepAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void closeUserDataStream(String listenKey, BinanceApiCallback callback) { + binanceApiService.closeAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java old mode 100644 new mode 100755 index 10b896ac6..355fa1348 --- a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java @@ -1,51 +1,51 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.BinanceApiError; -import com.binance.api.client.exception.BinanceApiException; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; - -import java.io.IOException; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.getBinanceApiError; - -/** - * An adapter/wrapper which transforms a Callback from Retrofit into a BinanceApiCallback which is exposed to the client. - */ -public class BinanceApiCallbackAdapter implements Callback { - - private final BinanceApiCallback callback; - - public BinanceApiCallbackAdapter(BinanceApiCallback callback) { - this.callback = callback; - } - - public void onResponse(Call call, Response response) { - if (response.isSuccessful()) { - callback.onResponse(response.body()); - } else { - if (response.code() == 504) { - // HTTP 504 return code is used when the API successfully sent the message but not get a response within the timeout period. - // It is important to NOT treat this as a failure; the execution status is UNKNOWN and could have been a success. - return; - } - try { - BinanceApiError apiError = getBinanceApiError(response); - onFailure(call, new BinanceApiException(apiError)); - } catch (IOException e) { - onFailure(call, new BinanceApiException(e)); - } - } - } - - @Override - public void onFailure(Call call, Throwable throwable) { - if (throwable instanceof BinanceApiException) { - callback.onFailure(throwable); - } else { - callback.onFailure(new BinanceApiException(throwable)); - } - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiError; +import com.binance.api.client.exception.BinanceApiException; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +import java.io.IOException; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.getBinanceApiError; + +/** + * An adapter/wrapper which transforms a Callback from Retrofit into a BinanceApiCallback which is exposed to the client. + */ +public class BinanceApiCallbackAdapter implements Callback { + + private final BinanceApiCallback callback; + + public BinanceApiCallbackAdapter(BinanceApiCallback callback) { + this.callback = callback; + } + + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + callback.onResponse(response.body()); + } else { + if (response.code() == 504) { + // HTTP 504 return code is used when the API successfully sent the message but not get a response within the timeout period. + // It is important to NOT treat this as a failure; the execution status is UNKNOWN and could have been a success. + return; + } + try { + BinanceApiError apiError = getBinanceApiError(response); + onFailure(call, new BinanceApiException(apiError)); + } catch (IOException e) { + onFailure(call, new BinanceApiException(e)); + } + } + } + + @Override + public void onFailure(Call call, Throwable throwable) { + if (throwable instanceof BinanceApiException) { + callback.onFailure(throwable); + } else { + callback.onFailure(new BinanceApiException(throwable)); + } + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java new file mode 100755 index 000000000..93bf3244d --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -0,0 +1,101 @@ +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; + +/** + * Implementation of Binance's Margin REST API using Retrofit with asynchronous/non-blocking method calls. + */ +public class BinanceApiMarginRestClientImpl implements BinanceApiMarginRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiMarginRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + @Override + public MarginAccount getAccount() { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } + + @Override + public List getOpenOrders(OrderRequest orderRequest) { + return executeSync(binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), + orderRequest.getTimestamp())); + } + + @Override + public NewOrderResponse newOrder(NewOrder order) { + return executeSync(binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + } + + @Override + public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { + return executeSync(binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); + } + + @Override + public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { + return executeSync(binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); + } + + @Override + public List getMyTrades(String symbol) { + return executeSync(binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + // user stream endpoints + + @Override + public String startUserDataStream() { + return executeSync(binanceApiService.startMarginUserDataStream()).toString(); + } + + @Override + public void keepAliveUserDataStream(String listenKey) { + executeSync(binanceApiService.keepAliveMarginUserDataStream(listenKey)); + } + + @Override + public MarginTransaction transfer(String asset, String amount, TransferType type) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } + + @Override + public MarginTransaction borrow(String asset, String amount) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } + + @Override + public LoanQueryResult queryLoan(String asset, String txId) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryLoan(asset, txId, timestamp)); + } + + @Override + public MarginTransaction repay(String asset, String amount) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.repay(asset, amount, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java old mode 100644 new mode 100755 index aceb3799a..b52fccd0f --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -1,233 +1,233 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; -import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; - -/** - * Implementation of Binance's REST API using Retrofit with synchronous/blocking method calls. - */ -public class BinanceApiRestClientImpl implements BinanceApiRestClient { - - private final BinanceApiService binanceApiService; - - public BinanceApiRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - // General endpoints - - @Override - public void ping() { - executeSync(binanceApiService.ping()); - } - - @Override - public Long getServerTime() { - return executeSync(binanceApiService.getServerTime()).getServerTime(); - } - - @Override - public ExchangeInfo getExchangeInfo() { - return executeSync(binanceApiService.getExchangeInfo()); - } - - @Override - public List getAllAssets() { - return executeSync(binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html")); - } - - // Market Data endpoints - - @Override - public OrderBook getOrderBook(String symbol, Integer limit) { - return executeSync(binanceApiService.getOrderBook(symbol, limit)); - } - - @Override - public List getTrades(String symbol, Integer limit) { - return executeSync(binanceApiService.getTrades(symbol, limit)); - } - - @Override - public List getHistoricalTrades(String symbol, Integer limit, Long fromId) { - return executeSync(binanceApiService.getHistoricalTrades(symbol, limit, fromId)); - } - - @Override - public List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime) { - return executeSync(binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime)); - } - - @Override - public List getAggTrades(String symbol) { - return getAggTrades(symbol, null, null, null, null); - } - - @Override - public List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime) { - return executeSync(binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime)); - } - - @Override - public List getCandlestickBars(String symbol, CandlestickInterval interval) { - return getCandlestickBars(symbol, interval, null, null, null); - } - - @Override - public TickerStatistics get24HrPriceStatistics(String symbol) { - return executeSync(binanceApiService.get24HrPriceStatistics(symbol)); - } - - @Override - public List getAll24HrPriceStatistics() { - return executeSync(binanceApiService.getAll24HrPriceStatistics()); - } - - @Override - public TickerPrice getPrice(String symbol) { - return executeSync(binanceApiService.getLatestPrice(symbol)); - } - - @Override - public List getAllPrices() { - return executeSync(binanceApiService.getLatestPrices()); - } - - @Override - public List getBookTickers() { - return executeSync(binanceApiService.getBookTickers()); - } - - @Override - public NewOrderResponse newOrder(NewOrder order) { - return executeSync(binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); - } - - @Override - public void newOrderTest(NewOrder order) { - executeSync(binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); - } - - // Account endpoints - - @Override - public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { - return executeSync(binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); - } - - @Override - public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { - return executeSync(binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); - } - - @Override - public List getOpenOrders(OrderRequest orderRequest) { - return executeSync(binanceApiService.getOpenOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), orderRequest.getTimestamp())); - } - - @Override - public List getAllOrders(AllOrdersRequest orderRequest) { - return executeSync(binanceApiService.getAllOrders(orderRequest.getSymbol(), - orderRequest.getOrderId(), orderRequest.getLimit(), - orderRequest.getRecvWindow(), orderRequest.getTimestamp())); - } - - @Override - public Account getAccount(Long recvWindow, Long timestamp) { - return executeSync(binanceApiService.getAccount(recvWindow, timestamp)); - } - - @Override - public Account getAccount() { - return getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp) { - return executeSync(binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp)); - } - - @Override - public List getMyTrades(String symbol, Integer limit) { - return getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public List getMyTrades(String symbol) { - return getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag) { - return executeSync(binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public DepositHistory getDepositHistory(String asset) { - return executeSync(binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public WithdrawHistory getWithdrawHistory(String asset) { - return executeSync(binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public DepositAddress getDepositAddress(String asset) { - return executeSync(binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - // User stream endpoints - - @Override - public String startUserDataStream() { - return executeSync(binanceApiService.startUserDataStream()).toString(); - } - - @Override - public void keepAliveUserDataStream(String listenKey) { - executeSync(binanceApiService.keepAliveUserDataStream(listenKey)); - } - - @Override - public void closeUserDataStream(String listenKey) { - executeSync(binanceApiService.closeAliveUserDataStream(listenKey)); - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; + +/** + * Implementation of Binance's REST API using Retrofit with synchronous/blocking method calls. + */ +public class BinanceApiRestClientImpl implements BinanceApiRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + // General endpoints + + @Override + public void ping() { + executeSync(binanceApiService.ping()); + } + + @Override + public Long getServerTime() { + return executeSync(binanceApiService.getServerTime()).getServerTime(); + } + + @Override + public ExchangeInfo getExchangeInfo() { + return executeSync(binanceApiService.getExchangeInfo()); + } + + @Override + public List getAllAssets() { + return executeSync(binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html")); + } + + // Market Data endpoints + + @Override + public OrderBook getOrderBook(String symbol, Integer limit) { + return executeSync(binanceApiService.getOrderBook(symbol, limit)); + } + + @Override + public List getTrades(String symbol, Integer limit) { + return executeSync(binanceApiService.getTrades(symbol, limit)); + } + + @Override + public List getHistoricalTrades(String symbol, Integer limit, Long fromId) { + return executeSync(binanceApiService.getHistoricalTrades(symbol, limit, fromId)); + } + + @Override + public List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime) { + return executeSync(binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime)); + } + + @Override + public List getAggTrades(String symbol) { + return getAggTrades(symbol, null, null, null, null); + } + + @Override + public List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime) { + return executeSync(binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime)); + } + + @Override + public List getCandlestickBars(String symbol, CandlestickInterval interval) { + return getCandlestickBars(symbol, interval, null, null, null); + } + + @Override + public TickerStatistics get24HrPriceStatistics(String symbol) { + return executeSync(binanceApiService.get24HrPriceStatistics(symbol)); + } + + @Override + public List getAll24HrPriceStatistics() { + return executeSync(binanceApiService.getAll24HrPriceStatistics()); + } + + @Override + public TickerPrice getPrice(String symbol) { + return executeSync(binanceApiService.getLatestPrice(symbol)); + } + + @Override + public List getAllPrices() { + return executeSync(binanceApiService.getLatestPrices()); + } + + @Override + public List getBookTickers() { + return executeSync(binanceApiService.getBookTickers()); + } + + @Override + public NewOrderResponse newOrder(NewOrder order) { + return executeSync(binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + } + + @Override + public void newOrderTest(NewOrder order) { + executeSync(binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + } + + // Account endpoints + + @Override + public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { + return executeSync(binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); + } + + @Override + public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { + return executeSync(binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); + } + + @Override + public List getOpenOrders(OrderRequest orderRequest) { + return executeSync(binanceApiService.getOpenOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), orderRequest.getTimestamp())); + } + + @Override + public List getAllOrders(AllOrdersRequest orderRequest) { + return executeSync(binanceApiService.getAllOrders(orderRequest.getSymbol(), + orderRequest.getOrderId(), orderRequest.getLimit(), + orderRequest.getRecvWindow(), orderRequest.getTimestamp())); + } + + @Override + public Account getAccount(Long recvWindow, Long timestamp) { + return executeSync(binanceApiService.getAccount(recvWindow, timestamp)); + } + + @Override + public Account getAccount() { + return getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); + } + + @Override + public List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp) { + return executeSync(binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp)); + } + + @Override + public List getMyTrades(String symbol, Integer limit) { + return getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); + } + + @Override + public List getMyTrades(String symbol) { + return getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); + } + + @Override + public WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag) { + return executeSync(binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + @Override + public DepositHistory getDepositHistory(String asset) { + return executeSync(binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + @Override + public WithdrawHistory getWithdrawHistory(String asset) { + return executeSync(binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + @Override + public DepositAddress getDepositAddress(String asset) { + return executeSync(binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + // User stream endpoints + + @Override + public String startUserDataStream() { + return executeSync(binanceApiService.startUserDataStream()).toString(); + } + + @Override + public void keepAliveUserDataStream(String listenKey) { + executeSync(binanceApiService.keepAliveUserDataStream(listenKey)); + } + + @Override + public void closeUserDataStream(String listenKey) { + executeSync(binanceApiService.closeAliveUserDataStream(listenKey)); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java old mode 100644 new mode 100755 index 9643c8e90..7ee0513f3 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -1,172 +1,221 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.NewOrderResponseType; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.event.ListenKey; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.ServerTime; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; -import retrofit2.Call; -import retrofit2.http.DELETE; -import retrofit2.http.GET; -import retrofit2.http.Headers; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Query; -import retrofit2.http.Url; - -import java.util.List; - -/** - * Binance's REST API URL mappings and endpoint security configuration. - */ -public interface BinanceApiService { - - // General endpoints - - @GET("/api/v1/ping") - Call ping(); - - @GET("/api/v1/time") - Call getServerTime(); - - @GET("/api/v1/exchangeInfo") - Call getExchangeInfo(); - - @GET - Call> getAllAssets(@Url String url); - - // Market data endpoints - - @GET("/api/v1/depth") - Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); - - @GET("/api/v1/trades") - Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @GET("/api/v1/historicalTrades") - Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); - - @GET("/api/v1/aggTrades") - Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); - - @GET("/api/v1/klines") - Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); - - @GET("/api/v1/ticker/24hr") - Call get24HrPriceStatistics(@Query("symbol") String symbol); - - @GET("/api/v1/ticker/24hr") - Call> getAll24HrPriceStatistics(); - - @GET("/api/v1/ticker/allPrices") - Call> getLatestPrices(); - - @GET("/api/v3/ticker/price") - Call getLatestPrice(@Query("symbol") String symbol); - - @GET("/api/v1/ticker/allBookTickers") - Call> getBookTickers(); - - // Account endpoints - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order") - Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order/test") - Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/order") - Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, - @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @DELETE("/api/v3/order") - Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/openOrders") - Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/allOrders") - Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/account") - Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/myTrades") - Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/wapi/v3/withdraw.html") - Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositHistory.html") - Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/withdrawHistory.html") - Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositAddress.html") - Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - // User stream endpoints - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @POST("/api/v1/userDataStream") - Call startUserDataStream(); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @PUT("/api/v1/userDataStream") - Call keepAliveUserDataStream(@Query("listenKey") String listenKey); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @DELETE("/api/v1/userDataStream") - Call closeAliveUserDataStream(@Query("listenKey") String listenKey); -} +package com.binance.api.client.impl; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.event.ListenKey; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; +import retrofit2.Call; +import retrofit2.http.DELETE; +import retrofit2.http.GET; +import retrofit2.http.Headers; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; + +import java.util.List; + +/** + * Binance's REST API URL mappings and endpoint security configuration. + */ +public interface BinanceApiService { + + // General endpoints + + @GET("/api/v1/ping") + Call ping(); + + @GET("/api/v1/time") + Call getServerTime(); + + @GET("/api/v1/exchangeInfo") + Call getExchangeInfo(); + + @GET + Call> getAllAssets(@Url String url); + + // Market data endpoints + + @GET("/api/v1/depth") + Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); + + @GET("/api/v1/trades") + Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @GET("/api/v1/historicalTrades") + Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); + + @GET("/api/v1/aggTrades") + Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); + + @GET("/api/v1/klines") + Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); + + @GET("/api/v1/ticker/24hr") + Call get24HrPriceStatistics(@Query("symbol") String symbol); + + @GET("/api/v1/ticker/24hr") + Call> getAll24HrPriceStatistics(); + + @GET("/api/v1/ticker/allPrices") + Call> getLatestPrices(); + + @GET("/api/v3/ticker/price") + Call getLatestPrice(@Query("symbol") String symbol); + + @GET("/api/v1/ticker/allBookTickers") + Call> getBookTickers(); + + // Account endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order") + Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order/test") + Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/order") + Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/api/v3/order") + Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/openOrders") + Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/allOrders") + Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/account") + Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/myTrades") + Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/wapi/v3/withdraw.html") + Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositHistory.html") + Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/withdrawHistory.html") + Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositAddress.html") + Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + // User stream endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/api/v1/userDataStream") + Call startUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/api/v1/userDataStream") + Call keepAliveUserDataStream(@Query("listenKey") String listenKey); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @DELETE("/api/v1/userDataStream") + Call closeAliveUserDataStream(@Query("listenKey") String listenKey); + + // Margin Account endpoints + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/transfer") + Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/loan") + Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/loan") + Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/repay") + Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/account") + Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/openOrders") + Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/margin/order") + Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/sapi/v1/margin/order") + Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/order") + Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/myTrades") + Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/sapi/v1/userDataStream") + Call startMarginUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/sapi/v1/userDataStream") + Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java old mode 100644 new mode 100755 index 8307f48b9..40acec7d2 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -1,97 +1,97 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiError; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.exception.BinanceApiException; -import com.binance.api.client.security.AuthenticationInterceptor; -import okhttp3.Dispatcher; -import okhttp3.OkHttpClient; -import okhttp3.RequestBody; -import okhttp3.ResponseBody; -import org.apache.commons.lang3.StringUtils; -import retrofit2.Call; -import retrofit2.Converter; -import retrofit2.Response; -import retrofit2.Retrofit; -import retrofit2.converter.jackson.JacksonConverterFactory; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.concurrent.TimeUnit; - -/** - * Generates a Binance API implementation based on @see {@link BinanceApiService}. - */ -public class BinanceApiServiceGenerator { - - private static final OkHttpClient sharedClient; - private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); - - static { - Dispatcher dispatcher = new Dispatcher(); - dispatcher.setMaxRequestsPerHost(500); - dispatcher.setMaxRequests(500); - sharedClient = new OkHttpClient.Builder() - .dispatcher(dispatcher) - .pingInterval(20, TimeUnit.SECONDS) - .build(); - } - - @SuppressWarnings("unchecked") - private static final Converter errorBodyConverter = - (Converter)converterFactory.responseBodyConverter( - BinanceApiError.class, new Annotation[0], null); - - public static S createService(Class serviceClass) { - return createService(serviceClass, null, null); - } - - public static S createService(Class serviceClass, String apiKey, String secret) { - Retrofit.Builder retrofitBuilder = new Retrofit.Builder() - .baseUrl(BinanceApiConstants.API_BASE_URL) - .addConverterFactory(converterFactory); - - if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { - retrofitBuilder.client(sharedClient); - } else { - // `adaptedClient` will use its own interceptor, but share thread pool etc with the 'parent' client - AuthenticationInterceptor interceptor = new AuthenticationInterceptor(apiKey, secret); - OkHttpClient adaptedClient = sharedClient.newBuilder().addInterceptor(interceptor).build(); - retrofitBuilder.client(adaptedClient); - } - - Retrofit retrofit = retrofitBuilder.build(); - return retrofit.create(serviceClass); - } - - /** - * Execute a REST call and block until the response is received. - */ - public static T executeSync(Call call) { - try { - Response response = call.execute(); - if (response.isSuccessful()) { - return response.body(); - } else { - BinanceApiError apiError = getBinanceApiError(response); - throw new BinanceApiException(apiError); - } - } catch (IOException e) { - throw new BinanceApiException(e); - } - } - - /** - * Extracts and converts the response error body into an object. - */ - public static BinanceApiError getBinanceApiError(Response response) throws IOException, BinanceApiException { - return errorBodyConverter.convert(response.errorBody()); - } - - /** - * Returns the shared OkHttpClient instance. - */ - public static OkHttpClient getSharedClient() { - return sharedClient; - } +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiError; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.exception.BinanceApiException; +import com.binance.api.client.security.AuthenticationInterceptor; +import okhttp3.Dispatcher; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import org.apache.commons.lang3.StringUtils; +import retrofit2.Call; +import retrofit2.Converter; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.jackson.JacksonConverterFactory; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.util.concurrent.TimeUnit; + +/** + * Generates a Binance API implementation based on @see {@link BinanceApiService}. + */ +public class BinanceApiServiceGenerator { + + private static final OkHttpClient sharedClient; + private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); + + static { + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequestsPerHost(500); + dispatcher.setMaxRequests(500); + sharedClient = new OkHttpClient.Builder() + .dispatcher(dispatcher) + .pingInterval(20, TimeUnit.SECONDS) + .build(); + } + + @SuppressWarnings("unchecked") + private static final Converter errorBodyConverter = + (Converter)converterFactory.responseBodyConverter( + BinanceApiError.class, new Annotation[0], null); + + public static S createService(Class serviceClass) { + return createService(serviceClass, null, null); + } + + public static S createService(Class serviceClass, String apiKey, String secret) { + Retrofit.Builder retrofitBuilder = new Retrofit.Builder() + .baseUrl(BinanceApiConstants.API_BASE_URL) + .addConverterFactory(converterFactory); + + if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { + retrofitBuilder.client(sharedClient); + } else { + // `adaptedClient` will use its own interceptor, but share thread pool etc with the 'parent' client + AuthenticationInterceptor interceptor = new AuthenticationInterceptor(apiKey, secret); + OkHttpClient adaptedClient = sharedClient.newBuilder().addInterceptor(interceptor).build(); + retrofitBuilder.client(adaptedClient); + } + + Retrofit retrofit = retrofitBuilder.build(); + return retrofit.create(serviceClass); + } + + /** + * Execute a REST call and block until the response is received. + */ + public static T executeSync(Call call) { + try { + Response response = call.execute(); + if (response.isSuccessful()) { + return response.body(); + } else { + BinanceApiError apiError = getBinanceApiError(response); + throw new BinanceApiException(apiError); + } + } catch (IOException e) { + throw new BinanceApiException(e); + } + } + + /** + * Extracts and converts the response error body into an object. + */ + public static BinanceApiError getBinanceApiError(Response response) throws IOException, BinanceApiException { + return errorBodyConverter.convert(response.errorBody()); + } + + /** + * Returns the shared OkHttpClient instance. + */ + public static OkHttpClient getSharedClient() { + return sharedClient; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java old mode 100644 new mode 100755 index b9e530b0a..6583bae5f --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -1,86 +1,86 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.event.AggTradeEvent; -import com.binance.api.client.domain.event.AllMarketTickersEvent; -import com.binance.api.client.domain.event.CandlestickEvent; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.fasterxml.jackson.core.type.TypeReference; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.WebSocket; - -import java.io.Closeable; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Binance API WebSocket client implementation using OkHttp. - */ -public class BinanceApiWebSocketClientImpl implements BinanceApiWebSocketClient, Closeable { - - private final OkHttpClient client; - - public BinanceApiWebSocketClientImpl(OkHttpClient client) { - this.client = client; - } - - @Override - public Closeable onDepthEvent(String symbols, BinanceApiCallback callback) { - final String channel = Arrays.stream(symbols.split(",")) - .map(String::trim) - .map(s -> String.format("%s@depth", s)) - .collect(Collectors.joining("/")); - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, DepthEvent.class)); - } - - @Override - public Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback) { - final String channel = Arrays.stream(symbols.split(",")) - .map(String::trim) - .map(s -> String.format("%s@kline_%s", s, interval.getIntervalId())) - .collect(Collectors.joining("/")); - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, CandlestickEvent.class)); - } - - public Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback) { - final String channel = Arrays.stream(symbols.split(",")) - .map(String::trim) - .map(s -> String.format("%s@aggTrade", s)) - .collect(Collectors.joining("/")); - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, AggTradeEvent.class)); - } - - public Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback) { - return createNewWebSocket(listenKey, new BinanceApiWebSocketListener<>(callback, UserDataUpdateEvent.class)); - } - - public Closeable onAllMarketTickersEvent(BinanceApiCallback> callback) { - final String channel = "!ticker@arr"; - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() {})); - } - - /** - * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. - */ - @Override - public void close() { } - - private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { - String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); - Request request = new Request.Builder().url(streamingUrl).build(); - final WebSocket webSocket = client.newWebSocket(request, listener); - return () -> { - final int code = 1000; - listener.onClosing(webSocket, code, null); - webSocket.close(code, null); - listener.onClosed(webSocket, code, null); - }; - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.event.AggTradeEvent; +import com.binance.api.client.domain.event.AllMarketTickersEvent; +import com.binance.api.client.domain.event.CandlestickEvent; +import com.binance.api.client.domain.event.DepthEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.fasterxml.jackson.core.type.TypeReference; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.WebSocket; + +import java.io.Closeable; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Binance API WebSocket client implementation using OkHttp. + */ +public class BinanceApiWebSocketClientImpl implements BinanceApiWebSocketClient, Closeable { + + private final OkHttpClient client; + + public BinanceApiWebSocketClientImpl(OkHttpClient client) { + this.client = client; + } + + @Override + public Closeable onDepthEvent(String symbols, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@depth", s)) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, DepthEvent.class)); + } + + @Override + public Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@kline_%s", s, interval.getIntervalId())) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, CandlestickEvent.class)); + } + + public Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@aggTrade", s)) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, AggTradeEvent.class)); + } + + public Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback) { + return createNewWebSocket(listenKey, new BinanceApiWebSocketListener<>(callback, UserDataUpdateEvent.class)); + } + + public Closeable onAllMarketTickersEvent(BinanceApiCallback> callback) { + final String channel = "!ticker@arr"; + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() {})); + } + + /** + * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. + */ + @Override + public void close() { } + + private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { + String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); + Request request = new Request.Builder().url(streamingUrl).build(); + final WebSocket webSocket = client.newWebSocket(request, listener); + return () -> { + final int code = 1000; + listener.onClosing(webSocket, code, null); + webSocket.close(code, null); + listener.onClosed(webSocket, code, null); + }; + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java old mode 100644 new mode 100755 index 8c84dbe3f..e2004090e --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java @@ -1,58 +1,58 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.exception.BinanceApiException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; - -import java.io.IOException; - -/** - * Binance API WebSocket listener. - */ -public class BinanceApiWebSocketListener extends WebSocketListener { - - private BinanceApiCallback callback; - - private static final ObjectMapper mapper = new ObjectMapper(); - - private final ObjectReader objectReader; - - private boolean closing = false; - - public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) { - this.callback = callback; - this.objectReader = mapper.readerFor(eventClass); - } - - public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) { - this.callback = callback; - this.objectReader = mapper.readerFor(eventTypeReference); - } - - @Override - public void onMessage(WebSocket webSocket, String text) { - try { - T event = objectReader.readValue(text); - callback.onResponse(event); - } catch (IOException e) { - throw new BinanceApiException(e); - } - } - - @Override - public void onClosing(final WebSocket webSocket, final int code, final String reason) { - closing = true; - } - - @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { - if (!closing) { - callback.onFailure(t); - } - } +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.exception.BinanceApiException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; + +import java.io.IOException; + +/** + * Binance API WebSocket listener. + */ +public class BinanceApiWebSocketListener extends WebSocketListener { + + private BinanceApiCallback callback; + + private static final ObjectMapper mapper = new ObjectMapper(); + + private final ObjectReader objectReader; + + private boolean closing = false; + + public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) { + this.callback = callback; + this.objectReader = mapper.readerFor(eventClass); + } + + public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) { + this.callback = callback; + this.objectReader = mapper.readerFor(eventTypeReference); + } + + @Override + public void onMessage(WebSocket webSocket, String text) { + try { + T event = objectReader.readValue(text); + callback.onResponse(event); + } catch (IOException e) { + throw new BinanceApiException(e); + } + } + + @Override + public void onClosing(final WebSocket webSocket, final int code, final String reason) { + closing = true; + } + + @Override + public void onFailure(WebSocket webSocket, Throwable t, Response response) { + if (!closing) { + callback.onFailure(t); + } + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java b/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java old mode 100644 new mode 100755 index a2eff2281..197aaabcb --- a/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java +++ b/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java @@ -1,92 +1,92 @@ -package com.binance.api.client.security; - -import com.binance.api.client.constant.BinanceApiConstants; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okio.Buffer; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.util.Objects; - -/** - * A request interceptor that injects the API Key Header into requests, and signs messages, whenever required. - */ -public class AuthenticationInterceptor implements Interceptor { - - private final String apiKey; - - private final String secret; - - public AuthenticationInterceptor(String apiKey, String secret) { - this.apiKey = apiKey; - this.secret = secret; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request original = chain.request(); - Request.Builder newRequestBuilder = original.newBuilder(); - - boolean isApiKeyRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) != null; - boolean isSignatureRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED) != null; - newRequestBuilder.removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) - .removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED); - - // Endpoint requires sending a valid API-KEY - if (isApiKeyRequired || isSignatureRequired) { - newRequestBuilder.addHeader(BinanceApiConstants.API_KEY_HEADER, apiKey); - } - - // Endpoint requires signing the payload - if (isSignatureRequired) { - String payload = original.url().query(); - if (!StringUtils.isEmpty(payload)) { - String signature = HmacSHA256Signer.sign(payload, secret); - HttpUrl signedUrl = original.url().newBuilder().addQueryParameter("signature", signature).build(); - newRequestBuilder.url(signedUrl); - } - } - - // Build new request after adding the necessary authentication information - Request newRequest = newRequestBuilder.build(); - return chain.proceed(newRequest); - } - - /** - * Extracts the request body into a String. - * - * @return request body as a string - */ - @SuppressWarnings("unused") - private static String bodyToString(RequestBody request) { - try (final Buffer buffer = new Buffer()) { - final RequestBody copy = request; - if (copy != null) { - copy.writeTo(buffer); - } else { - return ""; - } - return buffer.readUtf8(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final AuthenticationInterceptor that = (AuthenticationInterceptor) o; - return Objects.equals(apiKey, that.apiKey) && - Objects.equals(secret, that.secret); - } - - @Override - public int hashCode() { - return Objects.hash(apiKey, secret); - } +package com.binance.api.client.security; + +import com.binance.api.client.constant.BinanceApiConstants; +import okhttp3.HttpUrl; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okio.Buffer; +import org.apache.commons.lang3.StringUtils; + +import java.io.IOException; +import java.util.Objects; + +/** + * A request interceptor that injects the API Key Header into requests, and signs messages, whenever required. + */ +public class AuthenticationInterceptor implements Interceptor { + + private final String apiKey; + + private final String secret; + + public AuthenticationInterceptor(String apiKey, String secret) { + this.apiKey = apiKey; + this.secret = secret; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request original = chain.request(); + Request.Builder newRequestBuilder = original.newBuilder(); + + boolean isApiKeyRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) != null; + boolean isSignatureRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED) != null; + newRequestBuilder.removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) + .removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED); + + // Endpoint requires sending a valid API-KEY + if (isApiKeyRequired || isSignatureRequired) { + newRequestBuilder.addHeader(BinanceApiConstants.API_KEY_HEADER, apiKey); + } + + // Endpoint requires signing the payload + if (isSignatureRequired) { + String payload = original.url().query(); + if (!StringUtils.isEmpty(payload)) { + String signature = HmacSHA256Signer.sign(payload, secret); + HttpUrl signedUrl = original.url().newBuilder().addQueryParameter("signature", signature).build(); + newRequestBuilder.url(signedUrl); + } + } + + // Build new request after adding the necessary authentication information + Request newRequest = newRequestBuilder.build(); + return chain.proceed(newRequest); + } + + /** + * Extracts the request body into a String. + * + * @return request body as a string + */ + @SuppressWarnings("unused") + private static String bodyToString(RequestBody request) { + try (final Buffer buffer = new Buffer()) { + final RequestBody copy = request; + if (copy != null) { + copy.writeTo(buffer); + } else { + return ""; + } + return buffer.readUtf8(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final AuthenticationInterceptor that = (AuthenticationInterceptor) o; + return Objects.equals(apiKey, that.apiKey) && + Objects.equals(secret, that.secret); + } + + @Override + public int hashCode() { + return Objects.hash(apiKey, secret); + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java b/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java old mode 100644 new mode 100755 index fc5f06702..17309e273 --- a/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java +++ b/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java @@ -1,29 +1,29 @@ -package com.binance.api.client.security; - -import org.apache.commons.codec.binary.Hex; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - * Utility class to sign messages using HMAC-SHA256. - */ -public class HmacSHA256Signer { - - /** - * Sign the given message using the given secret. - * @param message message to sign - * @param secret secret key - * @return a signed message - */ - public static String sign(String message, String secret) { - try { - Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); - SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); - sha256_HMAC.init(secretKeySpec); - return new String(Hex.encodeHex(sha256_HMAC.doFinal(message.getBytes()))); - } catch (Exception e) { - throw new RuntimeException("Unable to sign message.", e); - } - } -} +package com.binance.api.client.security; + +import org.apache.commons.codec.binary.Hex; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * Utility class to sign messages using HMAC-SHA256. + */ +public class HmacSHA256Signer { + + /** + * Sign the given message using the given secret. + * @param message message to sign + * @param secret secret key + * @return a signed message + */ + public static String sign(String message, String secret) { + try { + Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); + sha256_HMAC.init(secretKeySpec); + return new String(Hex.encodeHex(sha256_HMAC.doFinal(message.getBytes()))); + } catch (Exception e) { + throw new RuntimeException("Unable to sign message.", e); + } + } +} diff --git a/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java b/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java old mode 100644 new mode 100755 index d003a8d94..62d100ef2 --- a/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java +++ b/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java @@ -1,81 +1,81 @@ -package com.binance.api.client.constant; - -import com.binance.api.client.domain.market.Candlestick; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @see BinanceApiConstants - */ -public class BinanceApiConstantsTest { - - private static String candlestickRaw; - private static Candlestick candlestick; - private static ToStringStyle DEFAULT_TO_STRING_BUILDER_STYLE; - - public BinanceApiConstantsTest() { - } - - @BeforeClass - public static void setUpClass() { - - DEFAULT_TO_STRING_BUILDER_STYLE = BinanceApiConstants.TO_STRING_BUILDER_STYLE; - - candlestickRaw = "[\n" - + " 1499040000000,\n" - + " \"0.01634790\",\n" - + " \"0.80000000\",\n" - + " \"0.01575800\",\n" - + " \"0.01577100\",\n" - + " \"148976.11427815\",\n" - + " 1499644799999,\n" - + " \"2434.19055334\",\n" - + " 308,\n" - + " \"1756.87402397\",\n" - + " \"28.46694368\",\n" - + " \"17928899.62484339\"\n" - + " ]"; - ObjectMapper mapper = new ObjectMapper(); - - try { - candlestick = mapper.readValue(candlestickRaw, Candlestick.class); - } catch (IOException e) { - fail(); - } - } - - @AfterClass - public static void tearDownClass() { - BinanceApiConstants.TO_STRING_BUILDER_STYLE = DEFAULT_TO_STRING_BUILDER_STYLE; - } - - @Test - public void testToStringBuilderStyleChange() { - String binaceApiDefaultStyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; - assertEquals(candlestick.toString(), binaceApiDefaultStyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.JSON_STYLE; - String jsonSyle = "{\"openTime\":1499040000000,\"open\":\"0.01634790\",\"high\":\"0.80000000\",\"low\":\"0.01575800\",\"close\":\"0.01577100\",\"volume\":\"148976.11427815\",\"closeTime\":1499644799999,\"quoteAssetVolume\":\"2434.19055334\",\"numberOfTrades\":308,\"takerBuyBaseAssetVolume\":\"1756.87402397\",\"takerBuyQuoteAssetVolume\":\"28.46694368\"}"; - assertEquals(candlestick.toString(), jsonSyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.NO_CLASS_NAME_STYLE; - String noClassNameSyle = "[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; - assertEquals(candlestick.toString(), noClassNameSyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; - String shortPrefixSyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; - assertEquals(candlestick.toString(), shortPrefixSyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SIMPLE_STYLE; - String simpleSyle = "1499040000000,0.01634790,0.80000000,0.01575800,0.01577100,148976.11427815,1499644799999,2434.19055334,308,1756.87402397,28.46694368"; - assertEquals(candlestick.toString(), simpleSyle); - } +package com.binance.api.client.constant; + +import com.binance.api.client.domain.market.Candlestick; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * @see BinanceApiConstants + */ +public class BinanceApiConstantsTest { + + private static String candlestickRaw; + private static Candlestick candlestick; + private static ToStringStyle DEFAULT_TO_STRING_BUILDER_STYLE; + + public BinanceApiConstantsTest() { + } + + @BeforeClass + public static void setUpClass() { + + DEFAULT_TO_STRING_BUILDER_STYLE = BinanceApiConstants.TO_STRING_BUILDER_STYLE; + + candlestickRaw = "[\n" + + " 1499040000000,\n" + + " \"0.01634790\",\n" + + " \"0.80000000\",\n" + + " \"0.01575800\",\n" + + " \"0.01577100\",\n" + + " \"148976.11427815\",\n" + + " 1499644799999,\n" + + " \"2434.19055334\",\n" + + " 308,\n" + + " \"1756.87402397\",\n" + + " \"28.46694368\",\n" + + " \"17928899.62484339\"\n" + + " ]"; + ObjectMapper mapper = new ObjectMapper(); + + try { + candlestick = mapper.readValue(candlestickRaw, Candlestick.class); + } catch (IOException e) { + fail(); + } + } + + @AfterClass + public static void tearDownClass() { + BinanceApiConstants.TO_STRING_BUILDER_STYLE = DEFAULT_TO_STRING_BUILDER_STYLE; + } + + @Test + public void testToStringBuilderStyleChange() { + String binaceApiDefaultStyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; + assertEquals(candlestick.toString(), binaceApiDefaultStyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.JSON_STYLE; + String jsonSyle = "{\"openTime\":1499040000000,\"open\":\"0.01634790\",\"high\":\"0.80000000\",\"low\":\"0.01575800\",\"close\":\"0.01577100\",\"volume\":\"148976.11427815\",\"closeTime\":1499644799999,\"quoteAssetVolume\":\"2434.19055334\",\"numberOfTrades\":308,\"takerBuyBaseAssetVolume\":\"1756.87402397\",\"takerBuyQuoteAssetVolume\":\"28.46694368\"}"; + assertEquals(candlestick.toString(), jsonSyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.NO_CLASS_NAME_STYLE; + String noClassNameSyle = "[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; + assertEquals(candlestick.toString(), noClassNameSyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; + String shortPrefixSyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; + assertEquals(candlestick.toString(), shortPrefixSyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SIMPLE_STYLE; + String simpleSyle = "1499040000000,0.01634790,0.80000000,0.01575800,0.01577100,148976.11427815,1499644799999,2434.19055334,308,1756.87402397,28.46694368"; + assertEquals(candlestick.toString(), simpleSyle); + } } \ No newline at end of file diff --git a/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java b/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java old mode 100644 new mode 100755 index 277a86162..f65e5eefe --- a/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java +++ b/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java @@ -1,49 +1,49 @@ -package com.binance.api.client.domain.account; - -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * @see NewOrderResponse - */ -public class NewOrderResponseTest { - - private NewOrderResponse newOrderResponse; - private Trade trade; - - @Before - public void setUp() { - newOrderResponse = new NewOrderResponse(); - trade = new Trade(); - trade.setId(123L); - } - - @Test - public void shouldHandleToStringWithNullFills() { - assertThat(newOrderResponse.toString(), containsString(",fills=")); - } - - @Test - public void shouldHandleToStringWithNoFills() { - newOrderResponse.setFills(Collections.emptyList()); - assertThat(newOrderResponse.toString(), containsString(",fills=")); - } - - @Test - public void shouldHandleToStringWithFills() { - newOrderResponse.setFills(trades(trade)); - assertThat(newOrderResponse.toString(), containsString(",fills=Trade[id=123,")); - } - - private static List trades(final Trade... trades) { - return Arrays.asList(trades); - } +package com.binance.api.client.domain.account; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @see NewOrderResponse + */ +public class NewOrderResponseTest { + + private NewOrderResponse newOrderResponse; + private Trade trade; + + @Before + public void setUp() { + newOrderResponse = new NewOrderResponse(); + trade = new Trade(); + trade.setId(123L); + } + + @Test + public void shouldHandleToStringWithNullFills() { + assertThat(newOrderResponse.toString(), containsString(",fills=")); + } + + @Test + public void shouldHandleToStringWithNoFills() { + newOrderResponse.setFills(Collections.emptyList()); + assertThat(newOrderResponse.toString(), containsString(",fills=")); + } + + @Test + public void shouldHandleToStringWithFills() { + newOrderResponse.setFills(trades(trade)); + assertThat(newOrderResponse.toString(), containsString(",fills=Trade[id=123,")); + } + + private static List trades(final Trade... trades) { + return Arrays.asList(trades); + } } \ No newline at end of file diff --git a/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java b/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java old mode 100644 new mode 100755 index 133c1ebba..d0a99bf85 --- a/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java @@ -1,44 +1,44 @@ -package com.binance.api.domain.account; - -import com.binance.api.client.domain.account.Withdraw; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; -import static junit.framework.TestCase.fail; - -/** - * Test deserialization of a withdraw/deposit history. - */ -public class WithdrawHistoryDeserializerTest { - - @Test - public void testWithdrawHistoryDeserialziation() { - String withdrawHistoryJson = "{\"withdrawList\":\n" + - "[{\"amount\":0.1,\"address\":\"0x456\",\"successTime\":\"2017-10-13 21:20:09\",\n" + - "\"txId\":\"0x123\",\"id\":\"1\",\"asset\":\"ETH\",\"applyTime\":\"2017-10-13 20:59:38\",\"userId\":\"1\",\"status\":6}],\n" + - "\"success\":true}"; - ObjectMapper mapper = new ObjectMapper(); - try { - WithdrawHistory withdrawHistory = mapper.readValue(withdrawHistoryJson, WithdrawHistory.class); - assertTrue(withdrawHistory.isSuccess()); - List withdrawList = withdrawHistory.getWithdrawList(); - assertEquals(withdrawHistory.getWithdrawList().size(), 1); - Withdraw withdraw = withdrawList.get(0); - assertEquals(withdraw.getAmount(), "0.1"); - assertEquals(withdraw.getAddress(), "0x456"); - assertEquals(withdraw.getAsset(), "ETH"); - assertEquals(withdraw.getApplyTime(), "2017-10-13 20:59:38"); - assertEquals(withdraw.getSuccessTime(), "2017-10-13 21:20:09"); - assertEquals(withdraw.getTxId(), "0x123"); - assertEquals(withdraw.getId(), "1"); - } catch (IOException e) { - fail(e.getMessage()); - } - } -} +package com.binance.api.domain.account; + +import com.binance.api.client.domain.account.Withdraw; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertTrue; +import static junit.framework.TestCase.fail; + +/** + * Test deserialization of a withdraw/deposit history. + */ +public class WithdrawHistoryDeserializerTest { + + @Test + public void testWithdrawHistoryDeserialziation() { + String withdrawHistoryJson = "{\"withdrawList\":\n" + + "[{\"amount\":0.1,\"address\":\"0x456\",\"successTime\":\"2017-10-13 21:20:09\",\n" + + "\"txId\":\"0x123\",\"id\":\"1\",\"asset\":\"ETH\",\"applyTime\":\"2017-10-13 20:59:38\",\"userId\":\"1\",\"status\":6}],\n" + + "\"success\":true}"; + ObjectMapper mapper = new ObjectMapper(); + try { + WithdrawHistory withdrawHistory = mapper.readValue(withdrawHistoryJson, WithdrawHistory.class); + assertTrue(withdrawHistory.isSuccess()); + List withdrawList = withdrawHistory.getWithdrawList(); + assertEquals(withdrawHistory.getWithdrawList().size(), 1); + Withdraw withdraw = withdrawList.get(0); + assertEquals(withdraw.getAmount(), "0.1"); + assertEquals(withdraw.getAddress(), "0x456"); + assertEquals(withdraw.getAsset(), "ETH"); + assertEquals(withdraw.getApplyTime(), "2017-10-13 20:59:38"); + assertEquals(withdraw.getSuccessTime(), "2017-10-13 21:20:09"); + assertEquals(withdraw.getTxId(), "0x123"); + assertEquals(withdraw.getId(), "1"); + } catch (IOException e) { + fail(e.getMessage()); + } + } +} diff --git a/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java b/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java old mode 100644 new mode 100755 index f4b01af40..8f7e40f43 --- a/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java @@ -1,68 +1,68 @@ -package com.binance.api.domain.event; - -import com.binance.api.client.domain.event.CandlestickEvent; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Tests that JSON responses from ta candlestick event are converted to the appropriate CandlestickEvent object. - */ -public class CandlestickEventDeserializerTest { - - @Test - public void testCandlestickEventDeserializer() { - String candlestickEventJson = "{\n" + - " \"e\": \"kline\",\n" + - " \"E\": 1,\n" + - " \"s\": \"ETHBTC\",\n" + - " \"k\": {\n" + - " \"t\": 1499404860000,\n" + - " \"T\": 1499404919999,\n" + - " \"s\": \"ETHBTC\", \n" + - " \"i\": \"1m\",\n" + - " \"f\": 77462, \n" + - " \"L\": 77465, \n" + - " \"o\": \"0.10278577\", \n" + - " \"c\": \"0.10278645\", \n" + - " \"h\": \"0.10278712\", \n" + - " \"l\": \"0.10278518\", \n" + - " \"v\": \"17.47929838\", \n" + - " \"n\": 4, \n" + - " \"x\": false, \n" + - " \"q\": \"1.79662878\", \n" + - " \"V\": \"2.34879839\", \n" + - " \"Q\": \"0.24142166\", \n" + - " \"B\": \"13279784.01349473\"\n" + - " }}"; - ObjectMapper mapper = new ObjectMapper(); - try { - CandlestickEvent candlestickEvent = mapper.readValue(candlestickEventJson, CandlestickEvent.class); - assertEquals(candlestickEvent.getEventType(), "kline"); - assertEquals(candlestickEvent.getEventTime(), 1L); - assertEquals(candlestickEvent.getSymbol(), "ETHBTC"); - - assertEquals((long)candlestickEvent.getOpenTime(), 1499404860000L); - assertEquals(candlestickEvent.getOpen(), "0.10278577"); - assertEquals(candlestickEvent.getHigh(), "0.10278712"); - assertEquals(candlestickEvent.getLow(), "0.10278518"); - assertEquals(candlestickEvent.getClose(), "0.10278645"); - assertEquals(candlestickEvent.getVolume(), "17.47929838"); - assertEquals((long)candlestickEvent.getCloseTime(), 1499404919999L); - assertEquals(candlestickEvent.getIntervalId(), "1m"); - assertEquals((long)candlestickEvent.getFirstTradeId(), 77462L); - assertEquals((long)candlestickEvent.getLastTradeId(), 77465L); - assertEquals(candlestickEvent.getQuoteAssetVolume(), "1.79662878"); - assertEquals((long)candlestickEvent.getNumberOfTrades(), 4L); - assertEquals(candlestickEvent.getTakerBuyBaseAssetVolume(), "2.34879839"); - assertEquals(candlestickEvent.getTakerBuyQuoteAssetVolume(), "0.24142166"); - assertEquals(candlestickEvent.getBarFinal(), false); - } catch (IOException e) { - fail(e.getMessage()); - } - } -} +package com.binance.api.domain.event; + +import com.binance.api.client.domain.event.CandlestickEvent; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Tests that JSON responses from ta candlestick event are converted to the appropriate CandlestickEvent object. + */ +public class CandlestickEventDeserializerTest { + + @Test + public void testCandlestickEventDeserializer() { + String candlestickEventJson = "{\n" + + " \"e\": \"kline\",\n" + + " \"E\": 1,\n" + + " \"s\": \"ETHBTC\",\n" + + " \"k\": {\n" + + " \"t\": 1499404860000,\n" + + " \"T\": 1499404919999,\n" + + " \"s\": \"ETHBTC\", \n" + + " \"i\": \"1m\",\n" + + " \"f\": 77462, \n" + + " \"L\": 77465, \n" + + " \"o\": \"0.10278577\", \n" + + " \"c\": \"0.10278645\", \n" + + " \"h\": \"0.10278712\", \n" + + " \"l\": \"0.10278518\", \n" + + " \"v\": \"17.47929838\", \n" + + " \"n\": 4, \n" + + " \"x\": false, \n" + + " \"q\": \"1.79662878\", \n" + + " \"V\": \"2.34879839\", \n" + + " \"Q\": \"0.24142166\", \n" + + " \"B\": \"13279784.01349473\"\n" + + " }}"; + ObjectMapper mapper = new ObjectMapper(); + try { + CandlestickEvent candlestickEvent = mapper.readValue(candlestickEventJson, CandlestickEvent.class); + assertEquals(candlestickEvent.getEventType(), "kline"); + assertEquals(candlestickEvent.getEventTime(), 1L); + assertEquals(candlestickEvent.getSymbol(), "ETHBTC"); + + assertEquals((long)candlestickEvent.getOpenTime(), 1499404860000L); + assertEquals(candlestickEvent.getOpen(), "0.10278577"); + assertEquals(candlestickEvent.getHigh(), "0.10278712"); + assertEquals(candlestickEvent.getLow(), "0.10278518"); + assertEquals(candlestickEvent.getClose(), "0.10278645"); + assertEquals(candlestickEvent.getVolume(), "17.47929838"); + assertEquals((long)candlestickEvent.getCloseTime(), 1499404919999L); + assertEquals(candlestickEvent.getIntervalId(), "1m"); + assertEquals((long)candlestickEvent.getFirstTradeId(), 77462L); + assertEquals((long)candlestickEvent.getLastTradeId(), 77465L); + assertEquals(candlestickEvent.getQuoteAssetVolume(), "1.79662878"); + assertEquals((long)candlestickEvent.getNumberOfTrades(), 4L); + assertEquals(candlestickEvent.getTakerBuyBaseAssetVolume(), "2.34879839"); + assertEquals(candlestickEvent.getTakerBuyQuoteAssetVolume(), "0.24142166"); + assertEquals(candlestickEvent.getBarFinal(), false); + } catch (IOException e) { + fail(e.getMessage()); + } + } +} diff --git a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java old mode 100644 new mode 100755 index 23b1ced98..a50d31221 --- a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java @@ -1,81 +1,81 @@ -package com.binance.api.domain.event; - - -import com.binance.api.client.domain.account.AssetBalance; -import com.binance.api.client.domain.ExecutionType; -import com.binance.api.client.domain.OrderRejectReason; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.event.AccountUpdateEvent; -import com.binance.api.client.domain.event.OrderTradeUpdateEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Tests that JSON responses from the stream API are converted to the appropriate object. - */ -public class UserDataUpdateEventDeserializerTest { - - @Test - public void testAccountUpdateEventDeserializer() { - final String accountUpdateJson = "{\"e\":\"outboundAccountInfo\",\"E\":1,\"m\":10,\"t\":10,\"b\":0,\"s\":0,\"T\":true,\"W\":true,\"D\":true,\"B\":[{\"a\":\"BTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETH\",\"f\":\"0.10000000\",\"l\":\"0.00000000\"},{\"a\":\"BNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NEO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"123\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"456\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"QTUM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"EOS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"GAS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BTM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"USDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HSR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OAX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"DNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MCO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ELC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PAY\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OMG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"WTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"YOYO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LLT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FID\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNGLS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STRAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BQX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FUN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"KNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"XVG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"IOTA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LINK\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CVC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"REP\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CTR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MDA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTL\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SALT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NULS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SUB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTH\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ADX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PIX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ENG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZEC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"}]}"; - ObjectMapper mapper = new ObjectMapper(); - try { - UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(accountUpdateJson, UserDataUpdateEvent.class); - assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "outboundAccountInfo"); - assertEquals(userDataUpdateEvent.getEventTime(), 1L); - AccountUpdateEvent accountUpdateEvent = userDataUpdateEvent.getAccountUpdateEvent(); - for (AssetBalance assetBalance : accountUpdateEvent.getBalances()) { - if ("ETH".equals(assetBalance.getAsset())) { - assertEquals(assetBalance.getFree(), "0.10000000"); - } else { - assertEquals(assetBalance.getFree(), "0.00000000"); - } - assertEquals(assetBalance.getLocked(), "0.00000000"); - } - } catch (IOException e) { - fail(); - } - } - - @Test - public void testOrderUpdateEventDeserializer() { - final String orderUpdateEventJson = "{\"e\":\"executionReport\",\"E\":1,\"s\":\"NEOETH\",\"c\":\"XXX\",\"S\":\"BUY\",\"o\":\"LIMIT\",\"f\":\"GTC\",\"q\":\"1000.00000000\",\"p\":\"0.00010000\",\"P\":\"0.00000000\",\"F\":\"0.00000000\",\"g\":-1,\"C\":\"5yairWLqfzbusOUdPyG712\",\"x\":\"CANCELED\",\"X\":\"CANCELED\",\"r\":\"NONE\",\"i\":123456,\"l\":\"0.00000000\",\"z\":\"0.00000000\",\"L\":\"0.00000000\",\"n\":\"0\",\"N\":null,\"T\":1,\"t\":-1,\"I\":1,\"w\":false,\"m\":false,\"M\":false}"; - ObjectMapper mapper = new ObjectMapper(); - try { - UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(orderUpdateEventJson, UserDataUpdateEvent.class); - assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "executionReport"); - assertEquals(userDataUpdateEvent.getEventTime(), 1L); - - OrderTradeUpdateEvent orderTradeUpdateEvent = userDataUpdateEvent.getOrderTradeUpdateEvent(); - assertEquals(orderTradeUpdateEvent.getSymbol(), "NEOETH"); - assertEquals(orderTradeUpdateEvent.getNewClientOrderId(), "XXX"); - - assertEquals(orderTradeUpdateEvent.getSide(), OrderSide.BUY); - assertEquals(orderTradeUpdateEvent.getType(), OrderType.LIMIT); - assertEquals(orderTradeUpdateEvent.getTimeInForce(), TimeInForce.GTC); - - assertEquals(orderTradeUpdateEvent.getOriginalQuantity(), "1000.00000000"); - assertEquals(orderTradeUpdateEvent.getPrice(), "0.00010000"); - - assertEquals(orderTradeUpdateEvent.getExecutionType(), ExecutionType.CANCELED); - assertEquals(orderTradeUpdateEvent.getOrderStatus(), OrderStatus.CANCELED); - assertEquals(orderTradeUpdateEvent.getOrderRejectReason(), OrderRejectReason.NONE); - - assertEquals(orderTradeUpdateEvent.getOrderId(), new Long(123456)); - assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), new Long(1)); - } catch (IOException e) { - fail(); - } - } - -} - +package com.binance.api.domain.event; + + +import com.binance.api.client.domain.account.AssetBalance; +import com.binance.api.client.domain.ExecutionType; +import com.binance.api.client.domain.OrderRejectReason; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.event.AccountUpdateEvent; +import com.binance.api.client.domain.event.OrderTradeUpdateEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Tests that JSON responses from the stream API are converted to the appropriate object. + */ +public class UserDataUpdateEventDeserializerTest { + + @Test + public void testAccountUpdateEventDeserializer() { + final String accountUpdateJson = "{\"e\":\"outboundAccountInfo\",\"E\":1,\"m\":10,\"t\":10,\"b\":0,\"s\":0,\"T\":true,\"W\":true,\"D\":true,\"B\":[{\"a\":\"BTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETH\",\"f\":\"0.10000000\",\"l\":\"0.00000000\"},{\"a\":\"BNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NEO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"123\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"456\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"QTUM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"EOS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"GAS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BTM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"USDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HSR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OAX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"DNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MCO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ELC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PAY\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OMG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"WTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"YOYO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LLT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FID\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNGLS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STRAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BQX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FUN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"KNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"XVG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"IOTA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LINK\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CVC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"REP\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CTR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MDA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTL\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SALT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NULS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SUB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTH\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ADX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PIX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ENG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZEC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"}]}"; + ObjectMapper mapper = new ObjectMapper(); + try { + UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(accountUpdateJson, UserDataUpdateEvent.class); + assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "outboundAccountInfo"); + assertEquals(userDataUpdateEvent.getEventTime(), 1L); + AccountUpdateEvent accountUpdateEvent = userDataUpdateEvent.getAccountUpdateEvent(); + for (AssetBalance assetBalance : accountUpdateEvent.getBalances()) { + if ("ETH".equals(assetBalance.getAsset())) { + assertEquals(assetBalance.getFree(), "0.10000000"); + } else { + assertEquals(assetBalance.getFree(), "0.00000000"); + } + assertEquals(assetBalance.getLocked(), "0.00000000"); + } + } catch (IOException e) { + fail(); + } + } + + @Test + public void testOrderUpdateEventDeserializer() { + final String orderUpdateEventJson = "{\"e\":\"executionReport\",\"E\":1,\"s\":\"NEOETH\",\"c\":\"XXX\",\"S\":\"BUY\",\"o\":\"LIMIT\",\"f\":\"GTC\",\"q\":\"1000.00000000\",\"p\":\"0.00010000\",\"P\":\"0.00000000\",\"F\":\"0.00000000\",\"g\":-1,\"C\":\"5yairWLqfzbusOUdPyG712\",\"x\":\"CANCELED\",\"X\":\"CANCELED\",\"r\":\"NONE\",\"i\":123456,\"l\":\"0.00000000\",\"z\":\"0.00000000\",\"L\":\"0.00000000\",\"n\":\"0\",\"N\":null,\"T\":1,\"t\":-1,\"I\":1,\"w\":false,\"m\":false,\"M\":false}"; + ObjectMapper mapper = new ObjectMapper(); + try { + UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(orderUpdateEventJson, UserDataUpdateEvent.class); + assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "executionReport"); + assertEquals(userDataUpdateEvent.getEventTime(), 1L); + + OrderTradeUpdateEvent orderTradeUpdateEvent = userDataUpdateEvent.getOrderTradeUpdateEvent(); + assertEquals(orderTradeUpdateEvent.getSymbol(), "NEOETH"); + assertEquals(orderTradeUpdateEvent.getNewClientOrderId(), "XXX"); + + assertEquals(orderTradeUpdateEvent.getSide(), OrderSide.BUY); + assertEquals(orderTradeUpdateEvent.getType(), OrderType.LIMIT); + assertEquals(orderTradeUpdateEvent.getTimeInForce(), TimeInForce.GTC); + + assertEquals(orderTradeUpdateEvent.getOriginalQuantity(), "1000.00000000"); + assertEquals(orderTradeUpdateEvent.getPrice(), "0.00010000"); + + assertEquals(orderTradeUpdateEvent.getExecutionType(), ExecutionType.CANCELED); + assertEquals(orderTradeUpdateEvent.getOrderStatus(), OrderStatus.CANCELED); + assertEquals(orderTradeUpdateEvent.getOrderRejectReason(), OrderRejectReason.NONE); + + assertEquals(orderTradeUpdateEvent.getOrderId(), new Long(123456)); + assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), new Long(1)); + } catch (IOException e) { + fail(); + } + } + +} + diff --git a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java old mode 100644 new mode 100755 index b865a8b68..94467915b --- a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java @@ -1,128 +1,128 @@ -package com.binance.api.domain.general; - -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.FilterType; -import com.binance.api.client.domain.general.RateLimit; -import com.binance.api.client.domain.general.RateLimitInterval; -import com.binance.api.client.domain.general.RateLimitType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; -import com.binance.api.client.domain.general.SymbolStatus; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -/** - * Test deserialization of exchange information. - */ -public class ExchangeInfoDeserializerTest { - - @Test - public void testExchangeInfoDeserialization() { - final String json = "{\n" + - " \"timezone\": \"UTC\",\n" + - " \"serverTime\": 1508631584636,\n" + - " \"rateLimits\": [{\n" + - " \"rateLimitType\": \"REQUEST_WEIGHT\",\n" + - " \"interval\": \"MINUTE\",\n" + - " \"limit\": 1200\n" + - " },\n" + - " {\n" + - " \"rateLimitType\": \"ORDERS\",\n" + - " \"interval\": \"SECOND\",\n" + - " \"limit\": 10\n" + - " },\n" + - " {\n" + - " \"rateLimitType\": \"ORDERS\",\n" + - " \"interval\": \"DAY\",\n" + - " \"limit\": 100000\n" + - " }\n" + - " ],\n" + - " \"exchangeFilters\": [],\n" + - " \"symbols\": [{\n" + - " \"symbol\": \"ETHBTC\",\n" + - " \"status\": \"TRADING\",\n" + - " \"baseAsset\": \"ETH\",\n" + - " \"baseAssetPrecision\": 8,\n" + - " \"quoteAsset\": \"BTC\",\n" + - " \"quotePrecision\": 8,\n" + - " \"orderTypes\": [\"LIMIT\", \"MARKET\"],\n" + - " \"icebergAllowed\": false,\n" + - " \"filters\": [{\n" + - " \"filterType\": \"PRICE_FILTER\",\n" + - " \"minPrice\": \"0.00000100\",\n" + - " \"maxPrice\": \"100000.00000000\",\n" + - " \"tickSize\": \"0.00000100\"\n" + - " }, {\n" + - " \"filterType\": \"LOT_SIZE\",\n" + - " \"minQty\": \"0.00100000\",\n" + - " \"maxQty\": \"100000.00000000\",\n" + - " \"stepSize\": \"0.00100000\"\n" + - " }, {\n" + - " \"filterType\": \"MIN_NOTIONAL\",\n" + - " \"minNotional\": \"0.00100000\"\n" + - " }]\n" + - " }]" + - "}"; - ObjectMapper mapper = new ObjectMapper(); - try { - ExchangeInfo exchangeInfo = mapper.readValue(json, ExchangeInfo.class); - System.out.println(exchangeInfo); - assertEquals(exchangeInfo.getTimezone(), "UTC"); - assertEquals((long)exchangeInfo.getServerTime(), 1508631584636L); - - List rateLimits = exchangeInfo.getRateLimits(); - assertEquals(rateLimits.size(), 3); - testRateLimit(rateLimits.get(0), RateLimitType.REQUEST_WEIGHT, RateLimitInterval.MINUTE, 1200); - testRateLimit(rateLimits.get(1), RateLimitType.ORDERS, RateLimitInterval.SECOND, 10); - testRateLimit(rateLimits.get(2), RateLimitType.ORDERS, RateLimitInterval.DAY, 100000); - - List symbols = exchangeInfo.getSymbols(); - assertEquals(symbols.size(), 1); - SymbolInfo symbolInfo = symbols.get(0); - assertEquals(symbolInfo.getSymbol(), "ETHBTC"); - assertEquals(symbolInfo.getStatus(), SymbolStatus.TRADING); - assertEquals(symbolInfo.getBaseAsset(), "ETH"); - assertEquals((int)symbolInfo.getBaseAssetPrecision(), 8); - assertEquals(symbolInfo.getQuoteAsset(), "BTC"); - assertEquals((int)symbolInfo.getQuotePrecision(), 8); - assertEquals(symbolInfo.getOrderTypes(), Arrays.asList(OrderType.LIMIT, OrderType.MARKET)); - assertFalse(symbolInfo.isIcebergAllowed()); - - List symbolFilters = symbolInfo.getFilters(); - assertEquals(symbolFilters.size(), 3); - - SymbolFilter priceFilter = symbolFilters.get(0); - assertEquals(priceFilter.getFilterType(), FilterType.PRICE_FILTER); - assertEquals(priceFilter.getMinPrice(), "0.00000100"); - assertEquals(priceFilter.getMaxPrice(), "100000.00000000"); - assertEquals(priceFilter.getTickSize(), "0.00000100"); - - SymbolFilter lotSizeFilter = symbolFilters.get(1); - assertEquals(lotSizeFilter.getFilterType(), FilterType.LOT_SIZE); - assertEquals(lotSizeFilter.getMinQty(), "0.00100000"); - assertEquals(lotSizeFilter.getMaxQty(), "100000.00000000"); - assertEquals(lotSizeFilter.getStepSize(), "0.00100000"); - - SymbolFilter minNotionalFilter = symbolFilters.get(2); - assertEquals(minNotionalFilter.getFilterType(), FilterType.MIN_NOTIONAL); - assertEquals(minNotionalFilter.getMinNotional(), "0.00100000"); - } catch (IOException e) { - fail(); - } - } - - private void testRateLimit(RateLimit rateLimit, RateLimitType expectedRateLimitType, RateLimitInterval expectedInterval, int expectedLimit) { - assertEquals(rateLimit.getRateLimitType(), expectedRateLimitType); - assertEquals(rateLimit.getInterval(), expectedInterval); - assertEquals((long)rateLimit.getLimit(), expectedLimit); - } -} +package com.binance.api.domain.general; + +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.FilterType; +import com.binance.api.client.domain.general.RateLimit; +import com.binance.api.client.domain.general.RateLimitInterval; +import com.binance.api.client.domain.general.RateLimitType; +import com.binance.api.client.domain.general.SymbolFilter; +import com.binance.api.client.domain.general.SymbolInfo; +import com.binance.api.client.domain.general.SymbolStatus; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +/** + * Test deserialization of exchange information. + */ +public class ExchangeInfoDeserializerTest { + + @Test + public void testExchangeInfoDeserialization() { + final String json = "{\n" + + " \"timezone\": \"UTC\",\n" + + " \"serverTime\": 1508631584636,\n" + + " \"rateLimits\": [{\n" + + " \"rateLimitType\": \"REQUEST_WEIGHT\",\n" + + " \"interval\": \"MINUTE\",\n" + + " \"limit\": 1200\n" + + " },\n" + + " {\n" + + " \"rateLimitType\": \"ORDERS\",\n" + + " \"interval\": \"SECOND\",\n" + + " \"limit\": 10\n" + + " },\n" + + " {\n" + + " \"rateLimitType\": \"ORDERS\",\n" + + " \"interval\": \"DAY\",\n" + + " \"limit\": 100000\n" + + " }\n" + + " ],\n" + + " \"exchangeFilters\": [],\n" + + " \"symbols\": [{\n" + + " \"symbol\": \"ETHBTC\",\n" + + " \"status\": \"TRADING\",\n" + + " \"baseAsset\": \"ETH\",\n" + + " \"baseAssetPrecision\": 8,\n" + + " \"quoteAsset\": \"BTC\",\n" + + " \"quotePrecision\": 8,\n" + + " \"orderTypes\": [\"LIMIT\", \"MARKET\"],\n" + + " \"icebergAllowed\": false,\n" + + " \"filters\": [{\n" + + " \"filterType\": \"PRICE_FILTER\",\n" + + " \"minPrice\": \"0.00000100\",\n" + + " \"maxPrice\": \"100000.00000000\",\n" + + " \"tickSize\": \"0.00000100\"\n" + + " }, {\n" + + " \"filterType\": \"LOT_SIZE\",\n" + + " \"minQty\": \"0.00100000\",\n" + + " \"maxQty\": \"100000.00000000\",\n" + + " \"stepSize\": \"0.00100000\"\n" + + " }, {\n" + + " \"filterType\": \"MIN_NOTIONAL\",\n" + + " \"minNotional\": \"0.00100000\"\n" + + " }]\n" + + " }]" + + "}"; + ObjectMapper mapper = new ObjectMapper(); + try { + ExchangeInfo exchangeInfo = mapper.readValue(json, ExchangeInfo.class); + System.out.println(exchangeInfo); + assertEquals(exchangeInfo.getTimezone(), "UTC"); + assertEquals((long)exchangeInfo.getServerTime(), 1508631584636L); + + List rateLimits = exchangeInfo.getRateLimits(); + assertEquals(rateLimits.size(), 3); + testRateLimit(rateLimits.get(0), RateLimitType.REQUEST_WEIGHT, RateLimitInterval.MINUTE, 1200); + testRateLimit(rateLimits.get(1), RateLimitType.ORDERS, RateLimitInterval.SECOND, 10); + testRateLimit(rateLimits.get(2), RateLimitType.ORDERS, RateLimitInterval.DAY, 100000); + + List symbols = exchangeInfo.getSymbols(); + assertEquals(symbols.size(), 1); + SymbolInfo symbolInfo = symbols.get(0); + assertEquals(symbolInfo.getSymbol(), "ETHBTC"); + assertEquals(symbolInfo.getStatus(), SymbolStatus.TRADING); + assertEquals(symbolInfo.getBaseAsset(), "ETH"); + assertEquals((int)symbolInfo.getBaseAssetPrecision(), 8); + assertEquals(symbolInfo.getQuoteAsset(), "BTC"); + assertEquals((int)symbolInfo.getQuotePrecision(), 8); + assertEquals(symbolInfo.getOrderTypes(), Arrays.asList(OrderType.LIMIT, OrderType.MARKET)); + assertFalse(symbolInfo.isIcebergAllowed()); + + List symbolFilters = symbolInfo.getFilters(); + assertEquals(symbolFilters.size(), 3); + + SymbolFilter priceFilter = symbolFilters.get(0); + assertEquals(priceFilter.getFilterType(), FilterType.PRICE_FILTER); + assertEquals(priceFilter.getMinPrice(), "0.00000100"); + assertEquals(priceFilter.getMaxPrice(), "100000.00000000"); + assertEquals(priceFilter.getTickSize(), "0.00000100"); + + SymbolFilter lotSizeFilter = symbolFilters.get(1); + assertEquals(lotSizeFilter.getFilterType(), FilterType.LOT_SIZE); + assertEquals(lotSizeFilter.getMinQty(), "0.00100000"); + assertEquals(lotSizeFilter.getMaxQty(), "100000.00000000"); + assertEquals(lotSizeFilter.getStepSize(), "0.00100000"); + + SymbolFilter minNotionalFilter = symbolFilters.get(2); + assertEquals(minNotionalFilter.getFilterType(), FilterType.MIN_NOTIONAL); + assertEquals(minNotionalFilter.getMinNotional(), "0.00100000"); + } catch (IOException e) { + fail(); + } + } + + private void testRateLimit(RateLimit rateLimit, RateLimitType expectedRateLimitType, RateLimitInterval expectedInterval, int expectedLimit) { + assertEquals(rateLimit.getRateLimitType(), expectedRateLimitType); + assertEquals(rateLimit.getInterval(), expectedInterval); + assertEquals((long)rateLimit.getLimit(), expectedLimit); + } +} diff --git a/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java b/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java old mode 100644 new mode 100755 index d59bef8ac..5f6146c9d --- a/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java @@ -1,51 +1,51 @@ -package com.binance.api.domain.market; - -import com.binance.api.client.domain.market.Candlestick; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Tests the adequate deserialization of candlestick JSON information. - */ -public class CandlestickDeserializerTest { - - @Test - public void testCandlestickDeserializerTest() { - final String candlestickJson = "[\n" + - " 1499040000000,\n" + - " \"0.01634790\",\n" + - " \"0.80000000\",\n" + - " \"0.01575800\",\n" + - " \"0.01577100\",\n" + - " \"148976.11427815\",\n" + - " 1499644799999,\n" + - " \"2434.19055334\",\n" + - " 308,\n" + - " \"1756.87402397\",\n" + - " \"28.46694368\",\n" + - " \"17928899.62484339\"\n" + - " ]"; - ObjectMapper mapper = new ObjectMapper(); - try { - Candlestick candlestick = mapper.readValue(candlestickJson, Candlestick.class); - assertEquals((long)candlestick.getOpenTime(), 1499040000000L); - assertEquals(candlestick.getOpen(), "0.01634790"); - assertEquals(candlestick.getHigh(), "0.80000000"); - assertEquals(candlestick.getLow(), "0.01575800"); - assertEquals(candlestick.getClose(), "0.01577100"); - assertEquals(candlestick.getVolume(), "148976.11427815"); - assertEquals((long)candlestick.getCloseTime(), 1499644799999L); - assertEquals(candlestick.getQuoteAssetVolume(), "2434.19055334"); - assertEquals((long)candlestick.getNumberOfTrades(), 308L); - assertEquals(candlestick.getTakerBuyBaseAssetVolume(), "1756.87402397"); - assertEquals(candlestick.getTakerBuyQuoteAssetVolume(), "28.46694368"); - } catch (IOException e) { - fail(); - } - } -} +package com.binance.api.domain.market; + +import com.binance.api.client.domain.market.Candlestick; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Tests the adequate deserialization of candlestick JSON information. + */ +public class CandlestickDeserializerTest { + + @Test + public void testCandlestickDeserializerTest() { + final String candlestickJson = "[\n" + + " 1499040000000,\n" + + " \"0.01634790\",\n" + + " \"0.80000000\",\n" + + " \"0.01575800\",\n" + + " \"0.01577100\",\n" + + " \"148976.11427815\",\n" + + " 1499644799999,\n" + + " \"2434.19055334\",\n" + + " 308,\n" + + " \"1756.87402397\",\n" + + " \"28.46694368\",\n" + + " \"17928899.62484339\"\n" + + " ]"; + ObjectMapper mapper = new ObjectMapper(); + try { + Candlestick candlestick = mapper.readValue(candlestickJson, Candlestick.class); + assertEquals((long)candlestick.getOpenTime(), 1499040000000L); + assertEquals(candlestick.getOpen(), "0.01634790"); + assertEquals(candlestick.getHigh(), "0.80000000"); + assertEquals(candlestick.getLow(), "0.01575800"); + assertEquals(candlestick.getClose(), "0.01577100"); + assertEquals(candlestick.getVolume(), "148976.11427815"); + assertEquals((long)candlestick.getCloseTime(), 1499644799999L); + assertEquals(candlestick.getQuoteAssetVolume(), "2434.19055334"); + assertEquals((long)candlestick.getNumberOfTrades(), 308L); + assertEquals(candlestick.getTakerBuyBaseAssetVolume(), "1756.87402397"); + assertEquals(candlestick.getTakerBuyQuoteAssetVolume(), "28.46694368"); + } catch (IOException e) { + fail(); + } + } +} diff --git a/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java b/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java old mode 100644 new mode 100755 index 928655379..8fcd51118 --- a/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java +++ b/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java @@ -1,81 +1,81 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.AssetBalance; - -import java.util.Map; -import java.util.TreeMap; - -import static com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType.ACCOUNT_UPDATE; - -/** - * Illustrates how to use the user data event stream to create a local cache for the balance of an account. - */ -public class AccountBalanceCacheExample { - - private final BinanceApiClientFactory clientFactory; - - /** - * Key is the symbol, and the value is the balance of that symbol on the account. - */ - private Map accountBalanceCache; - - /** - * Listen key used to interact with the user data streaming API. - */ - private final String listenKey; - - public AccountBalanceCacheExample(String apiKey, String secret) { - this.clientFactory = BinanceApiClientFactory.newInstance(apiKey, secret); - this.listenKey = initializeAssetBalanceCacheAndStreamSession(); - startAccountBalanceEventStreaming(listenKey); - } - - /** - * Initializes the asset balance cache by using the REST API and starts a new user data streaming session. - * - * @return a listenKey that can be used with the user data streaming API. - */ - private String initializeAssetBalanceCacheAndStreamSession() { - BinanceApiRestClient client = clientFactory.newRestClient(); - Account account = client.getAccount(); - - this.accountBalanceCache = new TreeMap<>(); - for (AssetBalance assetBalance : account.getBalances()) { - accountBalanceCache.put(assetBalance.getAsset(), assetBalance); - } - - return client.startUserDataStream(); - } - - /** - * Begins streaming of agg trades events. - */ - private void startAccountBalanceEventStreaming(String listenKey) { - BinanceApiWebSocketClient client = clientFactory.newWebSocketClient(); - - client.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == ACCOUNT_UPDATE) { - // Override cached asset balances - for (AssetBalance assetBalance : response.getAccountUpdateEvent().getBalances()) { - accountBalanceCache.put(assetBalance.getAsset(), assetBalance); - } - System.out.println(accountBalanceCache); - } - }); - } - - /** - * @return an account balance cache, containing the balance for every asset in this account. - */ - public Map getAccountBalanceCache() { - return accountBalanceCache; - } - - public static void main(String[] args) { - new AccountBalanceCacheExample("YOUR_API_KEY", "YOUR_SECRET"); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.AssetBalance; + +import java.util.Map; +import java.util.TreeMap; + +import static com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType.ACCOUNT_UPDATE; + +/** + * Illustrates how to use the user data event stream to create a local cache for the balance of an account. + */ +public class AccountBalanceCacheExample { + + private final BinanceApiClientFactory clientFactory; + + /** + * Key is the symbol, and the value is the balance of that symbol on the account. + */ + private Map accountBalanceCache; + + /** + * Listen key used to interact with the user data streaming API. + */ + private final String listenKey; + + public AccountBalanceCacheExample(String apiKey, String secret) { + this.clientFactory = BinanceApiClientFactory.newInstance(apiKey, secret); + this.listenKey = initializeAssetBalanceCacheAndStreamSession(); + startAccountBalanceEventStreaming(listenKey); + } + + /** + * Initializes the asset balance cache by using the REST API and starts a new user data streaming session. + * + * @return a listenKey that can be used with the user data streaming API. + */ + private String initializeAssetBalanceCacheAndStreamSession() { + BinanceApiRestClient client = clientFactory.newRestClient(); + Account account = client.getAccount(); + + this.accountBalanceCache = new TreeMap<>(); + for (AssetBalance assetBalance : account.getBalances()) { + accountBalanceCache.put(assetBalance.getAsset(), assetBalance); + } + + return client.startUserDataStream(); + } + + /** + * Begins streaming of agg trades events. + */ + private void startAccountBalanceEventStreaming(String listenKey) { + BinanceApiWebSocketClient client = clientFactory.newWebSocketClient(); + + client.onUserDataUpdateEvent(listenKey, response -> { + if (response.getEventType() == ACCOUNT_UPDATE) { + // Override cached asset balances + for (AssetBalance assetBalance : response.getAccountUpdateEvent().getBalances()) { + accountBalanceCache.put(assetBalance.getAsset(), assetBalance); + } + System.out.println(accountBalanceCache); + } + }); + } + + /** + * @return an account balance cache, containing the balance for every asset in this account. + */ + public Map getAccountBalanceCache() { + return accountBalanceCache; + } + + public static void main(String[] args) { + new AccountBalanceCacheExample("YOUR_API_KEY", "YOUR_SECRET"); + } +} diff --git a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java old mode 100644 new mode 100755 index bd7d56364..72fc68c3d --- a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java @@ -1,40 +1,40 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.Trade; - -import java.util.List; - -/** - * Examples on how to get account information. - */ -public class AccountEndpointsExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiRestClient client = factory.newRestClient(); - - // Get account balances - Account account = client.getAccount(60_000L, System.currentTimeMillis()); - System.out.println(account.getBalances()); - System.out.println(account.getAssetBalance("ETH")); - - // Get list of trades - List myTrades = client.getMyTrades("NEOETH"); - System.out.println(myTrades); - - // Get withdraw history - System.out.println(client.getWithdrawHistory("ETH")); - - // Get deposit history - System.out.println(client.getDepositHistory("ETH")); - - // Get deposit address - System.out.println(client.getDepositAddress("ETH")); - - // Withdraw - client.withdraw("ETH", "0x123", "0.1", null, null); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.Trade; + +import java.util.List; + +/** + * Examples on how to get account information. + */ +public class AccountEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiRestClient client = factory.newRestClient(); + + // Get account balances + Account account = client.getAccount(60_000L, System.currentTimeMillis()); + System.out.println(account.getBalances()); + System.out.println(account.getAssetBalance("ETH")); + + // Get list of trades + List myTrades = client.getMyTrades("NEOETH"); + System.out.println(myTrades); + + // Get withdraw history + System.out.println(client.getWithdrawHistory("ETH")); + + // Get deposit history + System.out.println(client.getDepositHistory("ETH")); + + // Get deposit address + System.out.println(client.getDepositAddress("ETH")); + + // Withdraw + client.withdraw("ETH", "0x123", "0.1", null, null); + } +} diff --git a/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java old mode 100644 new mode 100755 index 7e924fdf5..5ede0526b --- a/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java @@ -1,31 +1,31 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.account.Account; - -/** - * Examples on how to get account information. - */ -public class AccountEndpointsExampleAsync { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Get account balances (async) - client.getAccount((Account response) -> System.out.println(response.getAssetBalance("ETH"))); - - // Get list of trades (async) - client.getMyTrades("NEOETH", response -> System.out.println(response)); - - // Get withdraw history (async) - client.getWithdrawHistory("ETH", response -> System.out.println(response)); - - // Get deposit history (async) - client.getDepositHistory("ETH", response -> System.out.println(response)); - - // Withdraw (async) - client.withdraw("ETH", "0x123", "0.1", null, null, response -> {}); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.account.Account; + +/** + * Examples on how to get account information. + */ +public class AccountEndpointsExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Get account balances (async) + client.getAccount((Account response) -> System.out.println(response.getAssetBalance("ETH"))); + + // Get list of trades (async) + client.getMyTrades("NEOETH", response -> System.out.println(response)); + + // Get withdraw history (async) + client.getWithdrawHistory("ETH", response -> System.out.println(response)); + + // Get deposit history (async) + client.getDepositHistory("ETH", response -> System.out.println(response)); + + // Withdraw (async) + client.withdraw("ETH", "0x123", "0.1", null, null, response -> {}); + } +} diff --git a/src/test/java/com/binance/api/examples/AggTradesCacheExample.java b/src/test/java/com/binance/api/examples/AggTradesCacheExample.java old mode 100644 new mode 100755 index 8106ba34e..985ffe4ca --- a/src/test/java/com/binance/api/examples/AggTradesCacheExample.java +++ b/src/test/java/com/binance/api/examples/AggTradesCacheExample.java @@ -1,80 +1,80 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.market.AggTrade; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Illustrates how to use the aggTrades event stream to create a local cache of trades for a symbol. - */ -public class AggTradesCacheExample { - - /** - * Key is the aggregate trade id, and the value contains the aggregated trade data, which is - * automatically updated whenever a new agg data stream event arrives. - */ - private Map aggTradesCache; - - public AggTradesCacheExample(String symbol) { - initializeAggTradesCache(symbol); - startAggTradesEventStreaming(symbol); - } - - /** - * Initializes the aggTrades cache by using the REST API. - */ - private void initializeAggTradesCache(String symbol) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - List aggTrades = client.getAggTrades(symbol.toUpperCase()); - - this.aggTradesCache = new HashMap<>(); - for (AggTrade aggTrade : aggTrades) { - aggTradesCache.put(aggTrade.getAggregatedTradeId(), aggTrade); - } - } - - /** - * Begins streaming of agg trades events. - */ - private void startAggTradesEventStreaming(String symbol) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiWebSocketClient client = factory.newWebSocketClient(); - - client.onAggTradeEvent(symbol.toLowerCase(), response -> { - Long aggregatedTradeId = response.getAggregatedTradeId(); - AggTrade updateAggTrade = aggTradesCache.get(aggregatedTradeId); - if (updateAggTrade == null) { - // new agg trade - updateAggTrade = new AggTrade(); - } - updateAggTrade.setAggregatedTradeId(aggregatedTradeId); - updateAggTrade.setPrice(response.getPrice()); - updateAggTrade.setQuantity(response.getQuantity()); - updateAggTrade.setFirstBreakdownTradeId(response.getFirstBreakdownTradeId()); - updateAggTrade.setLastBreakdownTradeId(response.getLastBreakdownTradeId()); - updateAggTrade.setBuyerMaker(response.isBuyerMaker()); - - // Store the updated agg trade in the cache - aggTradesCache.put(aggregatedTradeId, updateAggTrade); - System.out.println(updateAggTrade); - }); - } - - /** - * @return an aggTrades cache, containing the aggregated trade id as the key, - * and the agg trade data as the value. - */ - public Map getAggTradesCache() { - return aggTradesCache; - } - - public static void main(String[] args) { - new AggTradesCacheExample("ETHBTC"); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.market.AggTrade; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Illustrates how to use the aggTrades event stream to create a local cache of trades for a symbol. + */ +public class AggTradesCacheExample { + + /** + * Key is the aggregate trade id, and the value contains the aggregated trade data, which is + * automatically updated whenever a new agg data stream event arrives. + */ + private Map aggTradesCache; + + public AggTradesCacheExample(String symbol) { + initializeAggTradesCache(symbol); + startAggTradesEventStreaming(symbol); + } + + /** + * Initializes the aggTrades cache by using the REST API. + */ + private void initializeAggTradesCache(String symbol) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + List aggTrades = client.getAggTrades(symbol.toUpperCase()); + + this.aggTradesCache = new HashMap<>(); + for (AggTrade aggTrade : aggTrades) { + aggTradesCache.put(aggTrade.getAggregatedTradeId(), aggTrade); + } + } + + /** + * Begins streaming of agg trades events. + */ + private void startAggTradesEventStreaming(String symbol) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiWebSocketClient client = factory.newWebSocketClient(); + + client.onAggTradeEvent(symbol.toLowerCase(), response -> { + Long aggregatedTradeId = response.getAggregatedTradeId(); + AggTrade updateAggTrade = aggTradesCache.get(aggregatedTradeId); + if (updateAggTrade == null) { + // new agg trade + updateAggTrade = new AggTrade(); + } + updateAggTrade.setAggregatedTradeId(aggregatedTradeId); + updateAggTrade.setPrice(response.getPrice()); + updateAggTrade.setQuantity(response.getQuantity()); + updateAggTrade.setFirstBreakdownTradeId(response.getFirstBreakdownTradeId()); + updateAggTrade.setLastBreakdownTradeId(response.getLastBreakdownTradeId()); + updateAggTrade.setBuyerMaker(response.isBuyerMaker()); + + // Store the updated agg trade in the cache + aggTradesCache.put(aggregatedTradeId, updateAggTrade); + System.out.println(updateAggTrade); + }); + } + + /** + * @return an aggTrades cache, containing the aggregated trade id as the key, + * and the agg trade data as the value. + */ + public Map getAggTradesCache() { + return aggTradesCache; + } + + public static void main(String[] args) { + new AggTradesCacheExample("ETHBTC"); + } +} diff --git a/src/test/java/com/binance/api/examples/AllMarketTickersExample.java b/src/test/java/com/binance/api/examples/AllMarketTickersExample.java old mode 100644 new mode 100755 index 94880a59e..4bee760ce --- a/src/test/java/com/binance/api/examples/AllMarketTickersExample.java +++ b/src/test/java/com/binance/api/examples/AllMarketTickersExample.java @@ -1,21 +1,21 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiWebSocketClient; - -/** - * All market tickers channel examples. - * - * It illustrates how to create a stream to obtain all market tickers. - */ -public class AllMarketTickersExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiWebSocketClient client = factory.newWebSocketClient(); - - client.onAllMarketTickersEvent(event -> { - System.out.println(event); - }); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiWebSocketClient; + +/** + * All market tickers channel examples. + * + * It illustrates how to create a stream to obtain all market tickers. + */ +public class AllMarketTickersExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiWebSocketClient client = factory.newWebSocketClient(); + + client.onAllMarketTickersEvent(event -> { + System.out.println(event); + }); + } +} diff --git a/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java b/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java old mode 100644 new mode 100755 index 1800be613..4b0be5217 --- a/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java +++ b/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java @@ -1,86 +1,86 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; - -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Illustrates how to use the klines/candlesticks event stream to create a local cache of bids/asks for a symbol. - */ -public class CandlesticksCacheExample { - - /** - * Key is the start/open time of the candle, and the value contains candlestick date. - */ - private Map candlesticksCache; - - public CandlesticksCacheExample(String symbol, CandlestickInterval interval) { - initializeCandlestickCache(symbol, interval); - startCandlestickEventStreaming(symbol, interval); - } - - /** - * Initializes the candlestick cache by using the REST API. - */ - private void initializeCandlestickCache(String symbol, CandlestickInterval interval) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - List candlestickBars = client.getCandlestickBars(symbol.toUpperCase(), interval); - - this.candlesticksCache = new TreeMap<>(); - for (Candlestick candlestickBar : candlestickBars) { - candlesticksCache.put(candlestickBar.getOpenTime(), candlestickBar); - } - } - - /** - * Begins streaming of depth events. - */ - private void startCandlestickEventStreaming(String symbol, CandlestickInterval interval) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiWebSocketClient client = factory.newWebSocketClient(); - - client.onCandlestickEvent(symbol.toLowerCase(), interval, response -> { - Long openTime = response.getOpenTime(); - Candlestick updateCandlestick = candlesticksCache.get(openTime); - if (updateCandlestick == null) { - // new candlestick - updateCandlestick = new Candlestick(); - } - // update candlestick with the stream data - updateCandlestick.setOpenTime(response.getOpenTime()); - updateCandlestick.setOpen(response.getOpen()); - updateCandlestick.setLow(response.getLow()); - updateCandlestick.setHigh(response.getHigh()); - updateCandlestick.setClose(response.getClose()); - updateCandlestick.setCloseTime(response.getCloseTime()); - updateCandlestick.setVolume(response.getVolume()); - updateCandlestick.setNumberOfTrades(response.getNumberOfTrades()); - updateCandlestick.setQuoteAssetVolume(response.getQuoteAssetVolume()); - updateCandlestick.setTakerBuyQuoteAssetVolume(response.getTakerBuyQuoteAssetVolume()); - updateCandlestick.setTakerBuyBaseAssetVolume(response.getTakerBuyQuoteAssetVolume()); - - // Store the updated candlestick in the cache - candlesticksCache.put(openTime, updateCandlestick); - System.out.println(updateCandlestick); - }); - } - - /** - * @return a klines/candlestick cache, containing the open/start time of the candlestick as the key, - * and the candlestick data as the value. - */ - public Map getCandlesticksCache() { - return candlesticksCache; - } - - public static void main(String[] args) { - new CandlesticksCacheExample("ETHBTC", CandlestickInterval.ONE_MINUTE); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; + +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * Illustrates how to use the klines/candlesticks event stream to create a local cache of bids/asks for a symbol. + */ +public class CandlesticksCacheExample { + + /** + * Key is the start/open time of the candle, and the value contains candlestick date. + */ + private Map candlesticksCache; + + public CandlesticksCacheExample(String symbol, CandlestickInterval interval) { + initializeCandlestickCache(symbol, interval); + startCandlestickEventStreaming(symbol, interval); + } + + /** + * Initializes the candlestick cache by using the REST API. + */ + private void initializeCandlestickCache(String symbol, CandlestickInterval interval) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + List candlestickBars = client.getCandlestickBars(symbol.toUpperCase(), interval); + + this.candlesticksCache = new TreeMap<>(); + for (Candlestick candlestickBar : candlestickBars) { + candlesticksCache.put(candlestickBar.getOpenTime(), candlestickBar); + } + } + + /** + * Begins streaming of depth events. + */ + private void startCandlestickEventStreaming(String symbol, CandlestickInterval interval) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiWebSocketClient client = factory.newWebSocketClient(); + + client.onCandlestickEvent(symbol.toLowerCase(), interval, response -> { + Long openTime = response.getOpenTime(); + Candlestick updateCandlestick = candlesticksCache.get(openTime); + if (updateCandlestick == null) { + // new candlestick + updateCandlestick = new Candlestick(); + } + // update candlestick with the stream data + updateCandlestick.setOpenTime(response.getOpenTime()); + updateCandlestick.setOpen(response.getOpen()); + updateCandlestick.setLow(response.getLow()); + updateCandlestick.setHigh(response.getHigh()); + updateCandlestick.setClose(response.getClose()); + updateCandlestick.setCloseTime(response.getCloseTime()); + updateCandlestick.setVolume(response.getVolume()); + updateCandlestick.setNumberOfTrades(response.getNumberOfTrades()); + updateCandlestick.setQuoteAssetVolume(response.getQuoteAssetVolume()); + updateCandlestick.setTakerBuyQuoteAssetVolume(response.getTakerBuyQuoteAssetVolume()); + updateCandlestick.setTakerBuyBaseAssetVolume(response.getTakerBuyQuoteAssetVolume()); + + // Store the updated candlestick in the cache + candlesticksCache.put(openTime, updateCandlestick); + System.out.println(updateCandlestick); + }); + } + + /** + * @return a klines/candlestick cache, containing the open/start time of the candlestick as the key, + * and the candlestick data as the value. + */ + public Map getCandlesticksCache() { + return candlesticksCache; + } + + public static void main(String[] args) { + new CandlesticksCacheExample("ETHBTC", CandlestickInterval.ONE_MINUTE); + } +} diff --git a/src/test/java/com/binance/api/examples/DepthCacheExample.java b/src/test/java/com/binance/api/examples/DepthCacheExample.java old mode 100644 new mode 100755 index eb1975796..25adc8c55 --- a/src/test/java/com/binance/api/examples/DepthCacheExample.java +++ b/src/test/java/com/binance/api/examples/DepthCacheExample.java @@ -1,244 +1,244 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.OrderBookEntry; - -import java.io.Closeable; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.TreeMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - -/** - * Illustrates how to use the depth event stream to create a local cache of bids/asks for a symbol. - * - * Snapshots of the order book can be retrieved from the REST API. - * Delta changes to the book can be received by subscribing for updates via the web socket API. - * - * To ensure no updates are missed, it is important to subscribe for updates on the web socket API - * _before_ getting the snapshot from the REST API. Done the other way around it is possible to - * miss one or more updates on the web socket, leaving the local cache in an inconsistent state. - * - * Steps: - * 1. Subscribe to depth events and cache any events that are received. - * 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. - * 3. Apply any cache events that have a final updateId later than the snapshot's update id. - * 4. Start applying any newly received depth events to the depth cache. - * - * The example repeats these steps, on a new web socket, should the web socket connection be lost. - */ -public class DepthCacheExample { - - private static final String BIDS = "BIDS"; - private static final String ASKS = "ASKS"; - - private final String symbol; - private final BinanceApiRestClient restClient; - private final BinanceApiWebSocketClient wsClient; - private final WsCallback wsCallback = new WsCallback(); - private final Map> depthCache = new HashMap<>(); - - private long lastUpdateId = -1; - private volatile Closeable webSocket; - - public DepthCacheExample(String symbol) { - this.symbol = symbol; - - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - this.wsClient = factory.newWebSocketClient(); - this.restClient = factory.newRestClient(); - - initialize(); - } - - private void initialize() { - // 1. Subscribe to depth events and cache any events that are received. - final List pendingDeltas = startDepthEventStreaming(); - - // 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. - initializeDepthCache(); - - // 3. & 4. handled in here. - applyPendingDeltas(pendingDeltas); - } - - /** - * Begins streaming of depth events. - * - * Any events received are cached until the rest API is polled for an initial snapshot. - */ - private List startDepthEventStreaming() { - final List pendingDeltas = new CopyOnWriteArrayList<>(); - wsCallback.setHandler(pendingDeltas::add); - - this.webSocket = wsClient.onDepthEvent(symbol.toLowerCase(), wsCallback); - - return pendingDeltas; - } - - /** - * 2. Initializes the depth cache by getting a snapshot from the REST API. - */ - private void initializeDepthCache() { - OrderBook orderBook = restClient.getOrderBook(symbol.toUpperCase(), 10); - - this.lastUpdateId = orderBook.getLastUpdateId(); - - NavigableMap asks = new TreeMap<>(Comparator.reverseOrder()); - for (OrderBookEntry ask : orderBook.getAsks()) { - asks.put(new BigDecimal(ask.getPrice()), new BigDecimal(ask.getQty())); - } - depthCache.put(ASKS, asks); - - NavigableMap bids = new TreeMap<>(Comparator.reverseOrder()); - for (OrderBookEntry bid : orderBook.getBids()) { - bids.put(new BigDecimal(bid.getPrice()), new BigDecimal(bid.getQty())); - } - depthCache.put(BIDS, bids); - } - - /** - * Deal with any cached updates and switch to normal running. - */ - private void applyPendingDeltas(final List pendingDeltas) { - final Consumer updateOrderBook = newEvent -> { - if (newEvent.getFinalUpdateId() > lastUpdateId) { - System.out.println(newEvent); - lastUpdateId = newEvent.getFinalUpdateId(); - updateOrderBook(getAsks(), newEvent.getAsks()); - updateOrderBook(getBids(), newEvent.getBids()); - printDepthCache(); - } - }; - - final Consumer drainPending = newEvent -> { - pendingDeltas.add(newEvent); - - // 3. Apply any deltas received on the web socket that have an update-id indicating they come - // after the snapshot. - pendingDeltas.stream() - .filter( - e -> e.getFinalUpdateId() > lastUpdateId) // Ignore any updates before the snapshot - .forEach(updateOrderBook); - - // 4. Start applying any newly received depth events to the depth cache. - wsCallback.setHandler(updateOrderBook); - }; - - wsCallback.setHandler(drainPending); - } - - /** - * Updates an order book (bids or asks) with a delta received from the server. - * - * Whenever the qty specified is ZERO, it means the price should was removed from the order book. - */ - private void updateOrderBook(NavigableMap lastOrderBookEntries, - List orderBookDeltas) { - for (OrderBookEntry orderBookDelta : orderBookDeltas) { - BigDecimal price = new BigDecimal(orderBookDelta.getPrice()); - BigDecimal qty = new BigDecimal(orderBookDelta.getQty()); - if (qty.compareTo(BigDecimal.ZERO) == 0) { - // qty=0 means remove this level - lastOrderBookEntries.remove(price); - } else { - lastOrderBookEntries.put(price, qty); - } - } - } - - public NavigableMap getAsks() { - return depthCache.get(ASKS); - } - - public NavigableMap getBids() { - return depthCache.get(BIDS); - } - - /** - * @return the best ask in the order book - */ - private Map.Entry getBestAsk() { - return getAsks().lastEntry(); - } - - /** - * @return the best bid in the order book - */ - private Map.Entry getBestBid() { - return getBids().firstEntry(); - } - - /** - * @return a depth cache, containing two keys (ASKs and BIDs), and for each, an ordered list of book entries. - */ - public Map> getDepthCache() { - return depthCache; - } - - public void close() throws IOException { - webSocket.close(); - } - - /** - * Prints the cached order book / depth of a symbol as well as the best ask and bid price in the book. - */ - private void printDepthCache() { - System.out.println(depthCache); - System.out.println("ASKS:(" + getAsks().size() + ")"); - getAsks().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); - System.out.println("BIDS:(" + getBids().size() + ")"); - getBids().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); - System.out.println("BEST ASK: " + toDepthCacheEntryString(getBestAsk())); - System.out.println("BEST BID: " + toDepthCacheEntryString(getBestBid())); - } - - /** - * Pretty prints an order book entry in the format "price / quantity". - */ - private static String toDepthCacheEntryString(Map.Entry depthCacheEntry) { - return depthCacheEntry.getKey().toPlainString() + " / " + depthCacheEntry.getValue(); - } - - public static void main(String[] args) { - new DepthCacheExample("ETHBTC"); - } - - private final class WsCallback implements BinanceApiCallback { - - private final AtomicReference> handler = new AtomicReference<>(); - - @Override - public void onResponse(DepthEvent depthEvent) { - try { - handler.get().accept(depthEvent); - } catch (final Exception e) { - System.err.println("Exception caught processing depth event"); - e.printStackTrace(System.err); - } - } - - @Override - public void onFailure(Throwable cause) { - System.out.println("WS connection failed. Reconnecting. cause:" + cause.getMessage()); - - initialize(); - } - - private void setHandler(final Consumer handler) { - this.handler.set(handler); - } - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.event.DepthEvent; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.OrderBookEntry; + +import java.io.Closeable; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.NavigableMap; +import java.util.TreeMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +/** + * Illustrates how to use the depth event stream to create a local cache of bids/asks for a symbol. + * + * Snapshots of the order book can be retrieved from the REST API. + * Delta changes to the book can be received by subscribing for updates via the web socket API. + * + * To ensure no updates are missed, it is important to subscribe for updates on the web socket API + * _before_ getting the snapshot from the REST API. Done the other way around it is possible to + * miss one or more updates on the web socket, leaving the local cache in an inconsistent state. + * + * Steps: + * 1. Subscribe to depth events and cache any events that are received. + * 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. + * 3. Apply any cache events that have a final updateId later than the snapshot's update id. + * 4. Start applying any newly received depth events to the depth cache. + * + * The example repeats these steps, on a new web socket, should the web socket connection be lost. + */ +public class DepthCacheExample { + + private static final String BIDS = "BIDS"; + private static final String ASKS = "ASKS"; + + private final String symbol; + private final BinanceApiRestClient restClient; + private final BinanceApiWebSocketClient wsClient; + private final WsCallback wsCallback = new WsCallback(); + private final Map> depthCache = new HashMap<>(); + + private long lastUpdateId = -1; + private volatile Closeable webSocket; + + public DepthCacheExample(String symbol) { + this.symbol = symbol; + + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + this.wsClient = factory.newWebSocketClient(); + this.restClient = factory.newRestClient(); + + initialize(); + } + + private void initialize() { + // 1. Subscribe to depth events and cache any events that are received. + final List pendingDeltas = startDepthEventStreaming(); + + // 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. + initializeDepthCache(); + + // 3. & 4. handled in here. + applyPendingDeltas(pendingDeltas); + } + + /** + * Begins streaming of depth events. + * + * Any events received are cached until the rest API is polled for an initial snapshot. + */ + private List startDepthEventStreaming() { + final List pendingDeltas = new CopyOnWriteArrayList<>(); + wsCallback.setHandler(pendingDeltas::add); + + this.webSocket = wsClient.onDepthEvent(symbol.toLowerCase(), wsCallback); + + return pendingDeltas; + } + + /** + * 2. Initializes the depth cache by getting a snapshot from the REST API. + */ + private void initializeDepthCache() { + OrderBook orderBook = restClient.getOrderBook(symbol.toUpperCase(), 10); + + this.lastUpdateId = orderBook.getLastUpdateId(); + + NavigableMap asks = new TreeMap<>(Comparator.reverseOrder()); + for (OrderBookEntry ask : orderBook.getAsks()) { + asks.put(new BigDecimal(ask.getPrice()), new BigDecimal(ask.getQty())); + } + depthCache.put(ASKS, asks); + + NavigableMap bids = new TreeMap<>(Comparator.reverseOrder()); + for (OrderBookEntry bid : orderBook.getBids()) { + bids.put(new BigDecimal(bid.getPrice()), new BigDecimal(bid.getQty())); + } + depthCache.put(BIDS, bids); + } + + /** + * Deal with any cached updates and switch to normal running. + */ + private void applyPendingDeltas(final List pendingDeltas) { + final Consumer updateOrderBook = newEvent -> { + if (newEvent.getFinalUpdateId() > lastUpdateId) { + System.out.println(newEvent); + lastUpdateId = newEvent.getFinalUpdateId(); + updateOrderBook(getAsks(), newEvent.getAsks()); + updateOrderBook(getBids(), newEvent.getBids()); + printDepthCache(); + } + }; + + final Consumer drainPending = newEvent -> { + pendingDeltas.add(newEvent); + + // 3. Apply any deltas received on the web socket that have an update-id indicating they come + // after the snapshot. + pendingDeltas.stream() + .filter( + e -> e.getFinalUpdateId() > lastUpdateId) // Ignore any updates before the snapshot + .forEach(updateOrderBook); + + // 4. Start applying any newly received depth events to the depth cache. + wsCallback.setHandler(updateOrderBook); + }; + + wsCallback.setHandler(drainPending); + } + + /** + * Updates an order book (bids or asks) with a delta received from the server. + * + * Whenever the qty specified is ZERO, it means the price should was removed from the order book. + */ + private void updateOrderBook(NavigableMap lastOrderBookEntries, + List orderBookDeltas) { + for (OrderBookEntry orderBookDelta : orderBookDeltas) { + BigDecimal price = new BigDecimal(orderBookDelta.getPrice()); + BigDecimal qty = new BigDecimal(orderBookDelta.getQty()); + if (qty.compareTo(BigDecimal.ZERO) == 0) { + // qty=0 means remove this level + lastOrderBookEntries.remove(price); + } else { + lastOrderBookEntries.put(price, qty); + } + } + } + + public NavigableMap getAsks() { + return depthCache.get(ASKS); + } + + public NavigableMap getBids() { + return depthCache.get(BIDS); + } + + /** + * @return the best ask in the order book + */ + private Map.Entry getBestAsk() { + return getAsks().lastEntry(); + } + + /** + * @return the best bid in the order book + */ + private Map.Entry getBestBid() { + return getBids().firstEntry(); + } + + /** + * @return a depth cache, containing two keys (ASKs and BIDs), and for each, an ordered list of book entries. + */ + public Map> getDepthCache() { + return depthCache; + } + + public void close() throws IOException { + webSocket.close(); + } + + /** + * Prints the cached order book / depth of a symbol as well as the best ask and bid price in the book. + */ + private void printDepthCache() { + System.out.println(depthCache); + System.out.println("ASKS:(" + getAsks().size() + ")"); + getAsks().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); + System.out.println("BIDS:(" + getBids().size() + ")"); + getBids().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); + System.out.println("BEST ASK: " + toDepthCacheEntryString(getBestAsk())); + System.out.println("BEST BID: " + toDepthCacheEntryString(getBestBid())); + } + + /** + * Pretty prints an order book entry in the format "price / quantity". + */ + private static String toDepthCacheEntryString(Map.Entry depthCacheEntry) { + return depthCacheEntry.getKey().toPlainString() + " / " + depthCacheEntry.getValue(); + } + + public static void main(String[] args) { + new DepthCacheExample("ETHBTC"); + } + + private final class WsCallback implements BinanceApiCallback { + + private final AtomicReference> handler = new AtomicReference<>(); + + @Override + public void onResponse(DepthEvent depthEvent) { + try { + handler.get().accept(depthEvent); + } catch (final Exception e) { + System.err.println("Exception caught processing depth event"); + e.printStackTrace(System.err); + } + } + + @Override + public void onFailure(Throwable cause) { + System.out.println("WS connection failed. Reconnecting. cause:" + cause.getMessage()); + + initialize(); + } + + private void setHandler(final Consumer handler) { + this.handler.set(handler); + } + } +} diff --git a/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java old mode 100644 new mode 100755 index 911cab374..760d6f26a --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java @@ -1,46 +1,46 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.FilterType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; - -import java.util.List; - -/** - * Examples on how to use the general endpoints. - */ -public class GeneralEndpointsExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - - // Test connectivity - client.ping(); - - // Check server time - long serverTime = client.getServerTime(); - System.out.println(serverTime); - - // Exchange info - ExchangeInfo exchangeInfo = client.getExchangeInfo(); - System.out.println(exchangeInfo.getTimezone()); - System.out.println(exchangeInfo.getSymbols()); - - // Obtain symbol information - SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); - System.out.println(symbolInfo.getStatus()); - - SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); - System.out.println(priceFilter.getMinPrice()); - System.out.println(priceFilter.getTickSize()); - - // Obtain asset information - List allAssets = client.getAllAssets(); - System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get()); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.FilterType; +import com.binance.api.client.domain.general.SymbolFilter; +import com.binance.api.client.domain.general.SymbolInfo; + +import java.util.List; + +/** + * Examples on how to use the general endpoints. + */ +public class GeneralEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + + // Test connectivity + client.ping(); + + // Check server time + long serverTime = client.getServerTime(); + System.out.println(serverTime); + + // Exchange info + ExchangeInfo exchangeInfo = client.getExchangeInfo(); + System.out.println(exchangeInfo.getTimezone()); + System.out.println(exchangeInfo.getSymbols()); + + // Obtain symbol information + SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); + System.out.println(symbolInfo.getStatus()); + + SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); + System.out.println(priceFilter.getMinPrice()); + System.out.println(priceFilter.getTickSize()); + + // Obtain asset information + List allAssets = client.getAllAssets(); + System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get()); + } +} diff --git a/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java old mode 100644 new mode 100755 index 77bfd238e..96739a5c2 --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java @@ -1,45 +1,45 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.FilterType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; - -import java.util.List; - -/** - * Examples on how to use the general endpoints. - */ -public class GeneralEndpointsExampleAsync { - - public static void main(String[] args) throws InterruptedException { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Test connectivity - client.ping(response -> System.out.println("Ping succeeded.")); - - // Check server time - client.getServerTime(response -> System.out.println(response.getServerTime())); - - // Exchange info - client.getExchangeInfo(exchangeInfo -> { - System.out.println(exchangeInfo.getTimezone()); - System.out.println(exchangeInfo.getSymbols()); - - // Obtain symbol information - SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); - System.out.println(symbolInfo.getStatus()); - - SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); - System.out.println(priceFilter.getMinPrice()); - System.out.println(priceFilter.getTickSize()); - }); - - // Obtain asset information - client.getAllAssets(allAssets -> - System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get())); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.FilterType; +import com.binance.api.client.domain.general.SymbolFilter; +import com.binance.api.client.domain.general.SymbolInfo; + +import java.util.List; + +/** + * Examples on how to use the general endpoints. + */ +public class GeneralEndpointsExampleAsync { + + public static void main(String[] args) throws InterruptedException { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Test connectivity + client.ping(response -> System.out.println("Ping succeeded.")); + + // Check server time + client.getServerTime(response -> System.out.println(response.getServerTime())); + + // Exchange info + client.getExchangeInfo(exchangeInfo -> { + System.out.println(exchangeInfo.getTimezone()); + System.out.println(exchangeInfo.getSymbols()); + + // Obtain symbol information + SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); + System.out.println(symbolInfo.getStatus()); + + SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); + System.out.println(priceFilter.getMinPrice()); + System.out.println(priceFilter.getTickSize()); + }); + + // Obtain asset information + client.getAllAssets(allAssets -> + System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get())); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java new file mode 100755 index 000000000..0d204fac1 --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java @@ -0,0 +1,41 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.MarginAccount; +import com.binance.api.client.domain.account.MarginTransaction; +import com.binance.api.client.domain.account.Trade; + +import java.util.List; + +/** + * Examples on how to get margin account information. + */ +public class MarginAccountEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + + // Get account balances + MarginAccount marginAccount = client.getAccount(); + System.out.println(marginAccount.getUserAssets()); + System.out.println(marginAccount.getAssetBalance("ETH")); + System.out.println(marginAccount.getMarginLevel()); + + // Get list of trades + List myTrades = client.getMyTrades("NEOETH"); + System.out.println(myTrades); + + // Transfer, borrow, repay + MarginTransaction spotToMargin = client.transfer("USDT", "1", TransferType.SPOT_TO_MARGIN); + System.out.println(spotToMargin.getTranId()); + MarginTransaction borrowed = client.borrow("USDT", "1"); + System.out.println(borrowed.getTranId()); + MarginTransaction repayed = client.repay("USDT", "1"); + System.out.println(repayed.getTranId()); + MarginTransaction marginToSpot = client.transfer("USDT", "1", TransferType.MARGIN_TO_SPOT); + System.out.println(marginToSpot.getTranId()); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java new file mode 100755 index 000000000..07c3507be --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java @@ -0,0 +1,36 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncMarginRestClient; +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.MarginTransaction; + +/** + * Examples on how to get margin account information asynchronously. + */ +public class MarginAccountEndpointsExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncMarginRestClient client = factory.newAsyncMarginRestClient(); + + // Get account balances + client.getAccount(marginAccount -> { + System.out.println(marginAccount.getUserAssets()); + System.out.println(marginAccount.getAssetBalance("ETH")); + System.out.println(marginAccount.getMarginLevel()); + }); + + // Get list of trades + client.getMyTrades("NEOETH", myTrades -> { + System.out.println(myTrades); + }); + + // Transfer, borrow, repay + client.transfer("USDT", "1", TransferType.SPOT_TO_MARGIN, transaction -> System.out.println(transaction.getTranId())); + client.borrow("USDT", "1", transaction -> System.out.println(transaction.getTranId())); + client.repay("USDT", "1", transaction -> System.out.println(transaction.getTranId())); + client.transfer("USDT", "1", TransferType.MARGIN_TO_SPOT, transaction -> System.out.println(transaction.getTranId())); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java new file mode 100755 index 000000000..b9456722f --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -0,0 +1,24 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; + +import java.util.List; + +/** + * Examples on how to get margin account information. + */ +public class MarginAccountEndpointsLoanQueryExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + MarginTransaction borrowed = client.borrow("USDT", "310"); + System.out.println(borrowed.getTranId()); + LoanQueryResult queryResult = client.queryLoan("USDT", borrowed.getTranId()); + Loan loan = queryResult.getRows().get(0); + System.out.println(loan.getStatus()); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExample.java b/src/test/java/com/binance/api/examples/MarginOrdersExample.java new file mode 100755 index 000000000..404274489 --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginOrdersExample.java @@ -0,0 +1,46 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.NewOrderResponseType; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.request.*; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class MarginOrdersExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + + // Getting list of open orders + List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); + System.out.println(openOrders); + + // Get status of a particular order + Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 751698L)); + System.out.println(order); + + // Canceling an order + try { + CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); + System.out.println(cancelOrderResponse); + } catch (BinanceApiException e) { + System.out.println(e.getError().getMsg()); + } + + // Placing a real LIMIT order + NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); + System.out.println(newOrderResponse); + } + +} diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java new file mode 100755 index 000000000..c80cdfc70 --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java @@ -0,0 +1,36 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncMarginRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class MarginOrdersExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncMarginRestClient client = factory.newAsyncMarginRestClient(); + + // Getting list of open orders + client.getOpenOrders(new OrderRequest("LINKETH"), response -> System.out.println(response)); + + // Get status of a particular order + client.getOrderStatus(new OrderStatusRequest("LINKETH", 745262L), + response -> System.out.println(response)); + + // Canceling an order + client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), + response -> System.out.println(response)); + + // Placing a real LIMIT order + client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println(response)); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java b/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java new file mode 100755 index 000000000..d6bab71fd --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java @@ -0,0 +1,55 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.event.AccountUpdateEvent; +import com.binance.api.client.domain.event.OrderTradeUpdateEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; + +/** + * User data stream endpoints examples. + * + * It illustrates how to create a stream to obtain updates on a user account, + * as well as update on trades/orders on a user account. + */ +public class MarginUserDataStreamExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + + // First, we obtain a listenKey which is required to interact with the user data stream + String listenKey = client.startUserDataStream(); + + // Then, we open a new web socket client, and provide a callback that is called on every update + BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient(); + + // Listen for changes in the account + webSocketClient.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()); + } + }); + System.out.println("Waiting for events..."); + + // We can keep alive the user data stream + // client.keepAliveUserDataStream(listenKey); + + // Or we can invalidate it, whenever it is no longer needed + // client.closeUserDataStream(listenKey); + } +} diff --git a/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java b/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java old mode 100644 new mode 100755 index 79a83b11f..592aba46a --- a/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java @@ -1,57 +1,57 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; -import com.binance.api.client.exception.BinanceApiException; - -import java.util.List; - -/** - * Examples on how to get market data information such as the latest price of a symbol, etc. - */ -public class MarketDataEndpointsExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - - // Getting depth of a symbol - OrderBook orderBook = client.getOrderBook("NEOETH", 10); - System.out.println(orderBook.getAsks()); - - // Getting latest price of a symbol - TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH"); - System.out.println(tickerStatistics); - - // Getting all latest prices - List allPrices = client.getAllPrices(); - System.out.println(allPrices); - - // Getting agg trades - List aggTrades = client.getAggTrades("NEOETH"); - System.out.println(aggTrades); - - // Weekly candlestick bars for a symbol - List candlesticks = client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY); - System.out.println(candlesticks); - - // Getting all book tickers - List allBookTickers = client.getBookTickers(); - System.out.println(allBookTickers); - - // Exception handling - try { - client.getOrderBook("UNKNOWN", 10); - } catch (BinanceApiException e) { - System.out.println(e.getError().getCode()); // -1121 - System.out.println(e.getError().getMsg()); // Invalid symbol - } - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +/** + * Examples on how to get market data information such as the latest price of a symbol, etc. + */ +public class MarketDataEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + + // Getting depth of a symbol + OrderBook orderBook = client.getOrderBook("NEOETH", 10); + System.out.println(orderBook.getAsks()); + + // Getting latest price of a symbol + TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH"); + System.out.println(tickerStatistics); + + // Getting all latest prices + List allPrices = client.getAllPrices(); + System.out.println(allPrices); + + // Getting agg trades + List aggTrades = client.getAggTrades("NEOETH"); + System.out.println(aggTrades); + + // Weekly candlestick bars for a symbol + List candlesticks = client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY); + System.out.println(candlesticks); + + // Getting all book tickers + List allBookTickers = client.getBookTickers(); + System.out.println(allBookTickers); + + // Exception handling + try { + client.getOrderBook("UNKNOWN", 10); + } catch (BinanceApiException e) { + System.out.println(e.getError().getCode()); // -1121 + System.out.println(e.getError().getMsg()); // Invalid symbol + } + } +} diff --git a/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java old mode 100644 new mode 100755 index c85330c2b..f27fab7ff --- a/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java @@ -1,57 +1,57 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; -import com.binance.api.client.exception.BinanceApiException; - -import java.util.List; - -/** - * Examples on how to get market data information such as the latest price of a symbol, etc., in an async way. - */ -public class MarketDataEndpointsExampleAsync { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Getting depth of a symbol (async) - client.getOrderBook("NEOETH", 10, (OrderBook response) -> { - System.out.println(response.getBids()); - }); - - // Getting latest price of a symbol (async) - client.get24HrPriceStatistics("NEOETH", (TickerStatistics response) -> { - System.out.println(response); - }); - - // Getting all latest prices (async) - client.getAllPrices((List response) -> { - System.out.println(response); - }); - - // Getting agg trades (async) - client.getAggTrades("NEOETH", (List response) -> System.out.println(response)); - - // Weekly candlestick bars for a symbol - client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY, - (List response) -> System.out.println(response)); - - // Book tickers (async) - client.getBookTickers(response -> System.out.println(response)); - - // Exception handling - try { - client.getOrderBook("UNKNOWN", 10, response -> System.out.println(response)); - } catch (BinanceApiException e) { - System.out.println(e.getError().getCode()); // -1121 - System.out.println(e.getError().getMsg()); // Invalid symbol - } - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +/** + * Examples on how to get market data information such as the latest price of a symbol, etc., in an async way. + */ +public class MarketDataEndpointsExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Getting depth of a symbol (async) + client.getOrderBook("NEOETH", 10, (OrderBook response) -> { + System.out.println(response.getBids()); + }); + + // Getting latest price of a symbol (async) + client.get24HrPriceStatistics("NEOETH", (TickerStatistics response) -> { + System.out.println(response); + }); + + // Getting all latest prices (async) + client.getAllPrices((List response) -> { + System.out.println(response); + }); + + // Getting agg trades (async) + client.getAggTrades("NEOETH", (List response) -> System.out.println(response)); + + // Weekly candlestick bars for a symbol + client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY, + (List response) -> System.out.println(response)); + + // Book tickers (async) + client.getBookTickers(response -> System.out.println(response)); + + // Exception handling + try { + client.getOrderBook("UNKNOWN", 10, response -> System.out.println(response)); + } catch (BinanceApiException e) { + System.out.println(e.getError().getCode()); // -1121 + System.out.println(e.getError().getMsg()); // Invalid symbol + } + } +} diff --git a/src/test/java/com/binance/api/examples/MarketDataStreamExample.java b/src/test/java/com/binance/api/examples/MarketDataStreamExample.java old mode 100644 new mode 100755 index f2b790510..898d49b10 --- a/src/test/java/com/binance/api/examples/MarketDataStreamExample.java +++ b/src/test/java/com/binance/api/examples/MarketDataStreamExample.java @@ -1,28 +1,28 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.market.CandlestickInterval; - -import java.io.IOException; - -/** - * Market data stream endpoints examples. - * - * It illustrates how to create a stream to obtain updates on market data such as executed trades. - */ -public class MarketDataStreamExample { - - public static void main(String[] args) throws InterruptedException, IOException { - BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient(); - - // Listen for aggregated trade events for ETH/BTC - client.onAggTradeEvent("ethbtc", response -> System.out.println(response)); - - // Listen for changes in the order book in ETH/BTC - client.onDepthEvent("ethbtc", response -> System.out.println(response)); - - // Obtain 1m candlesticks in real-time for ETH/BTC - client.onCandlestickEvent("ethbtc", CandlestickInterval.ONE_MINUTE, response -> System.out.println(response)); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.market.CandlestickInterval; + +import java.io.IOException; + +/** + * Market data stream endpoints examples. + * + * It illustrates how to create a stream to obtain updates on market data such as executed trades. + */ +public class MarketDataStreamExample { + + public static void main(String[] args) throws InterruptedException, IOException { + BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient(); + + // Listen for aggregated trade events for ETH/BTC + client.onAggTradeEvent("ethbtc", response -> System.out.println(response)); + + // Listen for changes in the order book in ETH/BTC + client.onDepthEvent("ethbtc", response -> System.out.println(response)); + + // Obtain 1m candlesticks in real-time for ETH/BTC + client.onCandlestickEvent("ethbtc", CandlestickInterval.ONE_MINUTE, response -> System.out.println(response)); + } +} diff --git a/src/test/java/com/binance/api/examples/OrdersExample.java b/src/test/java/com/binance/api/examples/OrdersExample.java old mode 100644 new mode 100755 index fc2185497..a1dd9d6cd --- a/src/test/java/com/binance/api/examples/OrdersExample.java +++ b/src/test/java/com/binance/api/examples/OrdersExample.java @@ -1,61 +1,61 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.NewOrderResponseType; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.exception.BinanceApiException; - -import java.util.List; - -import static com.binance.api.client.domain.account.NewOrder.limitBuy; -import static com.binance.api.client.domain.account.NewOrder.marketBuy; - -/** - * Examples on how to place orders, cancel them, and query account information. - */ -public class OrdersExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiRestClient client = factory.newRestClient(); - - // Getting list of open orders - List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); - System.out.println(openOrders); - - // Getting list of all orders with a limit of 10 - List allOrders = client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10)); - System.out.println(allOrders); - - // Get status of a particular order - Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 751698L)); - System.out.println(order); - - // Canceling an order - try { - CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); - System.out.println(cancelOrderResponse); - } catch (BinanceApiException e) { - System.out.println(e.getError().getMsg()); - } - - // Placing a test LIMIT order - client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001")); - - // Placing a test MARKET order - client.newOrderTest(marketBuy("LINKETH", "1000")); - - // Placing a real LIMIT order - NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); - System.out.println(newOrderResponse); - } - -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.NewOrderResponseType; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; +import static com.binance.api.client.domain.account.NewOrder.marketBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class OrdersExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiRestClient client = factory.newRestClient(); + + // Getting list of open orders + List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); + System.out.println(openOrders); + + // Getting list of all orders with a limit of 10 + List allOrders = client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10)); + System.out.println(allOrders); + + // Get status of a particular order + Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 751698L)); + System.out.println(order); + + // Canceling an order + try { + CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); + System.out.println(cancelOrderResponse); + } catch (BinanceApiException e) { + System.out.println(e.getError().getMsg()); + } + + // Placing a test LIMIT order + client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001")); + + // Placing a test MARKET order + client.newOrderTest(marketBuy("LINKETH", "1000")); + + // Placing a real LIMIT order + NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); + System.out.println(newOrderResponse); + } + +} diff --git a/src/test/java/com/binance/api/examples/OrdersExampleAsync.java b/src/test/java/com/binance/api/examples/OrdersExampleAsync.java old mode 100644 new mode 100755 index cadb53a58..776e694a6 --- a/src/test/java/com/binance/api/examples/OrdersExampleAsync.java +++ b/src/test/java/com/binance/api/examples/OrdersExampleAsync.java @@ -1,48 +1,48 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; - -import static com.binance.api.client.domain.account.NewOrder.limitBuy; -import static com.binance.api.client.domain.account.NewOrder.marketBuy; - -/** - * Examples on how to place orders, cancel them, and query account information. - */ -public class OrdersExampleAsync { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Getting list of open orders - client.getOpenOrders(new OrderRequest("LINKETH"), response -> System.out.println(response)); - - // Get status of a particular order - client.getOrderStatus(new OrderStatusRequest("LINKETH", 745262L), - response -> System.out.println(response)); - - // Getting list of all orders with a limit of 10 - client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10), response -> System.out.println(response)); - - // Canceling an order - client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), - response -> System.out.println(response)); - - // Placing a test LIMIT order - client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), - response -> System.out.println("Test order has succeeded.")); - - // Placing a test MARKET order - client.newOrderTest(marketBuy("LINKETH", "1000"), response -> System.out.println("Test order has succeeded.")); - - // Placing a real LIMIT order - client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), - response -> System.out.println(response)); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; +import static com.binance.api.client.domain.account.NewOrder.marketBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class OrdersExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Getting list of open orders + client.getOpenOrders(new OrderRequest("LINKETH"), response -> System.out.println(response)); + + // Get status of a particular order + client.getOrderStatus(new OrderStatusRequest("LINKETH", 745262L), + response -> System.out.println(response)); + + // Getting list of all orders with a limit of 10 + client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10), response -> System.out.println(response)); + + // Canceling an order + client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), + response -> System.out.println(response)); + + // Placing a test LIMIT order + client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println("Test order has succeeded.")); + + // Placing a test MARKET order + client.newOrderTest(marketBuy("LINKETH", "1000"), response -> System.out.println("Test order has succeeded.")); + + // Placing a real LIMIT order + client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println(response)); + } +} diff --git a/src/test/java/com/binance/api/examples/UserDataStreamExample.java b/src/test/java/com/binance/api/examples/UserDataStreamExample.java old mode 100644 new mode 100755 index 8ea5f309a..180f5d7b7 --- a/src/test/java/com/binance/api/examples/UserDataStreamExample.java +++ b/src/test/java/com/binance/api/examples/UserDataStreamExample.java @@ -1,54 +1,54 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.event.AccountUpdateEvent; -import com.binance.api.client.domain.event.OrderTradeUpdateEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; - -/** - * User data stream endpoints examples. - * - * It illustrates how to create a stream to obtain updates on a user account, - * as well as update on trades/orders on a user account. - */ -public class UserDataStreamExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiRestClient client = factory.newRestClient(); - - // First, we obtain a listenKey which is required to interact with the user data stream - String listenKey = client.startUserDataStream(); - - // Then, we open a new web socket client, and provide a callback that is called on every update - BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient(); - - // Listen for changes in the account - webSocketClient.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()); - } - }); - System.out.println("Waiting for events..."); - - // We can keep alive the user data stream - // client.keepAliveUserDataStream(listenKey); - - // Or we can invalidate it, whenever it is no longer needed - // client.closeUserDataStream(listenKey); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.event.AccountUpdateEvent; +import com.binance.api.client.domain.event.OrderTradeUpdateEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; + +/** + * User data stream endpoints examples. + * + * It illustrates how to create a stream to obtain updates on a user account, + * as well as update on trades/orders on a user account. + */ +public class UserDataStreamExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiRestClient client = factory.newRestClient(); + + // First, we obtain a listenKey which is required to interact with the user data stream + String listenKey = client.startUserDataStream(); + + // Then, we open a new web socket client, and provide a callback that is called on every update + BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient(); + + // Listen for changes in the account + webSocketClient.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()); + } + }); + System.out.println("Waiting for events..."); + + // We can keep alive the user data stream + // client.keepAliveUserDataStream(listenKey); + + // Or we can invalidate it, whenever it is no longer needed + // client.closeUserDataStream(listenKey); + } +} From f3e35be0deb136f64632746ab790de322d4c39c3 Mon Sep 17 00:00:00 2001 From: Truong Ha Date: Thu, 30 Apr 2020 14:15:36 +0700 Subject: [PATCH 2/8] Updated constants and services for margin endpoints --- .../client/constant/BinanceApiConstants.java | 5 ++ .../api/client/impl/BinanceApiService.java | 69 ++++++++++++++++--- 2 files changed, 64 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java index 4e3a9de27..8e84256d7 100755 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -29,6 +29,11 @@ public class BinanceApiConstants { */ public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; + /** + * Default margin receiving window. + */ + public static final long DEFAULT_MARGIN_RECEIVING_WINDOW = 5_000L; + /** * Default ToStringStyle used by toString methods. * Override this to change the output format of the overridden toString methods. diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 6f6c293db..3a4220317 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -4,16 +4,7 @@ import com.binance.api.client.domain.OrderSide; import com.binance.api.client.domain.OrderType; import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.NewOrderResponseType; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.*; import com.binance.api.client.domain.account.request.CancelOrderResponse; import com.binance.api.client.domain.event.ListenKey; import com.binance.api.client.domain.general.Asset; @@ -177,4 +168,62 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) @DELETE("/api/v1/userDataStream") Call closeAliveUserDataStream(@Query("listenKey") String listenKey); + + // Margin Account endpoints + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/transfer") + Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/loan") + Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/loan") + Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/repay") + Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/account") + Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/openOrders") + Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/margin/order") + Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/sapi/v1/margin/order") + Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/order") + Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/myTrades") + Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/sapi/v1/userDataStream") + Call startMarginUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/sapi/v1/userDataStream") + Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); } From 229060c2dfaab1613981187471a0defdbdc10d02 Mon Sep 17 00:00:00 2001 From: Truong Ha Date: Fri, 1 May 2020 12:45:43 +0700 Subject: [PATCH 3/8] Fixed issue with repay --- .../client/BinanceApiMarginRestClient.java | 17 ++++ .../api/client/domain/account/Loan.java | 3 - .../api/client/domain/account/Repay.java | 85 +++++++++++++++++++ .../domain/account/RepayQueryResult.java | 41 +++++++++ .../impl/BinanceApiMarginRestClientImpl.java | 12 +++ .../api/client/impl/BinanceApiService.java | 8 ++ ...arginAccountEndpointsLoanQueryExample.java | 25 +++--- 7 files changed, 175 insertions(+), 16 deletions(-) create mode 100755 src/main/java/com/binance/api/client/domain/account/Repay.java create mode 100755 src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java index 3e146ee39..527073b96 100755 --- a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -85,6 +85,21 @@ public interface BinanceApiMarginRestClient { */ MarginTransaction borrow(String asset, String amount); + /** + * Query loan record + * @param asset asset to query + * @return loan records + */ + RepayQueryResult queryRepay(String asset, long startTime); + + /** + * Query loan record + * @param asset asset to query + * @param txId the tranId in POST /sapi/v1/margin/repay + * @return loan records + */ + RepayQueryResult queryRepay(String asset, String txId); + /** * Repay loan for margin account * @param asset asset to repay @@ -100,4 +115,6 @@ public interface BinanceApiMarginRestClient { * @return loan records */ LoanQueryResult queryLoan(String asset, String txId); + + } diff --git a/src/main/java/com/binance/api/client/domain/account/Loan.java b/src/main/java/com/binance/api/client/domain/account/Loan.java index 5424c9b17..96389c269 100755 --- a/src/main/java/com/binance/api/client/domain/account/Loan.java +++ b/src/main/java/com/binance/api/client/domain/account/Loan.java @@ -1,10 +1,7 @@ package com.binance.api.client.domain.account; -import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.LoanStatus; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; /** * Represents an executed trade history item. diff --git a/src/main/java/com/binance/api/client/domain/account/Repay.java b/src/main/java/com/binance/api/client/domain/account/Repay.java new file mode 100755 index 000000000..22f3e7b0e --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Repay.java @@ -0,0 +1,85 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.domain.LoanStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Repay { + + private String amount; + private String asset; + private String interest; + private String principal; + LoanStatus status; + private long timestamp; + private String txId; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getInterest() { + return interest; + } + + public void setInterest(String interest) { + this.interest = interest; + } + + public String getPrincipal() { + return principal; + } + + public void setPrincipal(String principal) { + this.principal = principal; + } + + public LoanStatus getStatus() { + return status; + } + + public void setStatus(LoanStatus status) { + this.status = status; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getTxId() { + return txId; + } + + public void setTxId(String txId) { + this.txId = txId; + } + + @Override + public String toString() { + return "Repay{" + + "amount='" + amount + '\'' + + ", asset='" + asset + '\'' + + ", interest='" + interest + '\'' + + ", principal='" + principal + '\'' + + ", status=" + status + + ", timestamp=" + timestamp + + ", txId='" + txId + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java b/src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java new file mode 100755 index 000000000..4221e9df5 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java @@ -0,0 +1,41 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * History of account withdrawals. + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class RepayQueryResult { + + private int total; + private List rows; + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + public List getRows() { + return rows; + } + + public void setRows(List rows) { + this.rows = rows; + } + + @Override + public String toString() { + return "RepayQueryResult{" + + "total=" + total + + ", rows=" + rows + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java index 93bf3244d..5e88373e5 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -93,6 +93,18 @@ public LoanQueryResult queryLoan(String asset, String txId) { return executeSync(binanceApiService.queryLoan(asset, txId, timestamp)); } + @Override + public RepayQueryResult queryRepay(String asset, String txId) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryRepay(asset, txId, timestamp)); + } + + @Override + public RepayQueryResult queryRepay(String asset, long startTime) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryRepay(asset, startTime, timestamp)); + } + @Override public MarginTransaction repay(String asset, String amount) { long timestamp = System.currentTimeMillis(); diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 3a4220317..1640f90d7 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -182,6 +182,14 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @GET("/sapi/v1/margin/loan") Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) @POST("/sapi/v1/margin/repay") Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java index b9456722f..81d342212 100755 --- a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -2,23 +2,22 @@ import com.binance.api.client.BinanceApiClientFactory; import com.binance.api.client.BinanceApiMarginRestClient; -import com.binance.api.client.domain.TransferType; -import com.binance.api.client.domain.account.*; - -import java.util.List; +import com.binance.api.client.domain.account.MarginTransaction; +import com.binance.api.client.domain.account.RepayQueryResult; /** * Examples on how to get margin account information. */ public class MarginAccountEndpointsLoanQueryExample { - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiMarginRestClient client = factory.newMarginRestClient(); - MarginTransaction borrowed = client.borrow("USDT", "310"); - System.out.println(borrowed.getTranId()); - LoanQueryResult queryResult = client.queryLoan("USDT", borrowed.getTranId()); - Loan loan = queryResult.getRows().get(0); - System.out.println(loan.getStatus()); - } + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + MarginTransaction borrowed = client.borrow("USDT", "310"); + System.out.println(borrowed.getTranId()); + MarginTransaction repaid = client.repay("USDT", "310"); + System.out.println(repaid); + RepayQueryResult repayQueryResult = client.queryRepay("BNB", System.currentTimeMillis() - 1000); + System.out.println(repayQueryResult); + } } From 6b1a42f5ec7b1f7d209a65bbbccd029f4573276b Mon Sep 17 00:00:00 2001 From: Truong Ha Date: Fri, 1 May 2020 13:33:17 +0700 Subject: [PATCH 4/8] Added endpoint to get max borrowable --- .../client/BinanceApiMarginRestClient.java | 9 +++++- .../account/MaxBorrowableQueryResult.java | 31 +++++++++++++++++++ .../impl/BinanceApiMarginRestClientImpl.java | 6 ++++ .../api/client/impl/BinanceApiService.java | 4 +++ ...arginAccountEndpointsLoanQueryExample.java | 5 +++ 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100755 src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java index 527073b96..681a8db96 100755 --- a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -88,10 +88,17 @@ public interface BinanceApiMarginRestClient { /** * Query loan record * @param asset asset to query - * @return loan records + * @return repay records */ RepayQueryResult queryRepay(String asset, long startTime); + /** + * Query max borrowable + * @param asset asset to query + * @return max borrowable + */ + MaxBorrowableQueryResult queryMaxBorrowable(String asset); + /** * Query loan record * @param asset asset to query diff --git a/src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java b/src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java new file mode 100755 index 000000000..8a50fdea4 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java @@ -0,0 +1,31 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * Max Borrow Query Result + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class MaxBorrowableQueryResult { + + private String amount; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + @Override + public String toString() { + return "MaxBorrowQueryResult{" + + "amount='" + amount + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java index 5e88373e5..b4322fd70 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -105,6 +105,12 @@ public RepayQueryResult queryRepay(String asset, long startTime) { return executeSync(binanceApiService.queryRepay(asset, startTime, timestamp)); } + @Override + public MaxBorrowableQueryResult queryMaxBorrowable(String asset) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryMaxBorrowable(asset, timestamp)); + } + @Override public MarginTransaction repay(String asset, String amount) { long timestamp = System.currentTimeMillis(); diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 1640f90d7..60ca96488 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -186,6 +186,10 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @GET("/sapi/v1/margin/repay") Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/maxBorrowable") + Call queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) @GET("/sapi/v1/margin/repay") Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java index 81d342212..4cc4bf01f 100755 --- a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -3,6 +3,7 @@ import com.binance.api.client.BinanceApiClientFactory; import com.binance.api.client.BinanceApiMarginRestClient; import com.binance.api.client.domain.account.MarginTransaction; +import com.binance.api.client.domain.account.MaxBorrowableQueryResult; import com.binance.api.client.domain.account.RepayQueryResult; /** @@ -13,6 +14,10 @@ public class MarginAccountEndpointsLoanQueryExample { public static void main(String[] args) { BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); BinanceApiMarginRestClient client = factory.newMarginRestClient(); + MaxBorrowableQueryResult usdt = client.queryMaxBorrowable("USDT"); + System.out.println(usdt.getAmount()); + MaxBorrowableQueryResult bnb = client.queryMaxBorrowable("BNB"); + System.out.println(bnb.getAmount()); MarginTransaction borrowed = client.borrow("USDT", "310"); System.out.println(borrowed.getTranId()); MarginTransaction repaid = client.repay("USDT", "310"); From 8dea1864e2cdcc54766cd83e47ed88fcd1154c9e Mon Sep 17 00:00:00 2001 From: Fenix Date: Thu, 3 Sep 2020 20:28:41 +0700 Subject: [PATCH 5/8] Add filter MAX_POSITIION --- .../java/com/binance/api/client/domain/general/FilterType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 8dd26c46a..72ad3b41e 100755 --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -18,6 +18,7 @@ public enum FilterType { PERCENT_PRICE, MARKET_LOT_SIZE, MAX_NUM_ICEBERG_ORDERS, + MAX_POSITION, // Exchange EXCHANGE_MAX_NUM_ORDERS, From a7189e2547a43980dce0d0766733007ed7e74fd0 Mon Sep 17 00:00:00 2001 From: Ha Truong Date: Sun, 27 Sep 2020 11:08:39 +0700 Subject: [PATCH 6/8] Binance Liquid Swap endpoints --- .../api/client/BinanceApiClientFactory.java | 7 + .../api/client/BinanceApiSwapRestClient.java | 94 ++++ .../api/client/domain/SwapOperationType.java | 8 + .../api/client/domain/SwapRemoveType.java | 8 + .../api/client/domain/account/Liquidity.java | 102 +++++ .../account/LiquidityOperationRecord.java | 83 ++++ .../api/client/domain/account/Pool.java | 43 ++ .../client/domain/account/SwapHistory.java | 101 +++++ .../api/client/domain/account/SwapQuote.java | 81 ++++ .../api/client/domain/account/SwapRecord.java | 21 + .../api/client/domain/account/SwapStatus.java | 18 + .../api/client/impl/BinanceApiService.java | 422 ++++++++++-------- .../impl/BinanceApiServiceGenerator.java | 2 - .../impl/BinanceApiSwapRestClientImpl.java | 115 +++++ .../api/examples/SwapEndpointExample.java | 32 ++ 15 files changed, 960 insertions(+), 177 deletions(-) create mode 100755 src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java create mode 100644 src/main/java/com/binance/api/client/domain/SwapOperationType.java create mode 100644 src/main/java/com/binance/api/client/domain/SwapRemoveType.java create mode 100644 src/main/java/com/binance/api/client/domain/account/Liquidity.java create mode 100644 src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java create mode 100644 src/main/java/com/binance/api/client/domain/account/Pool.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapHistory.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapQuote.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapRecord.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapStatus.java create mode 100755 src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java create mode 100644 src/test/java/com/binance/api/examples/SwapEndpointExample.java diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java index a529e237c..842ad20d5 100755 --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -85,4 +85,11 @@ public BinanceApiMarginRestClient newMarginRestClient() { public BinanceApiWebSocketClient newWebSocketClient() { return new BinanceApiWebSocketClientImpl(getSharedClient()); } + + /** + * Creates a new synchronous/blocking Swap REST client. + */ + public BinanceApiSwapRestClient newSwapRestClient() { + return new BinanceApiSwapRestClientImpl(apiKey, secret); + } } diff --git a/src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java b/src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java new file mode 100755 index 000000000..f7baf2c2e --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java @@ -0,0 +1,94 @@ +package com.binance.api.client; + +import com.binance.api.client.domain.SwapRemoveType; +import com.binance.api.client.domain.account.*; +import retrofit2.Call; +import retrofit2.http.Query; + +import java.util.List; + +public interface BinanceApiSwapRestClient { + + /** + * Get metadata about all swap pools. + * + * @return + */ + List listAllSwapPools(); + + /** + * Get liquidity information and user share of a pool. + * + * @param poolId + * @return + */ + Liquidity getPoolLiquidityInfo(String poolId); + + /** + * Add liquidity to a pool. + * + * @param poolId + * @param asset + * @param quantity + * @return + */ + LiquidityOperationRecord addLiquidity(String poolId, + String asset, + String quantity); + + /** + * Remove liquidity from a pool, type include SINGLE and COMBINATION, asset is mandatory for single asset removal + * + * @param poolId + * @param type + * @param asset + * @param shareAmount + * @return + */ + LiquidityOperationRecord removeLiquidity(String poolId, SwapRemoveType type, List asset, String shareAmount); + + /** + * Get liquidity operation (add/remove) records of a pool + * + * @param poolId + * @param limit + * @return + */ + List getPoolLiquidityOperationRecords( + String poolId, + Integer limit); + + /** + * Get liquidity operation (add/remove) record. + * + * @param operationId + * @return + */ + LiquidityOperationRecord getLiquidityOperationRecord(String operationId); + + /** + * Request a quote for swap quote asset (selling asset) for base asset (buying asset), essentially price/exchange rates. + * + * @param quoteAsset + * @param baseAsset + * @param quoteQty + * @return + */ + SwapQuote requestQuote(String quoteAsset, + String baseAsset, + String quoteQty); + + /** + * Swap quoteAsset for baseAsset + * + * @param quoteAsset + * @param baseAsset + * @param quoteQty + * @return + */ + SwapRecord swap(String quoteAsset, + String baseAsset, + String quoteQty); + + SwapHistory getSwapHistory(String swapId); +} diff --git a/src/main/java/com/binance/api/client/domain/SwapOperationType.java b/src/main/java/com/binance/api/client/domain/SwapOperationType.java new file mode 100644 index 000000000..3561e5209 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/SwapOperationType.java @@ -0,0 +1,8 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SwapOperationType { + ADD, REMOVE +} diff --git a/src/main/java/com/binance/api/client/domain/SwapRemoveType.java b/src/main/java/com/binance/api/client/domain/SwapRemoveType.java new file mode 100644 index 000000000..64db76453 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/SwapRemoveType.java @@ -0,0 +1,8 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SwapRemoveType { + SINGLE, COMBINATION +} diff --git a/src/main/java/com/binance/api/client/domain/account/Liquidity.java b/src/main/java/com/binance/api/client/domain/account/Liquidity.java new file mode 100644 index 000000000..83eee88a3 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Liquidity.java @@ -0,0 +1,102 @@ +package com.binance.api.client.domain.account; + +import java.util.Map; + +public class Liquidity { + + private String poolId; + private String poolName; + private Long updateTime; + private Map liquidity; + private Share share; + + public String getPoolId() { + return poolId; + } + + public void setPoolId(String poolId) { + this.poolId = poolId; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + public Long getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Long updateTime) { + this.updateTime = updateTime; + } + + public Map getLiquidity() { + return liquidity; + } + + public void setLiquidity(Map liquidity) { + this.liquidity = liquidity; + } + + public Share getShare() { + return share; + } + + public void setShare(Share share) { + this.share = share; + } + + public static class Share { + private double shareAmount; + private double sharePercentage; + private Map asset; + + public double getShareAmount() { + return shareAmount; + } + + public void setShareAmount(double shareAmount) { + this.shareAmount = shareAmount; + } + + public double getSharePercentage() { + return sharePercentage; + } + + public void setSharePercentage(double sharePercentage) { + this.sharePercentage = sharePercentage; + } + + public Map getAsset() { + return asset; + } + + public void setAsset(Map asset) { + this.asset = asset; + } + + @Override + public String toString() { + return "Share{" + + "shareAmount=" + shareAmount + + ", sharePercentage=" + sharePercentage + + ", asset=" + asset + + '}'; + } + } + + @Override + public String toString() { + return "Liquidity{" + + "poolId=" + poolId + + ", poolName='" + poolName + '\'' + + ", updateTime=" + updateTime + + ", liquidity=" + liquidity + + ", share=" + share + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java new file mode 100644 index 000000000..65b68cf84 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java @@ -0,0 +1,83 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.domain.SwapOperationType; + +public class LiquidityOperationRecord { + + private String poolId; + private String operationId; + private String updateTime; + private String operation; + private String shareAmount; + private String poolName; + private SwapOperationType status; + + public String getPoolId() { + return poolId; + } + + public void setPoolId(String poolId) { + this.poolId = poolId; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getShareAmount() { + return shareAmount; + } + + public void setShareAmount(String shareAmount) { + this.shareAmount = shareAmount; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + public SwapOperationType getStatus() { + return status; + } + + public void setStatus(SwapOperationType status) { + this.status = status; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + @Override + public String toString() { + return "LiquidityOperationRecord{" + + "poolId='" + poolId + '\'' + + ", operationId='" + operationId + '\'' + + ", updateTime='" + updateTime + '\'' + + ", operation='" + operation + '\'' + + ", shareAmount='" + shareAmount + '\'' + + ", poolName='" + poolName + '\'' + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Pool.java b/src/main/java/com/binance/api/client/domain/account/Pool.java new file mode 100644 index 000000000..413d301f2 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Pool.java @@ -0,0 +1,43 @@ +package com.binance.api.client.domain.account; + +import java.util.List; + +public class Pool { + + private String poolId; + private String poolName; + private List assets; + + public String getPoolId() { + return poolId; + } + + public void setPoolId(String poolId) { + this.poolId = poolId; + } + + public List getAssets() { + return assets; + } + + public void setAssets(List assets) { + this.assets = assets; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + @Override + public String toString() { + return "Pool{" + + "poolId='" + poolId + '\'' + + ", poolName='" + poolName + '\'' + + ", assets=" + assets + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/SwapHistory.java b/src/main/java/com/binance/api/client/domain/account/SwapHistory.java new file mode 100644 index 000000000..b4c7c785c --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapHistory.java @@ -0,0 +1,101 @@ +package com.binance.api.client.domain.account; + +public class SwapHistory { + + private String quoteQty; + private Long swapTime; + private String swapId; + private String price; + private String fee; + private String baseQty; + private String baseAsset; + private String quoteAsset; + private SwapStatus status; + + public String getQuoteQty() { + return quoteQty; + } + + public void setQuoteQty(String quoteQty) { + this.quoteQty = quoteQty; + } + + public Long getSwapTime() { + return swapTime; + } + + public void setSwapTime(Long swapTime) { + this.swapTime = swapTime; + } + + public String getSwapId() { + return swapId; + } + + public void setSwapId(String swapId) { + this.swapId = swapId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getFee() { + return fee; + } + + public void setFee(String fee) { + this.fee = fee; + } + + public String getBaseQty() { + return baseQty; + } + + public void setBaseQty(String baseQty) { + this.baseQty = baseQty; + } + + public String getBaseAsset() { + return baseAsset; + } + + public void setBaseAsset(String baseAsset) { + this.baseAsset = baseAsset; + } + + public String getQuoteAsset() { + return quoteAsset; + } + + public void setQuoteAsset(String quoteAsset) { + this.quoteAsset = quoteAsset; + } + + public SwapStatus getStatus() { + return status; + } + + public void setStatus(SwapStatus status) { + this.status = status; + } + + @Override + public String toString() { + return "SwapHistory{" + + "quoteQty='" + quoteQty + '\'' + + ", swapTime=" + swapTime + + ", swapId='" + swapId + '\'' + + ", price='" + price + '\'' + + ", fee='" + fee + '\'' + + ", baseQty='" + baseQty + '\'' + + ", baseAsset='" + baseAsset + '\'' + + ", quoteAsset='" + quoteAsset + '\'' + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/SwapQuote.java b/src/main/java/com/binance/api/client/domain/account/SwapQuote.java new file mode 100644 index 000000000..c776750f8 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapQuote.java @@ -0,0 +1,81 @@ +package com.binance.api.client.domain.account; + +public class SwapQuote { + private String quoteQty; + private String price; + private String fee; + private String baseQty; + private String baseAsset; + private String slippage; + private String quoteAsset; + + public String getQuoteQty() { + return quoteQty; + } + + public void setQuoteQty(String quoteQty) { + this.quoteQty = quoteQty; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getFee() { + return fee; + } + + public void setFee(String fee) { + this.fee = fee; + } + + public String getBaseQty() { + return baseQty; + } + + public void setBaseQty(String baseQty) { + this.baseQty = baseQty; + } + + public String getBaseAsset() { + return baseAsset; + } + + public void setBaseAsset(String baseAsset) { + this.baseAsset = baseAsset; + } + + public String getSlippage() { + return slippage; + } + + public void setSlippage(String slippage) { + this.slippage = slippage; + } + + public String getQuoteAsset() { + return quoteAsset; + } + + public void setQuoteAsset(String quoteAsset) { + this.quoteAsset = quoteAsset; + } + + @Override + public String toString() { + return "SwapQuote{" + + "quoteQty='" + quoteQty + '\'' + + ", price='" + price + '\'' + + ", fee='" + fee + '\'' + + ", baseQty='" + baseQty + '\'' + + ", baseAsset='" + baseAsset + '\'' + + ", slippage='" + slippage + '\'' + + ", quoteAsset='" + quoteAsset + '\'' + + '}'; + } +} + diff --git a/src/main/java/com/binance/api/client/domain/account/SwapRecord.java b/src/main/java/com/binance/api/client/domain/account/SwapRecord.java new file mode 100644 index 000000000..085af3068 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapRecord.java @@ -0,0 +1,21 @@ +package com.binance.api.client.domain.account; + +public class SwapRecord { + + private String swapId; + + public String getSwapId() { + return swapId; + } + + public void setSwapId(String swapId) { + this.swapId = swapId; + } + + @Override + public String toString() { + return "SwapRecord{" + + "swapId='" + swapId + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/SwapStatus.java b/src/main/java/com/binance/api/client/domain/account/SwapStatus.java new file mode 100644 index 000000000..b1a0dc9eb --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapStatus.java @@ -0,0 +1,18 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonValue; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SwapStatus { + PENDING, + SUCCESS, + FAILED; + + @JsonValue + public int toValue() { + return ordinal(); + } +} + + diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 60ca96488..c940a370c 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -3,6 +3,7 @@ import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.OrderSide; import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.SwapRemoveType; import com.binance.api.client.domain.TimeInForce; import com.binance.api.client.domain.account.*; import com.binance.api.client.domain.account.request.CancelOrderResponse; @@ -32,210 +33,281 @@ */ public interface BinanceApiService { - // General endpoints + // General endpoints - @GET("/api/v1/ping") - Call ping(); + @GET("/api/v1/ping") + Call ping(); - @GET("/api/v1/time") - Call getServerTime(); + @GET("/api/v1/time") + Call getServerTime(); - @GET("/api/v1/exchangeInfo") - Call getExchangeInfo(); + @GET("/api/v1/exchangeInfo") + Call getExchangeInfo(); - @GET - Call> getAllAssets(@Url String url); + @GET + Call> getAllAssets(@Url String url); - // Market data endpoints + // Market data endpoints - @GET("/api/v1/depth") - Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); + @GET("/api/v1/depth") + Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); - @GET("/api/v1/trades") - Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); + @GET("/api/v1/trades") + Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @GET("/api/v1/historicalTrades") - Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @GET("/api/v1/historicalTrades") + Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); - @GET("/api/v1/aggTrades") - Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); + @GET("/api/v1/aggTrades") + Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); - @GET("/api/v1/klines") - Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); + @GET("/api/v1/klines") + Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); - @GET("/api/v1/ticker/24hr") - Call get24HrPriceStatistics(@Query("symbol") String symbol); + @GET("/api/v1/ticker/24hr") + Call get24HrPriceStatistics(@Query("symbol") String symbol); - @GET("/api/v1/ticker/24hr") - Call> getAll24HrPriceStatistics(); + @GET("/api/v1/ticker/24hr") + Call> getAll24HrPriceStatistics(); - @GET("/api/v1/ticker/allPrices") - Call> getLatestPrices(); + @GET("/api/v1/ticker/allPrices") + Call> getLatestPrices(); - @GET("/api/v3/ticker/price") - Call getLatestPrice(@Query("symbol") String symbol); + @GET("/api/v3/ticker/price") + Call getLatestPrice(@Query("symbol") String symbol); - @GET("/api/v1/ticker/allBookTickers") - Call> getBookTickers(); + @GET("/api/v1/ticker/allBookTickers") + Call> getBookTickers(); - // Account endpoints + // Account endpoints - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order") - Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order") - Call newOrderQuoteQty(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quoteOrderQty") String quoteOrderQty, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order/test") - Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/order") - Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, - @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @DELETE("/api/v3/order") - Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/openOrders") - Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/allOrders") - Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/account") - Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/myTrades") - Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/wapi/v3/withdraw.html") - Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order") + Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order") + Call newOrderQuoteQty(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quoteOrderQty") String quoteOrderQty, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositHistory.html") - Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order/test") + Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/withdrawHistory.html") - Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/order") + Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositAddress.html") - Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/api/v3/order") + Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - // User stream endpoints + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/openOrders") + Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @POST("/api/v1/userDataStream") - Call startUserDataStream(); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/allOrders") + Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @PUT("/api/v1/userDataStream") - Call keepAliveUserDataStream(@Query("listenKey") String listenKey); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/account") + Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @DELETE("/api/v1/userDataStream") - Call closeAliveUserDataStream(@Query("listenKey") String listenKey); - - // Margin Account endpoints - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @POST("/sapi/v1/margin/transfer") - Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @POST("/sapi/v1/margin/loan") - Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/loan") - Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/repay") - Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/maxBorrowable") - Call queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/myTrades") + Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/repay") - Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/wapi/v3/withdraw.html") + Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @POST("/sapi/v1/margin/repay") - Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/account") - Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositHistory.html") + Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/withdrawHistory.html") + Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositAddress.html") + Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + // User stream endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/api/v1/userDataStream") + Call startUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/api/v1/userDataStream") + Call keepAliveUserDataStream(@Query("listenKey") String listenKey); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @DELETE("/api/v1/userDataStream") + Call closeAliveUserDataStream(@Query("listenKey") String listenKey); + + // Margin Account endpoints + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/transfer") + Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/loan") + Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/loan") + Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/maxBorrowable") + Call queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/repay") + Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/account") + Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/openOrders") + Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/margin/order") + Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/sapi/v1/margin/order") + Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/order") + Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/myTrades") + Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/openOrders") - Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/sapi/v1/userDataStream") + Call startMarginUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/sapi/v1/userDataStream") + Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); + + // Binance Liquidity Swap Pool endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @GET("/sapi/v1/bswap/pools") + Call> listAllSwapPools(); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/liquidity") + Call> getPoolLiquidityInfo(@Query("poolId") String poolId, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/bswap/liquidityAdd") + Call addLiquidity(@Query("poolId") String poolId, + @Query("asset") String asset, + @Query("quantity") String quantity, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/bswap/liquidityRemove") + Call removeLiquidity(@Query("poolId") String poolId, + @Query("type") SwapRemoveType type, + @Query("asset") List asset, + @Query("shareAmount") String shareAmount, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/liquidityOps") + Call> getPoolLiquidityOperationRecords( + @Query("poolId") String poolId, + @Query("limit") Integer limit, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/liquidityOps") + Call> getLiquidityOperationRecord( + @Query("operationId") String operationId, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/quote") + Call requestQuote( + @Query("quoteAsset") String quoteAsset, + @Query("baseAsset") String baseAsset, + @Query("quoteQty") String quoteQty, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/bswap/swap") + Call swap( + @Query("quoteAsset") String quoteAsset, + @Query("baseAsset") String baseAsset, + @Query("quoteQty") String quoteQty, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/swap") + Call> getSwapHistory( + @Query("swapId") String swapId, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/sapi/v1/margin/order") - Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @DELETE("/sapi/v1/margin/order") - Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/sapi/v1/margin/order") - Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, - @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/sapi/v1/margin/myTrades") - Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @POST("/sapi/v1/userDataStream") - Call startMarginUserDataStream(); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @PUT("/sapi/v1/userDataStream") - Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 7bab3ad1e..1bd11a9e2 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -2,12 +2,10 @@ import com.binance.api.client.BinanceApiError; import com.binance.api.client.config.BinanceApiConfig; -import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.exception.BinanceApiException; import com.binance.api.client.security.AuthenticationInterceptor; import okhttp3.Dispatcher; import okhttp3.OkHttpClient; -import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.apache.commons.lang3.StringUtils; import retrofit2.Call; diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java new file mode 100755 index 000000000..4f1a18bc4 --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java @@ -0,0 +1,115 @@ +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiSwapRestClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.SwapRemoveType; +import com.binance.api.client.domain.account.*; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; + +/** + * Implementation of Binance's SWAP REST API using Retrofit method calls. + */ +public class BinanceApiSwapRestClientImpl implements BinanceApiSwapRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiSwapRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + @Override + public List listAllSwapPools() { + return executeSync(binanceApiService.listAllSwapPools()); + } + + @Override + public Liquidity getPoolLiquidityInfo(String poolId) { + long timestamp = System.currentTimeMillis(); + List liquidities = executeSync(binanceApiService.getPoolLiquidityInfo(poolId, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + if (liquidities != null && !liquidities.isEmpty()) { + return liquidities.get(0); + } + return null; + } + + @Override + public LiquidityOperationRecord addLiquidity(String poolId, String asset, String quantity) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.addLiquidity(poolId, + asset, + quantity, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public LiquidityOperationRecord removeLiquidity(String poolId, SwapRemoveType type, List asset, String shareAmount) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.removeLiquidity(poolId, + type, + asset, + shareAmount, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public List getPoolLiquidityOperationRecords(String poolId, Integer limit) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.getPoolLiquidityOperationRecords( + poolId, + limit, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + + } + + @Override + public LiquidityOperationRecord getLiquidityOperationRecord(String operationId) { + long timestamp = System.currentTimeMillis(); + List records = executeSync(binanceApiService.getLiquidityOperationRecord( + operationId, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + if (records != null && !records.isEmpty()) { + return records.get(0); + } + return null; + } + + @Override + public SwapQuote requestQuote(String quoteAsset, + String baseAsset, + String quoteQty) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.requestQuote(quoteAsset, baseAsset, quoteQty, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public SwapRecord swap(String quoteAsset, String baseAsset, String quoteQty) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.swap(quoteAsset, baseAsset, quoteQty, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public SwapHistory getSwapHistory(String swapId) { + long timestamp = System.currentTimeMillis(); + List history = executeSync(binanceApiService.getSwapHistory(swapId, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + if (history != null && !history.isEmpty()) { + return history.get(0); + } + return null; + } +} \ No newline at end of file diff --git a/src/test/java/com/binance/api/examples/SwapEndpointExample.java b/src/test/java/com/binance/api/examples/SwapEndpointExample.java new file mode 100644 index 000000000..c4c32d98d --- /dev/null +++ b/src/test/java/com/binance/api/examples/SwapEndpointExample.java @@ -0,0 +1,32 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiSwapRestClient; +import com.binance.api.client.domain.account.*; + +import java.util.List; + +public class SwapEndpointExample { + + public static String API_KEY = "api-key"; + public static String SECRET_KEY = "secret-key"; + + public static void main(String[] args) { + + BinanceApiClientFactory binanceApiClientFactory = BinanceApiClientFactory.newInstance(API_KEY, SECRET_KEY); + BinanceApiSwapRestClient swapClient = binanceApiClientFactory.newSwapRestClient(); + List pools = swapClient.listAllSwapPools(); + for(Pool pool:pools) { + System.out.println(pool); + Liquidity poolLiquidityInfo = swapClient.getPoolLiquidityInfo(pool.getPoolId()); + System.out.println(poolLiquidityInfo); + } + SwapQuote swapQuote = swapClient.requestQuote("USDT", "USDC", "10"); + System.out.println(swapQuote); + SwapRecord swapRecord = swapClient.swap("USDT", "USDC", "10"); + SwapHistory swapHistory = swapClient.getSwapHistory(swapRecord.getSwapId()); + System.out.println(swapHistory); + } + + +} From 8524e77dd48bb3ba87fbb95326a232a67d8a3469 Mon Sep 17 00:00:00 2001 From: Fenix Date: Sun, 27 Sep 2020 21:49:31 +0700 Subject: [PATCH 7/8] Fixed issue with status value --- .../domain/LiquidityOperationRecordStatus.java | 16 ++++++++++++++++ .../api/client/domain/SwapOperationType.java | 8 -------- .../domain/account/LiquidityOperationRecord.java | 8 ++++---- 3 files changed, 20 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java delete mode 100644 src/main/java/com/binance/api/client/domain/SwapOperationType.java diff --git a/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java b/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java new file mode 100644 index 000000000..2574a38e3 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java @@ -0,0 +1,16 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonValue; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum LiquidityOperationRecordStatus { + PENDING, + SUCCESS, + FAILED; + + @JsonValue + public int toValue() { + return ordinal(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/SwapOperationType.java b/src/main/java/com/binance/api/client/domain/SwapOperationType.java deleted file mode 100644 index 3561e5209..000000000 --- a/src/main/java/com/binance/api/client/domain/SwapOperationType.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public enum SwapOperationType { - ADD, REMOVE -} diff --git a/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java index 65b68cf84..2ce393f1c 100644 --- a/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java +++ b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java @@ -1,6 +1,6 @@ package com.binance.api.client.domain.account; -import com.binance.api.client.domain.SwapOperationType; +import com.binance.api.client.domain.LiquidityOperationRecordStatus; public class LiquidityOperationRecord { @@ -10,7 +10,7 @@ public class LiquidityOperationRecord { private String operation; private String shareAmount; private String poolName; - private SwapOperationType status; + private LiquidityOperationRecordStatus status; public String getPoolId() { return poolId; @@ -52,11 +52,11 @@ public void setPoolName(String poolName) { this.poolName = poolName; } - public SwapOperationType getStatus() { + public LiquidityOperationRecordStatus getStatus() { return status; } - public void setStatus(SwapOperationType status) { + public void setStatus(LiquidityOperationRecordStatus status) { this.status = status; } From c9ff0d997f2e6a375551aefb89ecb2a942b27cff Mon Sep 17 00:00:00 2001 From: Fenix Date: Sat, 3 Oct 2020 10:47:29 +0700 Subject: [PATCH 8/8] no message --- .../domain/account/CrossMarginAssets.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java diff --git a/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java b/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java new file mode 100644 index 000000000..33c5fd906 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java @@ -0,0 +1,74 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CrossMarginAssets { + + public String assetFullName; + public String assetName; + public boolean isBorrowable; + public boolean isMortgageable; + public String userMinBorrow; + public String userMinRepay; + + public String getAssetFullName() { + return assetFullName; + } + + public void setAssetFullName(String assetFullName) { + this.assetFullName = assetFullName; + } + + public String getAssetName() { + return assetName; + } + + public void setAssetName(String assetName) { + this.assetName = assetName; + } + + public boolean isBorrowable() { + return isBorrowable; + } + + public void setBorrowable(boolean borrowable) { + isBorrowable = borrowable; + } + + public boolean isMortgageable() { + return isMortgageable; + } + + public void setMortgageable(boolean mortgageable) { + isMortgageable = mortgageable; + } + + public String getUserMinBorrow() { + return userMinBorrow; + } + + public void setUserMinBorrow(String userMinBorrow) { + this.userMinBorrow = userMinBorrow; + } + + public String getUserMinRepay() { + return userMinRepay; + } + + public void setUserMinRepay(String userMinRepay) { + this.userMinRepay = userMinRepay; + } + + @Override + public String toString() { + return "CrossMarginAssets{" + + "assetFullName='" + assetFullName + '\'' + + ", assetName='" + assetName + '\'' + + ", isBorrowable=" + isBorrowable + + ", isMortgageable=" + isMortgageable + + ", userMinBorrow='" + userMinBorrow + '\'' + + ", userMinRepay='" + userMinRepay + '\'' + + '}'; + } +}