diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 46e008f74..ef8668215 --- a/README.md +++ b/README.md @@ -1,488 +1,5 @@ -# Java Binance API +# Discontinue this Library -binance-java-api is a lightweight Java library for interacting with the [Binance API](https://www.binance.com/restapipub.html), providing complete API coverage, and supporting synchronous and asynchronous requests, as well as event streaming using WebSockets. +The support to this library is scheduled to be discontinued, and it will be offline within the next six months. -## Features -* Support for synchronous and asynchronous REST requests to all [General](https://www.binance.com/restapipub.html#user-content-general-endpoints), [Market Data](https://www.binance.com/restapipub.html#user-content-market-data-endpoints), [Account](https://www.binance.com/restapipub.html#user-content-account-endpoints) endpoints, and [User](https://www.binance.com/restapipub.html#user-content-user-data-stream-endpoints) stream endpoints. -* Support for User Data, Trade, Kline, and Depth event streaming using [Binance WebSocket API](https://www.binance.com/restapipub.html#wss-endpoint). - -## Installation -1. Install library into your Maven's local repository by running `mvn install` -2. Add the following Maven dependency to your project's `pom.xml`: -``` - - com.binance.api - binance-api-client - 1.0.0 - -``` - -Alternatively, you can clone this repository and run the [examples](https://github.com/joaopsilva/binance-java-api/tree/master/src/test/java/com/binance/api/examples). - -## Examples - -### Getting Started - -There are three main client classes that can be used to interact with the API: - -1. [`BinanceApiRestClient`](https://github.com/joaopsilva/binance-java-api/blob/master/src/main/java/com/binance/api/client/BinanceApiRestClient.java), a synchronous/blocking [Binance API](https://www.binance.com/restapipub.html) client; -2. [`BinanceApiAsyncRestClient`](https://github.com/joaopsilva/binance-java-api/blob/master/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java), an asynchronous/non-blocking [Binance API](https://www.binance.com/restapipub.html) client; -3. [`BinanceApiWebSocketClient`](https://github.com/joaopsilva/binance-java-api/blob/master/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java), a data streaming client using [Binance WebSocket API](https://www.binance.com/restapipub.html#wss-endpoint). - -These can be instantiated through the corresponding factory method of [`BinanceApiClientFactory`](https://github.com/joaopsilva/binance-java-api/blob/master/src/main/java/com/binance/api/client/BinanceApiClientFactory.java), by passing the [security parameters](https://www.binance.com/restapipub.html#user-content-endpoint-security-type) `API-KEY` and `SECRET`, which can be created at [https://www.binance.com/userCenter/createApi.html](https://www.binance.com/userCenter/createApi.html). - -```java -BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("API-KEY", "SECRET"); -BinanceApiRestClient client = factory.newRestClient(); -``` - -If the client only needs to access endpoints which do not require additional security, then these parameters are optional. - -Once the client is instantiated, it is possible to start making requests to the API. - -### General endpoints - -#### Test connectivity -```java -client.ping(); -``` -#### Check server time -```java -long serverTime = client.getServerTime(); -System.out.println(serverTime); -``` -
- View Response - -```java -1508380346873 -``` -
- -### Market Data endpoints - -#### Order book of a symbol -```java -OrderBook orderBook = client.getOrderBook("NEOETH", 10); -List asks = orderBook.getAsks(); -OrderBookEntry firstAskEntry = asks.get(0); -System.out.println(firstAskEntry.getPrice() + " / " + firstAskEntry.getQty()); -``` -
- View Response - - ```java -0.09200000 / 5.52000000 -``` -
- -#### Compressed/Aggregate trades list of a symbol -```java -List aggTrades = client.getAggTrades("NEOETH"); -System.out.println(aggTrades); -``` -
- View Response - - ```java -[AggTrade[aggregatedTradeId=30593,price=0.09880800,quantity=40.89000000,firstBreakdownTradeId=33363,lastBreakdownTradeId=33363,tradeTime=1508331041246,isBuyerMaker=true], ...] -``` -
- -#### Weekly candlestick bars for a symbol -```java -List candlesticks = client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY); -System.out.println(candlesticks); -``` -
- View Response - - ```java -[Candlestick[openTime=1506297600000,open=0.09700000,high=0.12000100,low=0.05500000,close=0.11986900,volume=25709.37000000,closeTime=1506902399999,quoteAssetVolume=2649.80091051,numberOfTrades=2435,takerBuyBaseAssetVolume=10520.59000000,takerBuyQuoteAssetVolume=1101.94985388], ...] -``` -
- -#### Latest price of a symbol -```java -TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH"); -System.out.println(tickerStatistics.getLastPrice()); -``` -
- View Response - - ```java -0.09100100 -``` -
- -#### Getting all latests prices -```java -List allPrices = client.getAllPrices(); -System.out.println(allPrices); -``` -
- View Response - - ```java -[TickerPrice[symbol=ETHBTC,price=0.05590400], TickerPrice[symbol=LTCBTC,price=0.01073300], ...] -``` -
- -### Account Data endpoints - -#### Get account balances -```java -Account account = client.getAccount(); -System.out.println(account.getBalances()); -System.out.println(account.getAssetBalance("ETH").getFree()); -``` -
- View Response - - ```java -AssetBalance[asset=ETH,free=0.10000000,locked=0.00000000] -0.10000000 -``` -
- -#### Get list of trades for an account and a symbol -```java -List myTrades = client.getMyTrades("NEOETH"); -System.out.println(myTrades); -``` -
- View Response - - ```java -[Trade[id=123,price=0.00000100,qty=1000.00000000,commission=0.00172100,commissionAsset=ETH,time=1507927870561,buyer=false,maker=false,bestMatch=true,symbol=,orderId=11289], Trade[id=123,price=0.00001000,qty=3.00000000,commission=0.00000003,commissionAsset=ETH,time=1507927874215,buyer=false,maker=false,bestMatch=true,symbol=,orderId=123]] -``` -
- -#### Get account open orders for a symbol -```java -List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); -System.out.println(openOrders); -``` -
- View Response - - ```java -[Order[symbol=LINKETH,orderId=12345,clientOrderId=XYZ,price=0.00010000,origQty=1000.00000000,executedQty=0.00000000,status=NEW,timeInForce=GTC,type=LIMIT,side=BUY,stopPrice=0.00000000,icebergQty=0.00000000,time=1508382291552]] -``` -
- -#### Get order status -```java -Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 12345L)); -System.out.println(order.getExecutedQty()); -``` -
- View Response - - ```java -0.00000000 -``` -
- -#### Placing a MARKET order -```java -NewOrderResponse newOrderResponse = client.newOrder(marketBuy("LINKETH", "1000")); -System.out.println(newOrderResponse.getClientOrderId()); -``` -
- View Response - - ```java -XXXXXfc2XXzTXXGs66ZcXX -``` -
- -#### Placing a LIMIT order -```java -NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001")); -System.out.println(newOrderResponse.getTransactTime()); -``` -
- View Response - - ```java -1508382322725 -``` -
- -#### Canceling an order -```java -client.cancelOrder(new CancelOrderRequest("LINKETH", 123015L)); -``` - -#### Withdraw - -In order to be able to withdraw programatically, please enable the `Enable Withdrawals` option in the API settings. - -```java -client.withdraw("ETH", "0x123", "0.1", null); -``` - -#### Fetch withdraw history - -```java -WithdrawHistory withdrawHistory = client.getWithdrawHistory("ETH"); -System.out.println(withdrawHistory); -``` -
- View Response - - ```java -WithdrawHistory[withdrawList=[Withdraw[amount=0.1,address=0x123,asset=ETH,applyTime=2017-10-13 20:59:38,successTime=2017-10-13 21:20:09,txId=0x456,id=789]],success=true] -``` -
- -#### Fetch deposit history -```java -DepositHistory depositHistory = client.getDepositHistory("ETH"); -System.out.println(depositHistory); -``` -
- View Response - - ```java -DepositHistory[depositList=[Deposit[amount=0.100000000000000000,asset=ETH,insertTime=2017-10-18 13:03:39], Deposit[amount=1.000000000000000000,asset=NEO,insertTime=2017-10-13 20:24:04]],success=true] -``` -
- -#### Get deposit address -```java -DepositAddress depositAddress = client.getDepositAddress("ETH"); -System.out.println(depositAddress); -``` -
- View Response - - ```java -DepositAddress[address=0x99...,success=true,addressTag=,asset=ETH] -``` -
- -### User stream endpoints - -#### Start user data stream, keepalive, and close data stream -```java -String listenKey = client.startUserDataStream(); -client.keepAliveUserDataStream(listenKey); -client.closeUserDataStream(listenKey); -``` - -### WebSocket API - -#### Initialize the WebSocket client -```java -BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient(); -``` - -#### Handling web socket errors - -Each of the methods on `BinanceApiWebSocketClient`, which opens a new web socket, takes a `BinanceApiCallback`, which is -called for each event received from the Binance servers. - -The `BinanceApiCallback` interface also has a `onFailure(Throwable)` method, which, optionally, can be implemented to -receive notifications if the web-socket fails, e.g. disconnection. - -```java -client.onAggTradeEvent(symbol.toLowerCase(), new BinanceApiCallback() { - @Override - public void onResponse(final AggTradeEvent response) { - System.out.println(response); - } - - @Override - public void onFailure(final Throwable cause) { - System.err.println("Web socket failed"); - cause.printStackTrace(System.err); - } -}); -``` - -#### Closing web sockets - -Each of the methods on `BinanceApiWebSocketClient`, which opens a new web socket, also returns a `Closeable`. -This `Closeable` can be used to close the underlying web socket and free any associated resources, e.g. - -```java -Closable ws = client.onAggTradeEvent("ethbtc", someCallback); -// some time later... -ws.close(); -``` - -#### Listen for aggregated trade events for ETH/BTC -```java -client.onAggTradeEvent("ethbtc", (AggTradeEvent response) -> { - System.out.println(response.getPrice()); - System.out.println(response.getQuantity()); -}); -``` -
- View Response - - ```java -0.05583500 / 1.06400000 -1508383333069 -0.05557200 / 2.00000000 -1508383345070 -0.05583200 / 2.68500000 -1508383352961 -... -``` -
- -#### Listen for changes in the order book for ETH/BTC -```java -client.onDepthEvent("ethbtc", (DepthEvent response) -> { - System.out.println(response.getAsks()); -}); -``` -
- View Response - - ```java -[OrderBookEntry[price=0.05559500,qty=7.94200000], OrderBookEntry[price=0.05559800,qty=0.00000000]] -[OrderBookEntry[price=0.05558400,qty=30.61800000], OrderBookEntry[price=0.05559500,qty=0.00000000], OrderBookEntry[price=0.05560600,qty=8.32100000]] -[OrderBookEntry[price=0.05559100,qty=7.86600000], OrderBookEntry[price=0.05560600,qty=0.00000000], OrderBookEntry[price=0.05607700,qty=5.15500000], OrderBookEntry[price=0.05620700,qty=0.00000000], OrderBookEntry[price=0.05842200,qty=0.00000000]] -[OrderBookEntry[price=0.05558400,qty=29.61700000]] -... -``` -
- -#### Get 1m candlesticks in real-time for ETH/BTC -```java -client.onCandlestickEvent("ethbtc", CandlestickInterval.ONE_MINUTE, response -> System.out.println(response)); -``` -
- View Response - - ```java -CandlestickEvent[eventType=kline,eventTime=1508417055113,symbol=ETHBTC,openTime=1508417040000,open=0.05376300,high=0.05376300,low=0.05372900,close=0.05372900,volume=0.49400000,closeTime=1508417099999,intervalId=1m,firstTradeId=2199019,lastTradeId=2199020,quoteAssetVolume=0.02654552,numberOfTrades=2,takerBuyBaseAssetVolume=0.00000000,takerBuyQuoteAssetVolume=0.00000000,isBarFinal=false] -CandlestickEvent[eventType=kline,eventTime=1508417055145,symbol=ETHBTC,openTime=1508417040000,open=0.05376300,high=0.05376300,low=0.05371700,close=0.05371700,volume=0.62900000,closeTime=1508417099999,intervalId=1m,firstTradeId=2199019,lastTradeId=2199021,quoteAssetVolume=0.03379731,numberOfTrades=3,takerBuyBaseAssetVolume=0.00000000,takerBuyQuoteAssetVolume=0.00000000,isBarFinal=false] -CandlestickEvent[eventType=kline,eventTime=1508417096085,symbol=ETHBTC,openTime=1508417040000,open=0.05376300,high=0.05376300,low=0.05370900,close=0.05370900,volume=0.68000000,closeTime=1508417099999,intervalId=1m,firstTradeId=2199019,lastTradeId=2199022,quoteAssetVolume=0.03653646,numberOfTrades=4,takerBuyBaseAssetVolume=0.00000000,takerBuyQuoteAssetVolume=0.00000000,isBarFinal=false] -... -``` -
- -#### Keep a local depth cache for a symbol - -Please see [DepthCacheExample.java](https://github.com/joaopsilva/binance-java-api/blob/master/src/test/java/com/binance/api/examples/DepthCacheExample.java) for an implementation which uses the binance-java-api for maintaining a local depth cache for a symbol. In the same folder, you can also find how to do caching of account balances, aggregated trades, and klines/candlesticks. - -
- View Response - - ```java -ASKS: -0.05690700 / 6.15100000 -0.05447800 / 0.09500000 -0.05447700 / 28.22000000 -0.05439000 / 0.54500000 -0.05438400 / 1.10300000 -0.05436600 / 0.06100000 -0.05434000 / 0.05500000 -0.05432800 / 3.45100000 -0.05422700 / 1.11100000 -0.05410600 / 5.85900000 -0.05409300 / 4.50000000 -BIDS: -0.05390000 / 2.26000000 -0.05389000 / 15.00000000 -0.05385600 / 1.95000000 -0.05367900 / 0.10000000 -0.05366700 / 2.27600000 -0.05360000 / 10.96100000 -0.05348500 / 14.04000000 -0.05345000 / 0.56100000 -0.05336200 / 21.10000000 -0.05336100 / 21.15000000 -0.05306600 / 0.21100000 -0.05116300 / 10.95000000 -BEST ASK: 0.05409300 / 4.50000000 -BEST BID: 0.05390000 / 2.26000000 -... -``` -
- -#### Listen for changes in the account - -```java -client.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) { - AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent(); - - // Print new balances of every available asset - System.out.println(accountUpdateEvent.getBalances()); - } else { - OrderTradeUpdateEvent orderTradeUpdateEvent = response.getOrderTradeUpdateEvent(); - - // Print details about an order/trade - System.out.println(orderTradeUpdateEvent); - - // Print original quantity - System.out.println(orderTradeUpdateEvent.getOriginalQuantity()); - - // Or price - System.out.println(orderTradeUpdateEvent.getPrice()); - } -}); -``` - -### Asynchronous requests - -To make an asynchronous request it is necessary to use the `BinanceApiAsyncRestClient`, and call the method with the same name as in the synchronous version, but passing a callback [`BinanceApiCallback`](https://github.com/joaopsilva/binance-java-api/blob/master/src/main/java/com/binance/api/client/BinanceApiCallback.java) that handles the response whenever it arrives. - -#### Get latest price of a symbol asynchronously -```java -client.get24HrPriceStatistics("NEOETH", (TickerStatistics response) -> { - System.out.println(response.getLastPrice()); - System.out.println(response.getVolume()); -}); -``` -
- View Response - - ```java -0.09100100 -``` -
- -#### Placing a LIMIT order asynchronously -```java -client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), (NewOrderResponse response) -> { - System.out.println(response.getTransactTime()); -}); -``` -
- View Response - - ```java -1508382322725 -``` -
- -### Exception handling - -Every API method can potentially throw an unchecked `BinanceApiException` which wraps the error message returned from the Binance API, or an exception, in case the request never properly reached the server. - -```java -try { - client.getOrderBook("UNKNOWN", 10); -} catch (BinanceApiException e) { - System.out.println(e.getError().getCode()); // -1121 - System.out.println(e.getError().getMsg()); // Invalid symbol -} -``` -
- View Response - -```java --1121 -Invalid symbol -``` -
- -### More examples -An extensive set of examples, covering most aspects of the API, can be found at https://github.com/joaopsilva/binance-java-api/tree/master/src/test/java/com/binance/api/examples. +Please consider this offically supported Java library available at https://github.com/binance/binance-connector-java diff --git a/pom.xml b/pom.xml old mode 100644 new mode 100755 index f940bff48..67e7af532 --- a/pom.xml +++ b/pom.xml @@ -6,10 +6,16 @@ com.binance.api binance-api-client - 1.0.0 + 1.0.1 + + + The MIT License + https://opensource.org/licenses/MIT + + - 2.3.0 + 2.4.0 @@ -26,17 +32,17 @@ commons-codec commons-codec - 1.10 + 1.15 org.apache.commons commons-lang3 - 3.6 + 3.12.0 junit junit - 4.12 + 4.13.2 test @@ -54,4 +60,4 @@ - \ No newline at end of file + 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..8d1d8486f --- /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(MarginNewOrder 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 4916e16e6..d0e3b1c01 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -9,11 +9,14 @@ 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; @@ -27,7 +30,7 @@ import java.util.List; /** - * Binance API façade, supporting asynchronous/non-blocking access Binance's REST API. + * Binance API facade, supporting asynchronous/non-blocking access Binance's REST API. */ public interface BinanceApiAsyncRestClient { @@ -48,6 +51,11 @@ public interface BinanceApiAsyncRestClient { */ void getExchangeInfo(BinanceApiCallback callback); + /** + * ALL supported assets and whether or not they can be withdrawn. + */ + void getAllAssets(BinanceApiCallback> callback); + // Market Data endpoints /** @@ -63,7 +71,7 @@ public interface BinanceApiAsyncRestClient { * Get recent trades (up to last 500). Weight: 1 * * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 500.) + * @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); @@ -72,7 +80,7 @@ public interface BinanceApiAsyncRestClient { * Get older trades. Weight: 5 * * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 500.) + * @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 */ @@ -87,7 +95,7 @@ public interface BinanceApiAsyncRestClient { * * @param symbol symbol to aggregate (mandatory) * @param fromId ID to get aggregate trades from INCLUSIVE (optional) - * @param limit Default 500; max 500 (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 @@ -107,7 +115,7 @@ public interface BinanceApiAsyncRestClient { * * @param symbol symbol to aggregate (mandatory) * @param interval candlestick interval (mandatory) - * @param limit Default 500; max 500 (optional) + * @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 @@ -190,7 +198,7 @@ public interface BinanceApiAsyncRestClient { * @param cancelOrderRequest order status request parameters * @param callback the callback that handles the response */ - void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); + void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); /** * Get all open orders on a symbol (asynchronous). @@ -222,7 +230,7 @@ public interface BinanceApiAsyncRestClient { * Get trades for a specific account and symbol. * * @param symbol symbol to get trades from - * @param limit default 500; max 500 + * @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 */ @@ -232,7 +240,7 @@ public interface BinanceApiAsyncRestClient { * Get trades for a specific account and symbol. * * @param symbol symbol to get trades from - * @param limit default 500; max 500 + * @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); @@ -254,8 +262,9 @@ public interface BinanceApiAsyncRestClient { * @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, BinanceApiCallback callback); + void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback); /** * Fetch account deposit history. 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 b00d986c2..7ba5551bb --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -1,73 +1,138 @@ -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; - -/** - * 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(); - } -} +package com.binance.api.client; + +import com.binance.api.client.impl.*; +import com.binance.api.client.config.BinanceApiConfig; +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; + BinanceApiConfig.useTestnet = false; + BinanceApiConfig.useTestnetStreaming = false; + } + + /** + * Instantiates a new binance api client factory. + * + * @param apiKey the API key + * @param secret the Secret + * @param useTestnet true if endpoint is spot test network URL; false if endpoint is production spot API URL. + * @param useTestnetStreaming true for spot test network websocket streaming; false for no streaming. + */ + private BinanceApiClientFactory(String apiKey, String secret, boolean useTestnet, boolean useTestnetStreaming) { + this(apiKey, secret); + if (useTestnet) { + BinanceApiConfig.useTestnet = true; + BinanceApiConfig.useTestnetStreaming = useTestnetStreaming; } + } + + /** + * 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 with optional Spot Test Network endpoint. + * + * @param apiKey the API key + * @param secret the Secret + * @param useTestnet true if endpoint is spot test network URL; false if endpoint is production spot API URL. + * @param useTestnetStreaming true for spot test network websocket streaming; false for no streaming. + * + * @return the binance api client factory. + */ + public static BinanceApiClientFactory newInstance(String apiKey, String secret, boolean useTestnet, boolean useTestnetStreaming) { + return new BinanceApiClientFactory(apiKey, secret, useTestnet, useTestnetStreaming); + } + + /** + * New instance without authentication. + * + * @return the binance api client factory + */ + public static BinanceApiClientFactory newInstance() { + return new BinanceApiClientFactory(null, null); + } + + /** + * New instance without authentication and with optional Spot Test Network endpoint. + * + * @param useTestnet true if endpoint is spot test network URL; false if endpoint is production spot API URL. + * @param useTestnetStreaming true for spot test network websocket streaming; false for no streaming. + * + * @return the binance api client factory. + */ + public static BinanceApiClientFactory newInstance(boolean useTestnet, boolean useTestnetStreaming) { + return new BinanceApiClientFactory(null, null, useTestnet, useTestnetStreaming); + } + + /** + * 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()); + } + + /** + * 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/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..6f100a365 --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -0,0 +1,127 @@ +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. + */ + MarginNewOrderResponse newOrder(MarginNewOrder 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); + + /** + * Query loan record + * @param asset asset to query + * @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 + * @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 + * @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 97669356b..ebe0b9667 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -1,19 +1,9 @@ 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.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 com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.*; 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; @@ -25,7 +15,7 @@ import java.util.List; /** - * Binance API façade, supporting synchronous/blocking access Binance's REST API. + * Binance API facade, supporting synchronous/blocking access Binance's REST API. */ public interface BinanceApiRestClient { @@ -48,6 +38,11 @@ public interface BinanceApiRestClient { */ ExchangeInfo getExchangeInfo(); + /** + * @return All the supported assets and whether or not they can be withdrawn. + */ + List getAllAssets(); + // Market Data endpoints /** @@ -62,7 +57,7 @@ public interface BinanceApiRestClient { * Get recent trades (up to last 500). Weight: 1 * * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 500.) + * @param limit of last trades (Default 500; max 1000.) */ List getTrades(String symbol, Integer limit); @@ -70,7 +65,7 @@ public interface BinanceApiRestClient { * Get older trades. Weight: 5 * * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 500.) + * @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); @@ -84,7 +79,7 @@ public interface BinanceApiRestClient { * * @param symbol symbol to aggregate (mandatory) * @param fromId ID to get aggregate trades from INCLUSIVE (optional) - * @param limit Default 500; max 500 (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 @@ -103,7 +98,7 @@ public interface BinanceApiRestClient { * * @param symbol symbol to aggregate (mandatory) * @param interval candlestick interval (mandatory) - * @param limit Default 500; max 500 (optional) + * @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 @@ -123,7 +118,7 @@ public interface BinanceApiRestClient { * @param symbol ticker symbol (e.g. ETHBTC) */ TickerStatistics get24HrPriceStatistics(String symbol); - + /** * Get 24 hour price change statistics for all symbols. */ @@ -133,10 +128,10 @@ public interface BinanceApiRestClient { * Get Latest price for all symbols. */ List getAllPrices(); - + /** * Get latest price for symbol. - * + * * @param symbol ticker symbol (e.g. ETHBTC) */ TickerPrice getPrice(String symbol); @@ -176,7 +171,7 @@ public interface BinanceApiRestClient { * * @param cancelOrderRequest order status request parameters */ - void cancelOrder(CancelOrderRequest cancelOrderRequest); + CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); /** * Get all open orders on a symbol. @@ -194,6 +189,38 @@ public interface BinanceApiRestClient { */ List getAllOrders(AllOrdersRequest orderRequest); + /** + * Send in a new OCO; + * + * @param oco + * the OCO to submit + * @return a response containing details about the newly placed OCO. + */ + NewOCOResponse newOCO(NewOCO oco); + + /** + * Cancel an entire Order List + * + * @return + */ + CancelOrderListResponse cancelOrderList(CancelOrderListRequest cancelOrderListRequest); + + /** + * Check an order list status + * + * @param orderListStatusRequest + * @return an orderList + */ + OrderList getOrderListStatus(OrderListStatusRequest orderListStatusRequest); + + /** + * Get all list os orders + * + * @param allOrderListRequest + * @return + */ + List getAllOrderList(AllOrderListRequest allOrderListRequest); + /** * Get current account information. */ @@ -208,7 +235,7 @@ public interface BinanceApiRestClient { * Get trades for a specific account and symbol. * * @param symbol symbol to get trades from - * @param limit default 500; max 500 + * @param limit default 500; max 1000 * @param fromId TradeId to fetch from. Default gets most recent trades. * @return a list of trades */ @@ -218,7 +245,7 @@ public interface BinanceApiRestClient { * Get trades for a specific account and symbol. * * @param symbol symbol to get trades from - * @param limit default 500; max 500 + * @param limit default 500; max 1000 * @return a list of trades */ List getMyTrades(String symbol, Integer limit); @@ -230,6 +257,8 @@ public interface BinanceApiRestClient { * @return a list of trades */ List getMyTrades(String symbol); + + List getMyTrades(String symbol, Long fromId); /** * Submit a withdraw request. @@ -240,8 +269,15 @@ public interface BinanceApiRestClient { * @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); + + /** + * Conver a list of assets to BNB + * @param asset the list of assets to convert */ - void withdraw(String asset, String address, String amount, String name); + DustTransferResponse dustTranfer(List asset); /** * Fetch account deposit history. @@ -257,6 +293,13 @@ public interface BinanceApiRestClient { */ WithdrawHistory getWithdrawHistory(String asset); + /** + * Fetch sub-account transfer history. + * + * @return sub-account transfers + */ + List getSubAccountTransfers(); + /** * Fetch deposit address. * @@ -286,4 +329,4 @@ public interface BinanceApiRestClient { * @param listenKey listen key that identifies a data stream */ void closeUserDataStream(String listenKey); -} \ No newline at end of file +} 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/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java old mode 100644 new mode 100755 index b118efa9d..bc048d464 --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -1,47 +1,43 @@ 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.event.*; 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. + * Binance API data streaming facade, 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 symbol the market symbol to subscribe to + * @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 symbol, BinanceApiCallback callback); + Closeable onDepthEvent(String symbols, BinanceApiCallback callback); /** * Open a new web socket to receive {@link CandlestickEvent candlestickEvents} on a callback. * - * @param symbol the market symbol to subscribe to + * @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 symbol, CandlestickInterval interval, BinanceApiCallback callback); + Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback); /** * Open a new web socket to receive {@link AggTradeEvent aggTradeEvents} on a callback. * - * @param symbol the market symbol to subscribe to + * @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 symbol, BinanceApiCallback callback); + Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback); /** * Open a new web socket to receive {@link UserDataUpdateEvent userDataUpdateEvents} on a callback. @@ -53,12 +49,42 @@ public interface BinanceApiWebSocketClient extends Closeable { Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback); /** - * Open a new web socket to receive {@link AllMarketTickersEvent allMarketTickersEvents} on a callback. + * Open a new web socket to receive {@link TickerEvent tickerEvents} 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 onAllMarketTickersEvent(BinanceApiCallback> callback); + Closeable onTickerEvent(String symbols, BinanceApiCallback callback); + /** + * Open a new web socket to receive {@link List 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); + + /** + * Open a new web socket to receive {@link BookTickerEvent bookTickerEvents} 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 onBookTickerEvent(String symbols, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link TickerEvent allBookTickersEvents} 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 onAllBookTickersEvent(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/config/BinanceApiConfig.java b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java new file mode 100755 index 000000000..f4875297b --- /dev/null +++ b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java @@ -0,0 +1,82 @@ +package com.binance.api.client.config; + +/** + * Configuration used for Binance operations. + */ +public class BinanceApiConfig { + + /** + * Base domain for URLs. + */ + private static String BASE_DOMAIN = "binance.com"; + + /** + * Spot Test Network URL. + */ + private static final String TESTNET_DOMAIN = "testnet.binance.vision"; + + /** + * Binance Spot Test Network option: + * true if endpoint is spot test network URL; false if endpoint is production spot API URL. + */ + public static boolean useTestnet; + + /** + * Binance Spot Test Network option: + * true for websocket streaming; false for no streaming. + */ + public static boolean useTestnetStreaming; + + /** + * Set the URL base domain name (e.g., binance.com). + * + * @param baseDomain Base domain name + */ + public static void setBaseDomain(final String baseDomain) { + BASE_DOMAIN = baseDomain; + } + + /** + * Get the URL base domain name (e.g., binance.com). + * + * @return The base domain for URLs + */ + public static String getBaseDomain() { + return BASE_DOMAIN; + } + + /** + * REST API base URL. + */ + public static String getApiBaseUrl() { + return String.format("https://api.%s", getBaseDomain()); + } + + /** + * Streaming API base URL. + */ + public static String getStreamApiBaseUrl() { + return String.format("wss://stream.%s:9443/ws", getBaseDomain()); + } + + /** + * Asset info base URL. + */ + public static String getAssetInfoApiBaseUrl() { + return String.format("https://%s/", getBaseDomain()); + } + + /** + * Spot Test Network API base URL. + */ + public static String getTestNetBaseUrl() { + return String.format("https://%s", TESTNET_DOMAIN); + } + + /** + * Streaming Spot Test Network base URL. + */ + public static String getStreamTestNetBaseUrl() { + return String.format("wss://%s/ws", TESTNET_DOMAIN); + } +} 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 5fe72265b..8e84256d7 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -7,16 +7,6 @@ */ 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"; - /** * HTTP Header to be used for API-KEY authentication. */ @@ -37,11 +27,16 @@ public class BinanceApiConstants { /** * Default receiving window. */ - public static final long DEFAULT_RECEIVING_WINDOW = 6_000_000L; - + 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. + * 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/constant/Util.java b/src/main/java/com/binance/api/client/constant/Util.java new file mode 100755 index 000000000..dae7916f1 --- /dev/null +++ b/src/main/java/com/binance/api/client/constant/Util.java @@ -0,0 +1,33 @@ +package com.binance.api.client.constant; + + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Utility class + */ +public final class Util { + + /** + * List of fiat currencies. + */ + public static final List FIAT_CURRENCY = Collections.unmodifiableList(Arrays.asList("USDT", "BUSD", "PAX", "TUSD", "USDC", "NGN", "RUB", "USDS", "TRY")); + + public static final String BTC_TICKER = "BTC"; + + private Util() { + + } + + /** + * Check if the ticker is fiat currency. + */ + public static boolean isFiatCurrency(String symbol) { + for (String fiat : FIAT_CURRENCY) { + if (symbol.equals(fiat)) return true; + } + return false; + } +} diff --git a/src/main/java/com/binance/api/client/domain/ContingencyType.java b/src/main/java/com/binance/api/client/domain/ContingencyType.java new file mode 100755 index 000000000..f6393a6b4 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/ContingencyType.java @@ -0,0 +1,8 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum ContingencyType { + OCO +} 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 b6760b794..1e2a5e4f8 --- a/src/main/java/com/binance/api/client/domain/ExecutionType.java +++ b/src/main/java/com/binance/api/client/domain/ExecutionType.java @@ -1,13 +1,16 @@ -package com.binance.api.client.domain; - -/** - * Order execution type. - */ -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/LiquidityOperationRecordStatus.java b/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java new file mode 100755 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/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/OCOOrderStatus.java b/src/main/java/com/binance/api/client/domain/OCOOrderStatus.java new file mode 100755 index 000000000..61888fa52 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/OCOOrderStatus.java @@ -0,0 +1,10 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OCOOrderStatus { + EXECUTING, + ALL_DONE, + REJECT +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/OCOStatus.java b/src/main/java/com/binance/api/client/domain/OCOStatus.java new file mode 100755 index 000000000..59c0bd0c9 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/OCOStatus.java @@ -0,0 +1,10 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OCOStatus { + RESPONSE, + EXEC_STARTED, + ALL_DONE +} \ No newline at end of file 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 7da9173b4..52a1e3990 --- a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java +++ b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java @@ -1,17 +1,21 @@ -package com.binance.api.client.domain; - -/** - * Order reject reason values. - */ -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 +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 c477436bd..2f01d92db --- a/src/main/java/com/binance/api/client/domain/OrderSide.java +++ b/src/main/java/com/binance/api/client/domain/OrderSide.java @@ -1,9 +1,12 @@ -package com.binance.api.client.domain; - -/** - * Buy/Sell order side. - */ -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 478dd4d56..7b15e980b --- a/src/main/java/com/binance/api/client/domain/OrderStatus.java +++ b/src/main/java/com/binance/api/client/domain/OrderStatus.java @@ -1,14 +1,17 @@ -package com.binance.api.client.domain; - -/** - * Status of a submitted order. - */ -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 46eb162c2..78ee6b6fe --- a/src/main/java/com/binance/api/client/domain/OrderType.java +++ b/src/main/java/com/binance/api/client/domain/OrderType.java @@ -1,14 +1,17 @@ -package com.binance.api.client.domain; - -/** - * Type of order to submit to the system. - */ -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/SwapRemoveType.java b/src/main/java/com/binance/api/client/domain/SwapRemoveType.java new file mode 100755 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/TimeInForce.java b/src/main/java/com/binance/api/client/domain/TimeInForce.java old mode 100644 new mode 100755 index 49e266431..83043ce7f --- a/src/main/java/com/binance/api/client/domain/TimeInForce.java +++ b/src/main/java/com/binance/api/client/domain/TimeInForce.java @@ -1,16 +1,19 @@ -package com.binance.api.client.domain; - -/** - * 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 - */ -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 9f90aafa4..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,60 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An asset balance in an Account. - * - * @see Account - */ -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/CrossMarginAssets.java b/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java new file mode 100755 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 + '\'' + + '}'; + } +} 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 2ca99502f..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,60 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A deposit address for a given asset. - */ -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 0d45d32aa..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,44 +1,57 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * History of account deposits. - * - * @see Deposit - */ -public class DepositHistory { - - @JsonProperty("depositList") - private List depositList; - - private boolean success; - - 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) - .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/DustTransferResponse.java b/src/main/java/com/binance/api/client/domain/account/DustTransferResponse.java new file mode 100755 index 000000000..a585d2f01 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/DustTransferResponse.java @@ -0,0 +1,52 @@ +package com.binance.api.client.domain.account; + +import java.util.List; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DustTransferResponse { + + private String totalServiceCharge; + + private String totalTransfered; + + private List transferResult; + + public String getTotalServiceCharge() { + return totalServiceCharge; + } + + public void setTotalServiceCharge(String totalServiceCharge) { + this.totalServiceCharge = totalServiceCharge; + } + + public String getTotalTransfered() { + return totalTransfered; + } + + public void setTotalTransfered(String totalTransfered) { + this.totalTransfered = totalTransfered; + } + + public List getTransferResult() { + return transferResult; + } + + public void setTransferResult(List transferResult) { + this.transferResult = transferResult; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("totalServiceCharge", totalServiceCharge) + .append("totalTransfered", totalTransfered) + .append("transferResult", transferResult) + .toString(); + } + +} \ No newline at end of file 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 100755 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 100755 index 000000000..2ce393f1c --- /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.LiquidityOperationRecordStatus; + +public class LiquidityOperationRecord { + + private String poolId; + private String operationId; + private String updateTime; + private String operation; + private String shareAmount; + private String poolName; + private LiquidityOperationRecordStatus 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 LiquidityOperationRecordStatus getStatus() { + return status; + } + + public void setStatus(LiquidityOperationRecordStatus 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/Loan.java b/src/main/java/com/binance/api/client/domain/account/Loan.java new file mode 100755 index 000000000..96389c269 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Loan.java @@ -0,0 +1,48 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.domain.LoanStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * 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/MarginNewOrder.java b/src/main/java/com/binance/api/client/domain/account/MarginNewOrder.java new file mode 100755 index 000000000..74dd71d0b --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginNewOrder.java @@ -0,0 +1,289 @@ +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 MarginNewOrder { + + /** + * 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; + + /** + * Quote quantity. + */ + private String quoteOrderQty; + + /** + * 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; + + /** + * Set the margin order side-effect. NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default: NO_SIDE_EFFECT. + */ + private SideEffectType sideEffectType; + + /** + * Receiving window. + */ + private Long recvWindow; + + /** + * Order timestamp. + */ + private long timestamp; + + /** + * Creates a new order with all required parameters. + */ + public MarginNewOrder(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 MarginNewOrder(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 MarginNewOrder symbol(String symbol) { + this.symbol = symbol; + return this; + } + + public OrderSide getSide() { + return side; + } + + public MarginNewOrder side(OrderSide side) { + this.side = side; + return this; + } + + public OrderType getType() { + return type; + } + + public MarginNewOrder type(OrderType type) { + this.type = type; + return this; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public MarginNewOrder timeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + return this; + } + + public String getQuantity() { + return quantity; + } + + public MarginNewOrder quantity(String quantity) { + this.quantity = quantity; + return this; + } + + public String getQuoteOrderQty() { + return quoteOrderQty; + } + + public MarginNewOrder quoteOrderQty(String quoteOrderQty) { + this.quoteOrderQty = quoteOrderQty; + return this; + } + + public String getPrice() { + return price; + } + + public MarginNewOrder price(String price) { + this.price = price; + return this; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public MarginNewOrder newClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + return this; + } + + public String getStopPrice() { + return stopPrice; + } + + public MarginNewOrder stopPrice(String stopPrice) { + this.stopPrice = stopPrice; + return this; + } + + public String getIcebergQty() { + return icebergQty; + } + + public MarginNewOrder icebergQty(String icebergQty) { + this.icebergQty = icebergQty; + return this; + } + + public NewOrderResponseType getNewOrderRespType() { + return newOrderRespType; + } + + public MarginNewOrder newOrderRespType(NewOrderResponseType newOrderRespType) { + this.newOrderRespType = newOrderRespType; + return this; + } + + public SideEffectType getSideEffectType() { + return sideEffectType; + } + + public MarginNewOrder sideEffectType(SideEffectType sideEffectType) { + this.sideEffectType = sideEffectType; + return this; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public MarginNewOrder recvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + return this; + } + + public long getTimestamp() { + return timestamp; + } + + public MarginNewOrder 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 MarginNewOrder marketBuy(String symbol, String quantity) { + return new MarginNewOrder(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 MarginNewOrder marketSell(String symbol, String quantity) { + return new MarginNewOrder(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 MarginNewOrder limitBuy(String symbol, TimeInForce timeInForce, String quantity, String price) { + return new MarginNewOrder(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 MarginNewOrder limitSell(String symbol, TimeInForce timeInForce, String quantity, String price) { + return new MarginNewOrder(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("quoteOrderQty", quoteOrderQty) + .append("price", price) + .append("newClientOrderId", newClientOrderId) + .append("stopPrice", stopPrice) + .append("icebergQty", icebergQty) + .append("newOrderRespType", newOrderRespType) + .append("sideEffectType", sideEffectType) + .append("recvWindow", recvWindow) + .append("timestamp", timestamp) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginNewOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/MarginNewOrderResponse.java new file mode 100755 index 000000000..0d65d82ea --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginNewOrderResponse.java @@ -0,0 +1,210 @@ +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 MarginNewOrderResponse { + + /** + * 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 String marginBuyBorrowAmount; + + private String marginBuyBorrowAsset; + + 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 String getMarginBuyBorrowAmount() { + return marginBuyBorrowAmount; + } + + public void setMarginBuyBorrowAmount(String marginBuyBorrowAmount) { + this.marginBuyBorrowAmount = marginBuyBorrowAmount; + } + + public String getMarginBuyBorrowAsset() { + return marginBuyBorrowAsset; + } + + public void setMarginBuyBorrowAsset(String marginBuyBorrowAsset) { + this.marginBuyBorrowAsset = marginBuyBorrowAsset; + } + + 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("marginBuyBorrowAmount", marginBuyBorrowAmount) + .append("marginBuyBorrowAsset", marginBuyBorrowAsset) + .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/MarginTransaction.java b/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java new file mode 100755 index 000000000..f08995f1d --- /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(ignoreUnknown = true) +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/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/domain/account/NewOCO.java b/src/main/java/com/binance/api/client/domain/account/NewOCO.java new file mode 100755 index 000000000..9ee106b15 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/NewOCO.java @@ -0,0 +1,241 @@ +package com.binance.api.client.domain.account; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOCO { + + /** + * Symbol to place the order on. + */ + private String symbol; + + /** + * A unique Id for the entire orderList + */ + private String listClientOrderId; + + /** + * Buy/Sell order side. + */ + private OrderSide side; + + /** + * Quantity. + */ + private String quantity; + + /** + * A unique Id for the limit order + */ + private String limitClientOrderId; + + /** + * Price. + */ + private String price; + + /** + * Used to make the LIMIT_MAKER leg an iceberg order. + */ + private String limitIcebergQty; + + /** + * A unique Id for the stop loss/stop loss limit leg + */ + private String stopClientOrderId; + + /** + * Stop Price. + */ + private String stopPrice; + + /** + * If provided, stopLimitTimeInForce is required. + */ + private String stopLimitPrice; + + /** + * Used with STOP_LOSS_LIMIT leg to make an iceberg order. + */ + private String stopIcebergQty; + + /** + * Valid values are GTC/FOK/IOC + */ + private TimeInForce stopLimitTimeInForce; + + /** + * 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 OCO with all required parameters. + */ + public NewOCO(String symbol, OrderSide side, String quantity, String price, String stopPrice) { + this.symbol = symbol; + this.side = side; + this.quantity = quantity; + this.price = price; + this.stopPrice = stopPrice; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getListClientOrderId() { + return listClientOrderId; + } + + public void setListClientOrderId(String listClientOrderId) { + this.listClientOrderId = listClientOrderId; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public String getQuantity() { + return quantity; + } + + public void setQuantity(String quantity) { + this.quantity = quantity; + } + + public String getLimitClientOrderId() { + return limitClientOrderId; + } + + public void setLimitClientOrderId(String limitClientOrderId) { + this.limitClientOrderId = limitClientOrderId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getLimitIcebergQty() { + return limitIcebergQty; + } + + public void setLimitIcebergQty(String limitIcebergQty) { + this.limitIcebergQty = limitIcebergQty; + } + + public String getStopClientOrderId() { + return stopClientOrderId; + } + + public void setStopClientOrderId(String stopClientOrderId) { + this.stopClientOrderId = stopClientOrderId; + } + + public String getStopPrice() { + return stopPrice; + } + + public void setStopPrice(String stopPrice) { + this.stopPrice = stopPrice; + } + + public String getStopLimitPrice() { + return stopLimitPrice; + } + + public void setStopLimitPrice(String stopLimitPrice) { + this.stopLimitPrice = stopLimitPrice; + } + + public String getStopIcebergQty() { + return stopIcebergQty; + } + + public void setStopIcebergQty(String stopIcebergQty) { + this.stopIcebergQty = stopIcebergQty; + } + + public TimeInForce getStopLimitTimeInForce() { + return stopLimitTimeInForce; + } + + public void setStopLimitTimeInForce(TimeInForce stopLimitTimeInForce) { + this.stopLimitTimeInForce = stopLimitTimeInForce; + } + + public NewOrderResponseType getNewOrderRespType() { + return newOrderRespType; + } + + public void setNewOrderRespType(NewOrderResponseType newOrderRespType) { + this.newOrderRespType = newOrderRespType; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public void setRecvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE).append("symbol", symbol) + .append("listClientOrderId", listClientOrderId) + .append("side", side) + .append("quantity", quantity) + .append("limitClientOrderId", limitClientOrderId) + .append("price", price) + .append("limitIcebergQty", limitIcebergQty) + .append("stopClientOrderId", stopClientOrderId) + .append("stopPrice", stopPrice) + .append("stopLimitPrice", stopLimitPrice) + .append("stopIcebergQty", stopIcebergQty) + .append("stopLimitTimeInForce", stopLimitTimeInForce) + .append("newOrderRespType", newOrderRespType) + .append("recvWindow", recvWindow) + .append("timestamp", timestamp) + .toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java b/src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java new file mode 100755 index 000000000..b22580827 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java @@ -0,0 +1,88 @@ +package com.binance.api.client.domain.account; + +import java.util.List; + +import com.binance.api.client.domain.ContingencyType; +import com.binance.api.client.domain.OCOOrderStatus; +import com.binance.api.client.domain.OCOStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOCOResponse extends OrderList { + + private Long orderListId; + private ContingencyType contingencyType; + private OCOStatus listStatusType; + private OCOOrderStatus listOrderStatus; + private String listClientOrderId; + private Long transactionTime; + private String symbol; + private List orderReports; + + // Getters + public Long getOrderListId() { + return this.orderListId; + } + + public ContingencyType getContingencyType() { + return this.contingencyType; + } + + public OCOStatus getListStatusType() { + return this.listStatusType; + } + + public OCOOrderStatus getListOrderStatus() { + return this.listOrderStatus; + } + + public String getListClientOrderId() { + return this.listClientOrderId; + } + + public Long getTransactionTime() { + return this.transactionTime; + } + + public String getSymbol() { + return this.symbol; + } + + public List getOrderReports() { + return orderReports; + } + + // Setter + public void setOrderListId(Long orderListId) { + this.orderListId = orderListId; + } + + public void setContingencyType(ContingencyType contingencyType) { + this.contingencyType = contingencyType; + } + + public void setListStatusType(OCOStatus listStatusType) { + this.listStatusType = listStatusType; + } + + public void setListOrderStatus(OCOOrderStatus listOrderStatus) { + this.listOrderStatus = listOrderStatus; + } + + public void setListClientOrderId(String listClientOrderId) { + this.listClientOrderId = listClientOrderId; + } + + public void setTransactionTime(Long transactionTime) { + this.transactionTime = transactionTime; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public void setOrderReports(List orderReports) { + this.orderReports = orderReports; + } + +} 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 af76a78b2..6c592219a --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -4,11 +4,13 @@ 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 { /** @@ -36,6 +38,11 @@ public class NewOrder { */ private String quantity; + /** + * Quote quantity. + */ + private String quoteOrderQty; + /** * Price. */ @@ -51,11 +58,21 @@ public class NewOrder { */ private String stopPrice; + /** + * Used with stop orders. + */ + private String stopLimitPrice; + /** * Used with iceberg orders. */ private String icebergQty; + /** + * Set the response JSON. ACK, RESULT, or FULL; default: RESULT. + */ + private NewOrderResponseType newOrderRespType; + /** * Receiving window. */ @@ -75,6 +92,7 @@ public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeI this.type = type; this.timeInForce = timeInForce; this.quantity = quantity; + this.newOrderRespType = NewOrderResponseType.RESULT; this.timestamp = System.currentTimeMillis(); this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; } @@ -132,6 +150,15 @@ public NewOrder quantity(String quantity) { return this; } + public String getQuoteOrderQty() { + return quoteOrderQty; + } + + public NewOrder quoteOrderQty(String quoteOrderQty) { + this.quoteOrderQty = quoteOrderQty; + return this; + } + public String getPrice() { return price; } @@ -159,6 +186,15 @@ public NewOrder stopPrice(String stopPrice) { return this; } + public String getStopLimitPrice() { + return stopLimitPrice; + } + + public NewOrder stopLimitPrice(String stopLimitPrice) { + this.stopLimitPrice = stopLimitPrice; + return this; + } + public String getIcebergQty() { return icebergQty; } @@ -168,6 +204,15 @@ public NewOrder icebergQty(String icebergQty) { return this; } + public NewOrderResponseType getNewOrderRespType() { + return newOrderRespType; + } + + public NewOrder newOrderRespType(NewOrderResponseType newOrderRespType) { + this.newOrderRespType = newOrderRespType; + return this; + } + public Long getRecvWindow() { return recvWindow; } @@ -225,17 +270,20 @@ public static NewOrder limitSell(String symbol, TimeInForce timeInForce, String @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("recvWindow", recvWindow) - .append("timestamp", timestamp) - .toString(); + .append("symbol", symbol) + .append("side", side) + .append("type", type) + .append("timeInForce", timeInForce) + .append("quantity", quantity) + .append("quoteOrderQty", quoteOrderQty) + .append("price", price) + .append("newClientOrderId", newClientOrderId) + .append("stopPrice", stopPrice) + .append("stopLimitPrice", stopLimitPrice) + .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 7485f175e..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,77 +1,188 @@ -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; - -/** - * 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; - - /** - * 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; - } - - @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) - .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 new file mode 100755 index 000000000..fe1d00e55 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java @@ -0,0 +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 +} + 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 a0b5939b7..881efd6dc --- a/src/main/java/com/binance/api/client/domain/account/Order.java +++ b/src/main/java/com/binance/api/client/domain/account/Order.java @@ -6,6 +6,7 @@ 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; /** @@ -69,6 +70,11 @@ public class Order { */ private String stopPrice; + /** + * Used with stop orders. + */ + private String stopLimitPrice; + /** * Used with iceberg orders. */ @@ -79,6 +85,27 @@ public class Order { */ private long time; + /** + * Used to calculate the average price + */ + private String cummulativeQuoteQty; + + /** + * Update timestamp. + */ + private long updateTime; + + /** + * Is working. + */ + @JsonProperty("isWorking") + private boolean working; + + /** + * Original quote order quantity. + */ + private String origQuoteOrderQty; + public String getSymbol() { return symbol; } @@ -167,6 +194,14 @@ public void setStopPrice(String stopPrice) { this.stopPrice = stopPrice; } + public String getStopLimitPrice() { + return stopLimitPrice; + } + + public void setStopLimitPrice(String stopLimitPrice) { + this.stopLimitPrice = stopLimitPrice; + } + public String getIcebergQty() { return icebergQty; } @@ -183,22 +218,59 @@ public void setTime(long time) { this.time = time; } + public String getCummulativeQuoteQty() { + return cummulativeQuoteQty; + } + + public void setCummulativeQuoteQty(String cummulativeQuoteQty) { + this.cummulativeQuoteQty = cummulativeQuoteQty; + } + + public long getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(long updateTime) { + this.updateTime = updateTime; + } + + public boolean isWorking() { + return working; + } + + public void setWorking(boolean working) { + this.working = working; + } + + public String getOrigQuoteOrderQty() { + return origQuoteOrderQty; + } + + public void setOrigQuoteOrderQty(String origQuoteOrderQty) { + this.origQuoteOrderQty = origQuoteOrderQty; + } + @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) - .toString(); + .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("stopLimitPrice", stopLimitPrice) + .append("icebergQty", icebergQty) + .append("time", time) + .append("cummulativeQuoteQty", cummulativeQuoteQty) + .append("updateTime", updateTime) + .append("isWorking", working) + .append("origQuoteOrderQty", origQuoteOrderQty) + .toString(); } } diff --git a/src/main/java/com/binance/api/client/domain/account/OrderList.java b/src/main/java/com/binance/api/client/domain/account/OrderList.java new file mode 100755 index 000000000..2ee3674d0 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/OrderList.java @@ -0,0 +1,113 @@ +package com.binance.api.client.domain.account; + +import java.util.List; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.ContingencyType; +import com.binance.api.client.domain.OCOOrderStatus; +import com.binance.api.client.domain.OCOStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderList { + + /** + * Order id. + */ + private Long orderListId; + + private ContingencyType contingencyType; + + private OCOStatus listStatusType; + + private OCOOrderStatus listOrderStatus; + + private String listClientOrderId; + + private Long transactionTime; + + private String symbol; + + private List orders; + + public Long getOrderListId() { + return orderListId; + } + + public void setOrderListId(Long orderListId) { + this.orderListId = orderListId; + } + + public ContingencyType getContingencyType() { + return contingencyType; + } + + public void setContingencyType(ContingencyType contingencyType) { + this.contingencyType = contingencyType; + } + + public OCOStatus getListStatusType() { + return listStatusType; + } + + public void setListStatusType(OCOStatus listStatusType) { + this.listStatusType = listStatusType; + } + + public OCOOrderStatus getListOrderStatus() { + return listOrderStatus; + } + + public void setListOrderStatus(OCOOrderStatus listOrderStatus) { + this.listOrderStatus = listOrderStatus; + } + + public String getListClientOrderId() { + return listClientOrderId; + } + + public void setListClientOrderId(String listClientOrderId) { + this.listClientOrderId = listClientOrderId; + } + + public Long getTransactionTime() { + return transactionTime; + } + + public void setTransactionTime(Long transactionTime) { + this.transactionTime = transactionTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public List getOrders() { + return orders; + } + + public void setOrders(List orders) { + this.orders = orders; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderListId", orderListId) + .append("contingencyType", contingencyType) + .append("listStatusType", listStatusType) + .append("listOrderStatus", listOrderStatus) + .append("listClientOrderId", listClientOrderId) + .append("transactionTime", transactionTime) + .append("symbol", symbol) + .append("orders", orders) + .toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/OrderReport.java b/src/main/java/com/binance/api/client/domain/account/OrderReport.java new file mode 100755 index 000000000..041876861 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/OrderReport.java @@ -0,0 +1,172 @@ +package com.binance.api.client.domain.account; + +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; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderReport { + + /** + * Order symbol. + */ + private String symbol; + + /** + * Order id. + */ + private Long orderId; + + private Long orderListId; + + /** + * This will be either a generated one, or the newClientOrderId parameter + * which was passed when creating the new order. + */ + private String clientOrderId; + + private String origClientOrderId; + + private Long transactTime; + + private String price; + + private String origQty; + + private String executedQty; + + private String cummulativeQuoteQty; + + private OrderStatus status; + + private TimeInForce timeInForce; + + private OrderType type; + + private OrderSide side; + + private String stopPrice; + + 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 Long getOrderListId() { + return orderListId; + } + + public void setOrderListId(Long orderListId) { + this.orderListId = orderListId; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public void setOrigClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + } + + 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 String getStopPrice() { + return stopPrice; + } + + public void setStopPrice(String stopPrice) { + this.stopPrice = stopPrice; + } + +} \ No newline at end of file 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 100755 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/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/domain/account/SideEffectType.java b/src/main/java/com/binance/api/client/domain/account/SideEffectType.java new file mode 100755 index 000000000..940490e16 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SideEffectType.java @@ -0,0 +1,17 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Desired side-effect for margin orders: + * NO_SIDE_EFFECT for normal trade order; + * MARGIN_BUY for margin trade order; + * AUTO_REPAY for making auto repayment after order filled + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SideEffectType { + NO_SIDE_EFFECT, + MARGIN_BUY, + AUTO_REPAY +} + diff --git a/src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java b/src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java new file mode 100755 index 000000000..69b7d70cf --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java @@ -0,0 +1,151 @@ +package com.binance.api.client.domain.account; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class SubAccountTransfer { + + /** + * Counter party name + */ + private String counterParty; + + /** + * Counter party email + */ + private String email; + + /** + * Transfer in or transfer out + */ + private Integer type; // 1 for transfer in, 2 for transfer out + + /** + * Transfer asset + */ + private String asset; + + /** + * Quantity of transfer asset + */ + private String qty; + + /** + * Type of from account + */ + private String fromAccountType; + + /** + * Type of to account + */ + private String toAccountType; + + /** + * Transfer status + */ + private String status; + + /** + * Transfer ID + */ + private Long tranId; + + /** + * Transfer time + */ + private Long time; + + // Setter + public void setCounterParty(String counterParty) { + this.counterParty = counterParty; + } + + public void setEmail(String email) { + this.email = email; + } + + public void setType(Integer type) { + this.type = type; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public void setQty(String qty) { + this.qty = qty; + } + + public void setFromAccountType(String fromAccountType) { this.fromAccountType = fromAccountType; } + + public void setToAccountType(String toAccountType) { this.toAccountType = toAccountType; } + + public void setStatus(String status) { + this.status = status; + } + + public void setTranId(Long tranId) { + this.tranId = tranId; + } + + public void setTime(Long time) { + this.time = time; + } + + // Getter + public String getCounterParty() { + return this.counterParty; + } + + public String getEmail() { + return this.email; + } + + public Integer getType() { + return this.type; + } + + public String getAsset() { + return this.asset; + } + + public String getQty() { + return this.qty; + } + + public String getFromAccountType() { return this.fromAccountType; } + + public String getToAccountType() { return this.toAccountType; } + + public String getStatus() { + return this.status; + } + + public Long getTranId() { + return this.tranId; + } + + public Long getTime() { + return this.time; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("counterParty", this.counterParty) + .append("email", this.email) + .append("type", this.type) + .append("asset", this.asset) + .append("qty", this.qty) + .append("fromAccountType", this.fromAccountType) + .append("toAccountType", this.toAccountType) + .append("status", this.status) + .append("tranId", this.tranId) + .append("time", this.time) + .toString(); + } + +} \ No newline at end of file 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 100755 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 100755 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 100755 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 100755 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/domain/account/Trade.java b/src/main/java/com/binance/api/client/domain/account/Trade.java old mode 100644 new mode 100755 index feb639faa..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,148 +1,188 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents an executed trade. - */ -public class Trade { - - /** - * Trade id. - */ - private Long id; - - /** - * Price. - */ - private String price; - - /** - * Quantity. - */ - private String qty; - - /** - * Commission. - */ - private String commission; - - /** - * Asset on which commission is taken - */ - private String commissionAsset; - - /** - * Trade execution time. - */ - private long time; - - @JsonProperty("isBuyer") - private boolean buyer; - - @JsonProperty("isMaker") - private boolean maker; - - @JsonProperty("isBestMatch") - private boolean bestMatch; - - private String orderId; - - 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 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 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("price", price) - .append("qty", qty) - .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 a4470a0c1..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,102 +1,104 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents an executed trade history item. - */ -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/TransferResult.java b/src/main/java/com/binance/api/client/domain/account/TransferResult.java new file mode 100755 index 000000000..a07f12c56 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/TransferResult.java @@ -0,0 +1,91 @@ +package com.binance.api.client.domain.account; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Dust transfer result information. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TransferResult { + + private String amount; + + private String fromAsset; + + /** + * Order timestamp. + */ + private long operateTime; + + private String serviceChargeAmount; + + private long tranId; + + private String transferedAmount; + + + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getFromAsset() { + return fromAsset; + } + + public void setFromAsset(String fromAsset) { + this.fromAsset = fromAsset; + } + + public long getOperateTime() { + return operateTime; + } + + public void setOperateTime(long operateTime) { + this.operateTime = operateTime; + } + + public String getServiceChargeAmount() { + return serviceChargeAmount; + } + + public void setServiceChargeAmount(String serviceChargeAmount) { + this.serviceChargeAmount = serviceChargeAmount; + } + + public long getTranId() { + return tranId; + } + + public void setTranId(long tranId) { + this.tranId = tranId; + } + + public String getTransferedAmount() { + return transferedAmount; + } + + public void setTransferedAmount(String transferedAmount) { + this.transferedAmount = transferedAmount; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("amount", amount) + .append("fromAsset", fromAsset) + .append("operateTime", operateTime) + .append("serviceChargeAmount", serviceChargeAmount) + .append("tranId", tranId) + .append("transderedAmount", transferedAmount) + .toString(); + } + +} \ No newline at end of file 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 4694c0d09..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,42 +1,44 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * History of account withdrawals. - * - * @see Withdraw - */ -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 new file mode 100755 index 000000000..b9ebded80 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java @@ -0,0 +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(); + } + + +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/AllOrderListRequest.java b/src/main/java/com/binance/api/client/domain/account/request/AllOrderListRequest.java new file mode 100755 index 000000000..6d7be4740 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/request/AllOrderListRequest.java @@ -0,0 +1,77 @@ +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class AllOrderListRequest { + + private static final Integer DEFAULT_LIMIT = 500; + + private Long fromId; + + private Long startTime; + + private Long endTime; + + private Integer limit; + + private Long recvWindow; + + private Long timestamp; + + public AllOrderListRequest() { + this.limit = DEFAULT_LIMIT; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + public Long getFromId() { + return fromId; + } + + public void setFromId(Long fromId) { + this.fromId = fromId; + } + + public Long getStartTime() { + return startTime; + } + + public void setStartTime(Long startTime) { + this.startTime = startTime; + } + + public Long getEndTime() { + return endTime; + } + + public void setEndTime(Long endTime) { + this.endTime = endTime; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public void setRecvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + +} \ No newline at end of file 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/CancelOrderListRequest.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderListRequest.java new file mode 100755 index 000000000..07d057ba3 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderListRequest.java @@ -0,0 +1,83 @@ +package com.binance.api.client.domain.account.request; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; + +public class CancelOrderListRequest { + + private String symbol; + + private Long orderListId; + + private String listClientOrderId; + + /** + * Used to uniquely identify this cancel. Automatically generated by default + */ + private String newClientOrderId; + + private Long recvWindow; + + private Long timestamp; + + public CancelOrderListRequest(String symbol) { + this.symbol = symbol; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOrderListId() { + return orderListId; + } + + public void setOrderListId(Long orderListId) { + this.orderListId = orderListId; + } + + public String getListClientOrderId() { + return listClientOrderId; + } + + public void setListClientOrderId(String listClientOrderId) { + this.listClientOrderId = listClientOrderId; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public void setNewClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public void setRecvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE).append("symbol", symbol).append("orderListId", orderListId).append("listClientOrderId", listClientOrderId).append("newClientOrderId", newClientOrderId).append("recvWindow", recvWindow).append("timestamp", timestamp).toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderListResponse.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderListResponse.java new file mode 100755 index 000000000..a8cdb4a89 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderListResponse.java @@ -0,0 +1,9 @@ +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.domain.account.NewOCOResponse; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CancelOrderListResponse extends NewOCOResponse { + +} \ No newline at end of file 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 new file mode 100755 index 000000000..20fc07912 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java @@ -0,0 +1,89 @@ +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderStatus; +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 Long orderId; + + private String clientOrderId; + + private OrderStatus 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 void setStatus(OrderStatus status) { + this.status = status; + } + + public OrderStatus getStatus() { + return status; + } + + public void setExecutedQty(String executedQty) { + this.executedQty = executedQty; + } + + public String getExecutedQty() { + return executedQty; + } + + public Long getOrderId() { + return orderId; + } + + public CancelOrderResponse setOrderId(Long 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(); + } +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/request/OrderListStatusRequest.java b/src/main/java/com/binance/api/client/domain/account/request/OrderListStatusRequest.java new file mode 100755 index 000000000..648bf708b --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/request/OrderListStatusRequest.java @@ -0,0 +1,55 @@ +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderListStatusRequest { + + private Long orderListId; + + private String origClientOrderId; + + private Long recvWindow; + + private Long timestamp; + + public OrderListStatusRequest(Long orderListId) { + this.orderListId = orderListId; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + public Long getOrderListId() { + return orderListId; + } + + public void setOrderListId(Long orderListId) { + this.orderListId = orderListId; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public void setOrigClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public void setRecvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + +} \ No newline at end of file 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 2221af12d..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,53 +1,55 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Base request parameters for order-related methods. - */ -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 deleted file mode 100644 index 336f0980e..000000000 --- a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java +++ /dev/null @@ -1,270 +0,0 @@ -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 double priceChange; - - @JsonProperty("P") - private double priceChangePercent; - - @JsonProperty("w") - private double weightedAveragePrice; - - @JsonProperty("x") - private double previousDaysClosePrice; - - @JsonProperty("c") - private double currentDaysClosePrice; - - @JsonProperty("Q") - private long closeTradesQuantity; - - @JsonProperty("a") - private double bestAskPrice; - - @JsonProperty("A") - private long bestAskQuantity; - - @JsonProperty("o") - private double openPrice; - - @JsonProperty("h") - private double highPrice; - - @JsonProperty("l") - private double lowPrice; - - @JsonProperty("v") - private long totalTradedBaseAssetVolume; - - @JsonProperty("q") - private long 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 double getPriceChange() { - return priceChange; - } - - public void setPriceChange(double priceChange) { - this.priceChange = priceChange; - } - - public double getPriceChangePercent() { - return priceChangePercent; - } - - public void setPriceChangePercent(double priceChangePercent) { - this.priceChangePercent = priceChangePercent; - } - - public double getWeightedAveragePrice() { - return weightedAveragePrice; - } - - public void setWeightedAveragePrice(double weightedAveragePrice) { - this.weightedAveragePrice = weightedAveragePrice; - } - - public double getPreviousDaysClosePrice() { - return previousDaysClosePrice; - } - - public void setPreviousDaysClosePrice(double previousDaysClosePrice) { - this.previousDaysClosePrice = previousDaysClosePrice; - } - - public double getCurrentDaysClosePrice() { - return currentDaysClosePrice; - } - - public void setCurrentDaysClosePrice(double currentDaysClosePrice) { - this.currentDaysClosePrice = currentDaysClosePrice; - } - - public long getCloseTradesQuantity() { - return closeTradesQuantity; - } - - public void setCloseTradesQuantity(long closeTradesQuantity) { - this.closeTradesQuantity = closeTradesQuantity; - } - - public double getBestAskPrice() { - return bestAskPrice; - } - - public void setBestAskPrice(double bestAskPrice) { - this.bestAskPrice = bestAskPrice; - } - - public long getBestAskQuantity() { - return bestAskQuantity; - } - - public void setBestAskQuantity(long bestAskQuantity) { - this.bestAskQuantity = bestAskQuantity; - } - - public double getOpenPrice() { - return openPrice; - } - - public void setOpenPrice(double openPrice) { - this.openPrice = openPrice; - } - - public double getHighPrice() { - return highPrice; - } - - public void setHighPrice(double highPrice) { - this.highPrice = highPrice; - } - - public double getLowPrice() { - return lowPrice; - } - - public void setLowPrice(double lowPrice) { - this.lowPrice = lowPrice; - } - - public long getTotalTradedBaseAssetVolume() { - return totalTradedBaseAssetVolume; - } - - public void setTotalTradedBaseAssetVolume(long totalTradedBaseAssetVolume) { - this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; - } - - public long getTotalTradedQuoteAssetVolume() { - return totalTradedQuoteAssetVolume; - } - - public void setTotalTradedQuoteAssetVolume(long 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("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/BalanceUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/BalanceUpdateEvent.java new file mode 100755 index 000000000..49f2c0b7e --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/event/BalanceUpdateEvent.java @@ -0,0 +1,83 @@ +package com.binance.api.client.domain.event; + +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; + +/** + * Account update event which will reflect the balance changes of the account. + *

+ * This event is embedded as part of a user data update event. + * + * @see UserDataUpdateEvent + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class BalanceUpdateEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("a") + private String asset; + + @JsonProperty("d") + private String balanceDelta; + + @JsonProperty("T") + private Long clearTime; + + 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 getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getBalanceDelta() { + return balanceDelta; + } + + public void setBalanceDelta(String balanceDelta) { + this.balanceDelta = balanceDelta; + } + + public Long getClearTime() { + return clearTime; + } + + public void setClearTime(Long clearTime) { + this.clearTime = clearTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("balances", asset) + .append("balanceDelta", balanceDelta) + .append("clearTime", clearTime) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java b/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java new file mode 100755 index 000000000..d3612194f --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java @@ -0,0 +1,112 @@ +package com.binance.api.client.domain.event; + +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; + +/** + * BookTickerEvent event for a symbol. Pushes any update to the best bid or + * ask's price or quantity in real-time for a specified symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class BookTickerEvent { + + @JsonProperty("u") + private long updateId; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("b") + private String bidPrice; + + @JsonProperty("B") + private String bidQuantity; + + @JsonProperty("a") + private String askPrice; + + @JsonProperty("A") + private String askQuantity; + + public BookTickerEvent() { + super(); + } + + public BookTickerEvent(long updateId, String symbol, String bidPrice, String bidQuantity, String askPrice, + String askQuantity) { + super(); + this.updateId = updateId; + this.symbol = symbol; + this.bidPrice = bidPrice; + this.bidQuantity = bidQuantity; + this.askPrice = askPrice; + this.askQuantity = askQuantity; + } + + public BookTickerEvent(String symbol, String bidPrice, String bidQuantity, String askPrice, String askQuantity) { + super(); + this.symbol = symbol; + this.bidPrice = bidPrice; + this.bidQuantity = bidQuantity; + this.askPrice = askPrice; + this.askQuantity = askQuantity; + } + + public long getUpdateId() { + return updateId; + } + + public void setUpdateId(long updateId) { + this.updateId = updateId; + } + + 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 getBidQuantity() { + return bidQuantity; + } + + public void setBidQuantity(String bidQuantity) { + this.bidQuantity = bidQuantity; + } + + public String getAskPrice() { + return askPrice; + } + + public void setAskPrice(String askPrice) { + this.askPrice = askPrice; + } + + public String getAskQuantity() { + return askQuantity; + } + + public void setAskQuantity(String askQuantity) { + this.askQuantity = askQuantity; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE).append("eventType", "BookTicker") + .append("updateId", updateId).append("symbol", symbol).append("bidPrice", bidPrice) + .append("bidQuantity", bidQuantity).append("askPrice", askPrice).append("askQuantity", askQuantity) + .toString(); + } +} \ 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 31cbe1e4f..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,219 +1,221 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -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) -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 555d0af16..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,22 +1,25 @@ -package com.binance.api.client.domain.event; - -/** - * Dummy type to wrap a listen key from a server response. - */ -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 0f26008a7..d2bf6fc84 --- 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,19 +1,14 @@ 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.binance.api.client.domain.*; 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 @@ -25,7 +20,7 @@ public class OrderTradeUpdateEvent { private String eventType; @JsonProperty("E") - private long eventTime; + private Long eventTime; @JsonProperty("s") private String symbol; @@ -129,6 +124,30 @@ public class OrderTradeUpdateEvent { @JsonProperty("t") private Long tradeId; + /** + * Order creation time. + */ + @JsonProperty("O") + private Long orderCreationTime; + + /** + * Cumulative quote asset transacted quantity. + */ + @JsonProperty("Z") + private String cumulativeQuoteQty; + + /** + * Last quote asset transacted quantity (i.e. lastPrice * lastQty). + */ + @JsonProperty("Y") + private String lastQuoteQty; + + /** + * Quote Order Qty. + */ + @JsonProperty("Q") + private String quoteOrderQty; + public String getEventType() { return eventType; } @@ -137,11 +156,11 @@ public void setEventType(String eventType) { this.eventType = eventType; } - public long getEventTime() { + public Long getEventTime() { return eventTime; } - public void setEventTime(long eventTime) { + public void setEventTime(Long eventTime) { this.eventTime = eventTime; } @@ -225,7 +244,7 @@ public void setOrderRejectReason(OrderRejectReason orderRejectReason) { this.orderRejectReason = orderRejectReason; } - public long getOrderId() { + public Long getOrderId() { return orderId; } @@ -273,22 +292,53 @@ public void setCommissionAsset(String commissionAsset) { this.commissionAsset = commissionAsset; } - public long getOrderTradeTime() { + public Long getOrderTradeTime() { return orderTradeTime; } - public void setOrderTradeTime(long orderTradeTime) { + public void setOrderTradeTime(Long orderTradeTime) { this.orderTradeTime = orderTradeTime; } - public long getTradeId() { + public Long getTradeId() { return tradeId; } - public void setTradeId(long tradeId) { + public void setTradeId(Long tradeId) { this.tradeId = tradeId; } + public Long getOrderCreationTime() { + return orderCreationTime; + } + + public void setOrderCreationTime(Long orderCreationTime) { + this.orderCreationTime = orderCreationTime; + } + + public String getCumulativeQuoteQty() { + return cumulativeQuoteQty; + } + + public void setCumulativeQuoteQty(String cumulativeQuoteQty) { + this.cumulativeQuoteQty = cumulativeQuoteQty; + } + + public String getLastQuoteQty() { + return lastQuoteQty; + } + + public void setLastQuoteQty(String lastQuoteQty) { + this.lastQuoteQty = lastQuoteQty; + } + + public String getQuoteOrderQty() { + return quoteOrderQty; + } + + public void setQuoteOrderQty(String quoteOrderQty) { + this.quoteOrderQty = quoteOrderQty; + } @Override public String toString() { @@ -313,6 +363,10 @@ public String toString() { .append("commissionAsset", commissionAsset) .append("orderTradeTime", orderTradeTime) .append("tradeId", tradeId) + .append("orderCreationTime", orderCreationTime) + .append("cumulativeQuoteQty", cumulativeQuoteQty) + .append("lastQuoteQty", lastQuoteQty) + .append("quoteOrderQty", quoteOrderQty) .toString(); } } diff --git a/src/main/java/com/binance/api/client/domain/event/TickerEvent.java b/src/main/java/com/binance/api/client/domain/event/TickerEvent.java new file mode 100755 index 000000000..c0c7e97f1 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/event/TickerEvent.java @@ -0,0 +1,295 @@ +package com.binance.api.client.domain.event; + +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; + +/** + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TickerEvent { + + @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 statisticsOpenTime; + + @JsonProperty("C") + private long statisticsCloseTime; + + @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 getStatisticsOpenTime() { + return statisticsOpenTime; + } + + public void setStatisticsOpenTime(long statisticsOpenTime) { + this.statisticsOpenTime = statisticsOpenTime; + } + + public long getStatisticsCloseTime() { + return statisticsCloseTime; + } + + public void setStatisticsCloseTime(long statisticsCloseTime) { + this.statisticsCloseTime = statisticsCloseTime; + } + + 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("statisticsOpenTime", statisticsOpenTime) + .append("statisticsCloseTime", statisticsCloseTime) + .append("firstTradeId", firstTradeId) + .append("lastTradeId", lastTradeId) + .append("totalNumberOfTrades", totalNumberOfTrades) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/TopOrdersEvent.java b/src/main/java/com/binance/api/client/domain/event/TopOrdersEvent.java new file mode 100755 index 000000000..a9a0a3c78 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/event/TopOrdersEvent.java @@ -0,0 +1,51 @@ +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 org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Top bids and asks from Partial Book Depth event + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TopOrdersEvent { + private Long lastUpdateId; + private List bids; + 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/event/UserDataUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java old mode 100644 new mode 100755 index 0af50e198..062565790 --- 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,15 +1,20 @@ package com.binance.api.client.domain.event; import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.exception.UnsupportedEventException; 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: - * + * User data update event which can be of four types: + *

* 1) outboundAccountInfo, whenever there is a change in the account (e.g. balance of an asset) - * 2) executionReport, whenever there is a trade or an order + * 2) outboundAccountPosition, the change in account balances caused by an event. + * 3) executionReport, whenever there is a trade or an order + * 4) balanceUpdate, the change in account balance (delta). + *

+ * Deserialization could fail with UnsupportedEventException in case of unsupported eventType. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonDeserialize(using = UserDataUpdateEventDeserializer.class) @@ -19,7 +24,9 @@ public class UserDataUpdateEvent { private long eventTime; - private AccountUpdateEvent accountUpdateEvent; + private AccountUpdateEvent outboundAccountPositionUpdateEvent; + + private BalanceUpdateEvent balanceUpdateEvent; private OrderTradeUpdateEvent orderTradeUpdateEvent; @@ -39,12 +46,28 @@ public void setEventTime(long eventTime) { this.eventTime = eventTime; } + /** + * @Deprecated: left in for backwards compatibility. Use getOutboundAccountPositionUpdateEvent() instead, as that is what the Binance API documentation calls it. + */ + @Deprecated public AccountUpdateEvent getAccountUpdateEvent() { - return accountUpdateEvent; + return outboundAccountPositionUpdateEvent; + } + + public AccountUpdateEvent getOutboundAccountPositionUpdateEvent() { + return outboundAccountPositionUpdateEvent; + } + + public void setOutboundAccountPositionUpdateEvent(AccountUpdateEvent accountUpdateEvent) { + this.outboundAccountPositionUpdateEvent = accountUpdateEvent; + } + + public BalanceUpdateEvent getBalanceUpdateEvent() { + return balanceUpdateEvent; } - public void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { - this.accountUpdateEvent = accountUpdateEvent; + public void setBalanceUpdateEvent(BalanceUpdateEvent balanceUpdateEvent) { + this.balanceUpdateEvent = balanceUpdateEvent; } public OrderTradeUpdateEvent getOrderTradeUpdateEvent() { @@ -60,8 +83,10 @@ 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); + if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + sb.append("outboundAccountPositionUpdateEvent", outboundAccountPositionUpdateEvent); + } else if (eventType == UserDataUpdateEventType.BALANCE_UPDATE) { + sb.append("balanceUpdateEvent", balanceUpdateEvent); } else { sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); } @@ -69,8 +94,13 @@ public String toString() { } public enum UserDataUpdateEventType { - ACCOUNT_UPDATE("outboundAccountInfo"), - ORDER_TRADE_UPDATE("executionReport"); + /** Corresponds to "outboundAccountPosition" events. */ + ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), + /** Corresponds to "balanceUpdate" events. */ + BALANCE_UPDATE("balanceUpdate"), + /** Corresponds to "executionReport" events. */ + ORDER_TRADE_UPDATE("executionReport"), + ; private final String eventTypeId; @@ -83,12 +113,14 @@ public String getEventTypeId() { } public static UserDataUpdateEventType fromEventTypeId(String eventTypeId) { - if (ACCOUNT_UPDATE.eventTypeId.equals(eventTypeId)) { - return ACCOUNT_UPDATE; - } else if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { + if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { return ORDER_TRADE_UPDATE; + } else if (ACCOUNT_POSITION_UPDATE.eventTypeId.equals(eventTypeId)) { + return ACCOUNT_POSITION_UPDATE; + } else if (BALANCE_UPDATE.eventTypeId.equals(eventTypeId)) { + return BALANCE_UPDATE; } - throw new IllegalArgumentException("Unrecognized user data update event type id: " + eventTypeId); + throw new UnsupportedEventException("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 afc584636..9e0031efc --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java @@ -12,7 +12,8 @@ import java.io.IOException; /** - * Custom deserializer for a User Data stream event, since the API can return two different responses in this stream. + * Custom deserializer for a User Data stream event, since the API can return four different responses in this stream. + * * @see UserDataUpdateEvent */ public class UserDataUpdateEventDeserializer extends JsonDeserializer { @@ -22,7 +23,7 @@ public class UserDataUpdateEventDeserializer extends JsonDeserializer T getUserDataUpdateEventDetail(String json, Class clazz, ObjectMap throw new BinanceApiException(e); } } -} \ No newline at end of file +} 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 new file mode 100755 index 000000000..715190f31 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/general/Asset.java @@ -0,0 +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(); + } + } 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 ef4907925..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,42 +1,44 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -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. - */ -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 593b4ae5e..57c2931db --- 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,8 +1,11 @@ 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, @@ -10,8 +13,14 @@ public enum FilterType { MIN_NOTIONAL, MAX_NUM_ORDERS, MAX_ALGO_ORDERS, + MAX_NUM_ALGO_ORDERS, + ICEBERG_PARTS, + PERCENT_PRICE, + MARKET_LOT_SIZE, + MAX_NUM_ICEBERG_ORDERS, + MAX_POSITION, // Exchange EXCHANGE_MAX_NUM_ORDERS, EXCHANGE_MAX_ALGO_ORDERS -} +} \ No newline at end of file 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 8f0e3fd1a..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,49 +1,51 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Rate limits. - */ -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 bc316061d..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,10 +1,13 @@ -package com.binance.api.client.domain.general; - -/** - * Rate limit intervals. - */ -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 af438bebb..fb5ee0e89 --- 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,9 +1,13 @@ -package com.binance.api.client.domain.general; - -/** - * Rate limiters. - */ -public enum RateLimitType { - REQUESTS, - 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, + RAW_REQUESTS +} 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 9b7475271..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,21 +1,24 @@ -package com.binance.api.client.domain.general; - -/** - * Time of the server running Binance's REST API. - */ -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 8902b1188..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,139 +1,160 @@ -package com.binance.api.client.domain.general; - -/** - * 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. - */ -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_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. - */ - 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 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..ca2723235 --- 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,171 @@ -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 boolean ocoAllowed; + + private boolean quoteOrderQtyMarketAllowed; + + private boolean isSpotTradingAllowed; + + private boolean isMarginTradingAllowed; + + 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 boolean isOcoAllowed() { + return ocoAllowed; + } + + public void setOcoAllowed(boolean ocoAllowed) { + this.ocoAllowed = ocoAllowed; + } + + public boolean isQuoteOrderQtyMarketAllowed() { + return quoteOrderQtyMarketAllowed; + } + + public void setQuoteOrderQtyMarketAllowed(boolean quoteOrderQtyMarketAllowed) { + this.quoteOrderQtyMarketAllowed = quoteOrderQtyMarketAllowed; + } + + public boolean isSpotTradingAllowed() { + return isSpotTradingAllowed; + } + + public void setIsSpotTradingAllowed(boolean isSpotTradingAllowed) { + this.isSpotTradingAllowed = isSpotTradingAllowed; + } + + public boolean isMarginTradingAllowed() { + return isMarginTradingAllowed; + } + + public void setIsMarginTradingAllowed(boolean isMarginTradingAllowed) { + this.isMarginTradingAllowed = isMarginTradingAllowed; + } + + 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 e9ddff627..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,14 +1,17 @@ -package com.binance.api.client.domain.general; - -/** - * Status of a symbol on the exchange. - */ -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 c91f3a76f..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,86 +1,88 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents the best price/qty on the order book for a given symbol. - */ -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 3bd4887e3..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,33 +1,36 @@ -package com.binance.api.client.domain.market; - -/** - * Kline/Candlestick intervals. - * m -> minutes; h -> hours; d -> days; w -> weeks; M -> months - */ -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 d5054a9e6..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,60 +1,62 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Order book of a symbol in Binance. - */ -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 3bc946a7d..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,42 +1,44 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -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) -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 e2444cbc8..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,44 +1,46 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Wraps a symbol and its corresponding latest price. - */ -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/exception/UnsupportedEventException.java b/src/main/java/com/binance/api/client/exception/UnsupportedEventException.java new file mode 100755 index 000000000..4a04731b7 --- /dev/null +++ b/src/main/java/com/binance/api/client/exception/UnsupportedEventException.java @@ -0,0 +1,9 @@ +package com.binance.api.client.exception; + +public class UnsupportedEventException extends IllegalArgumentException { + private static final long serialVersionUID = -1852755188564122928L; + + public UnsupportedEventException(String message) { + super(message); + } +} 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..d3e5c22f6 --- /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(MarginNewOrder 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.getSideEffectType(), 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 08b5f9ffd..e6ea387b9 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -2,6 +2,7 @@ import com.binance.api.client.BinanceApiAsyncRestClient; import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.config.BinanceApiConfig; import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.account.Account; import com.binance.api.client.domain.account.DepositAddress; @@ -12,11 +13,14 @@ 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; @@ -59,6 +63,12 @@ public void getExchangeInfo(BinanceApiCallback callback) { binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); } + @Override + public void getAllAssets(BinanceApiCallback> callback) { + binanceApiService.getAllAssets(BinanceApiConfig.getAssetInfoApiBaseUrl() + "assetWithdraw/getAllAsset.html") + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + // Market Data endpoints @Override @@ -100,7 +110,7 @@ public void getCandlestickBars(String symbol, CandlestickInterval interval, Bina 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)); @@ -110,7 +120,7 @@ public void getAll24HrPriceStatistics(BinanceApiCallback> 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)); @@ -123,16 +133,24 @@ public void getBookTickers(BinanceApiCallback> 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.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + if (order.getQuoteOrderQty() == null) { + 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)); + } else { + binanceApiService.newOrderQuoteQty(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuoteOrderQty(), 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.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); } // Account endpoints @@ -145,7 +163,7 @@ public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCall } @Override - public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { + 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)); @@ -191,8 +209,8 @@ public void getMyTrades(String symbol, BinanceApiCallback> callback) } @Override - public void withdraw(String asset, String address, String amount, String name, BinanceApiCallback callback) { - binanceApiService.withdraw(asset, address, amount, name, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + 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)); } @@ -230,4 +248,4 @@ public void keepAliveUserDataStream(String listenKey, BinanceApiCallback c public void closeUserDataStream(String listenKey, BinanceApiCallback callback) { binanceApiService.closeAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); } -} \ No newline at end of file +} 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 6ec5a3614..355fa1348 --- a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java @@ -1,47 +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); - throw new BinanceApiException(apiError); - } catch (IOException e) { - throw new BinanceApiException(e); - } - } - } - - @Override - public void onFailure(Call call, Throwable throwable) { - throw 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..959fa2a5f --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -0,0 +1,119 @@ +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 MarginNewOrderResponse newOrder(MarginNewOrder 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.getSideEffectType(), 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 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 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(); + 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 a88e9d731..c80c7a06d --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -1,28 +1,14 @@ package com.binance.api.client.impl; import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.config.BinanceApiConfig; 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.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 com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.*; +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 com.binance.api.client.domain.market.*; +import retrofit2.Call; import java.util.List; @@ -30,196 +16,266 @@ import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; /** - * Implementation of Binance's REST API using Retrofit with synchronous/blocking method calls. + * 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()); - } - - // 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.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.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 void cancelOrder(CancelOrderRequest cancelOrderRequest) { - 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 void withdraw(String asset, String address, String amount, String name) { - executeSync(binanceApiService.withdraw(asset, address, amount, name, 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)); - } + 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(BinanceApiConfig.getAssetInfoApiBaseUrl() + "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) { + final Call call; + if (order.getQuoteOrderQty() == null) { + call = 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()); + } else { + call = binanceApiService.newOrderQuoteQty(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuoteOrderQty(), order.getPrice(), order.getNewClientOrderId(), + order.getStopPrice(), order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), + order.getTimestamp()); + } + return executeSync(call); + } + + @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 NewOCOResponse newOCO(NewOCO oco) { + return executeSync(binanceApiService.newOCO(oco.getSymbol(), oco.getListClientOrderId(), oco.getSide(), + oco.getQuantity(), oco.getLimitClientOrderId(), oco.getPrice(), oco.getLimitIcebergQty(), + oco.getStopClientOrderId(), oco.getStopPrice(), oco.getStopLimitPrice(), oco.getStopIcebergQty(), + oco.getStopLimitTimeInForce(), oco.getNewOrderRespType(), oco.getRecvWindow(), oco.getTimestamp())); + } + + @Override + public CancelOrderListResponse cancelOrderList(CancelOrderListRequest cancelOrderListRequest) { + return executeSync(binanceApiService.cancelOrderList(cancelOrderListRequest.getSymbol(), cancelOrderListRequest.getOrderListId(), + cancelOrderListRequest.getListClientOrderId(), cancelOrderListRequest.getNewClientOrderId(), + cancelOrderListRequest.getRecvWindow(), cancelOrderListRequest.getTimestamp())); + } + + @Override + public OrderList getOrderListStatus(OrderListStatusRequest orderListStatusRequest) { + return executeSync(binanceApiService.getOrderListStatus(orderListStatusRequest.getOrderListId(), orderListStatusRequest.getOrigClientOrderId(), + orderListStatusRequest.getRecvWindow(), orderListStatusRequest.getTimestamp())); + } + + @Override + public List getAllOrderList(AllOrderListRequest allOrderListRequest) { + return executeSync(binanceApiService.getAllOrderList(allOrderListRequest.getFromId(), allOrderListRequest.getStartTime(), + allOrderListRequest.getEndTime(), allOrderListRequest.getLimit(), allOrderListRequest.getRecvWindow(), allOrderListRequest.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 List getMyTrades(String symbol, Long fromId) { + return getMyTrades(symbol, null, fromId, 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 DustTransferResponse dustTranfer(List asset) { + return executeSync(binanceApiService.dustTransfer(asset, 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 List getSubAccountTransfers() { + return executeSync(binanceApiService.getSubAccountTransfers(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 b2d21cd4c..5825f9844 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -3,31 +3,18 @@ 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.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.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.*; +import com.binance.api.client.domain.account.request.CancelOrderListResponse; +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 com.binance.api.client.domain.market.*; 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.*; import java.util.List; @@ -36,127 +23,312 @@ */ 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/v3/exchangeInfo") + Call getExchangeInfo(); + + @GET + Call> getAllAssets(@Url String url); - @GET("/api/v1/exchangeInfo") - Call getExchangeInfo(); + // 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); - // Market data endpoints + @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/depth") - Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); + @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") + 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); - @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("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("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("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); -} \ No newline at end of file + @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) + @POST("/api/v3/order/oco") + Call newOCO(@Query("symbol") String symbol, @Query("listClientOrderId") String listClientOrderId, @Query("side") OrderSide side, + @Query("quantity") String quantity, @Query("limitClientOrderId") String limitClientOrderId, @Query("price") String price, + @Query("limitIcebergQty") String limitIcebergQty, @Query("stopClientOrderId")String stopClientOrderId, @Query("stopPrice") String stopPrice, + @Query("stopLimitPrice")String stopLimitPrice, @Query("stopIcebergQty") String stopIcebergQty, @Query("stopLimitTimeInForce") TimeInForce stopLimitTimeInForce, + @Query("newOrderRespType") NewOrderResponseType newOrderRespType, @Query("recvWindow") Long recvWindow, @Query("timestamp") long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/api/v3/orderList") + Call cancelOrderList(@Query("symbol") String symbol, @Query("orderListId") Long orderListId, @Query("listClientOrderId") String listClientOrderId, + @Query("newClientOrderId") String newClientOrderId, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/orderList") + Call getOrderListStatus(@Query("orderListId") Long orderListId, @Query("origClientOrderId") String origClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/allOrderList") + Call> getAllOrderList(@Query("fromId") Long fromId, @Query("startTime") Long startTime, @Query("endTime") Long endTime, + @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); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/asset/dust") + Call dustTransfer(@Query("asset") List asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/sub-account/transfer/subUserHistory") + Call> getSubAccountTransfers(@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("sideEffectType") SideEffectType sideEffectType, @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); + + // 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); + + +} 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 6d7ee2b76..dec8d3047 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -1,46 +1,82 @@ package com.binance.api.client.impl; import com.binance.api.client.BinanceApiError; -import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.config.BinanceApiConfig; import com.binance.api.client.exception.BinanceApiException; import com.binance.api.client.security.AuthenticationInterceptor; +import okhttp3.Dispatcher; import okhttp3.OkHttpClient; +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 { - static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); + private static final OkHttpClient sharedClient; + private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); - private static Retrofit.Builder builder = - new Retrofit.Builder() - .baseUrl(BinanceApiConstants.API_BASE_URL) - .addConverterFactory(JacksonConverterFactory.create()); + static { + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequestsPerHost(500); + dispatcher.setMaxRequests(500); + sharedClient = new OkHttpClient.Builder() + .dispatcher(dispatcher) + .pingInterval(20, TimeUnit.SECONDS) + .build(); + } - private static Retrofit retrofit = builder.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); } + /** + * Create a Binance API service. + * + * @param serviceClass the type of service. + * @param apiKey Binance API key. + * @param secret Binance secret. + * + * @return a new implementation of the API endpoints for the Binance API service. + */ public static S createService(Class serviceClass, String apiKey, String secret) { - if (!StringUtils.isEmpty(apiKey) && !StringUtils.isEmpty(secret)) { + String baseUrl = null; + if (!BinanceApiConfig.useTestnet) { baseUrl = BinanceApiConfig.getApiBaseUrl(); } + else { + baseUrl = /*BinanceApiConfig.useTestnetStreaming ? + BinanceApiConfig.getStreamTestNetBaseUrl() :*/ + BinanceApiConfig.getTestNetBaseUrl(); + } + + Retrofit.Builder retrofitBuilder = new Retrofit.Builder() + .baseUrl(baseUrl) + .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); - if (!httpClient.interceptors().contains(interceptor)) { - httpClient.addInterceptor(interceptor); - builder.client(httpClient.build()); - retrofit = builder.build(); - } + OkHttpClient adaptedClient = sharedClient.newBuilder().addInterceptor(interceptor).build(); + retrofitBuilder.client(adaptedClient); } + + Retrofit retrofit = retrofitBuilder.build(); return retrofit.create(serviceClass); } @@ -65,7 +101,13 @@ public static T executeSync(Call call) { * Extracts and converts the response error body into an object. */ public static BinanceApiError getBinanceApiError(Response response) throws IOException, BinanceApiException { - return (BinanceApiError)retrofit.responseBodyConverter(BinanceApiError.class, new Annotation[0]) - .convert(response.errorBody()); + 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/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/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 87ff981ab..4d68fb436 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -2,47 +2,53 @@ 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.config.BinanceApiConfig; +import com.binance.api.client.domain.event.*; import com.binance.api.client.domain.market.CandlestickInterval; -import okhttp3.Dispatcher; +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 OkHttpClient client; + private final OkHttpClient client; - public BinanceApiWebSocketClientImpl() { - Dispatcher d = new Dispatcher(); - d.setMaxRequestsPerHost(100); - this.client = new OkHttpClient.Builder().dispatcher(d).build(); + public BinanceApiWebSocketClientImpl(OkHttpClient client) { + this.client = client; } - public Closeable onDepthEvent(String symbol, BinanceApiCallback callback) { - final String channel = String.format("%s@depth", symbol); + @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 symbol, CandlestickInterval interval, BinanceApiCallback callback) { - final String channel = String.format("%s@kline_%s", symbol, interval.getIntervalId()); + 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 symbol, BinanceApiCallback callback) { - final String channel = String.format("%s@aggTrade", symbol); + 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)); } @@ -50,18 +56,44 @@ public Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback(callback, UserDataUpdateEvent.class)); } - public Closeable onAllMarketTickersEvent(BinanceApiCallback> callback) { + @Override + public Closeable onTickerEvent(String symbols, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@ticker", s)) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, TickerEvent.class)); + } + + public Closeable onAllMarketTickersEvent(BinanceApiCallback> callback) { final String channel = "!ticker@arr"; - return createNewWebSocket(channel, new BinanceApiWebSocketListener>(callback)); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() { + })); + } + + @Override + public Closeable onBookTickerEvent(String symbols, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@bookTicker", s)) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, BookTickerEvent.class)); + } + + public Closeable onAllBookTickersEvent(BinanceApiCallback callback) { + final String channel = "!bookTicker"; + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, BookTickerEvent.class)); } + /** + * @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() { - client.dispatcher().executorService().shutdown(); } private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { - String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); + String streamingUrl = String.format("%s/%s", BinanceApiConfig.useTestnetStreaming?BinanceApiConfig.getStreamTestNetBaseUrl():BinanceApiConfig.getStreamApiBaseUrl(), channel); Request request = new Request.Builder().url(streamingUrl).build(); final WebSocket webSocket = client.newWebSocket(request, listener); return () -> { 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 978317c08..e2004090e --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java @@ -1,62 +1,58 @@ -package com.binance.api.client.impl; - -import java.io.IOException; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -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; - -/** - * Binance API WebSocket listener. - */ -public class BinanceApiWebSocketListener extends WebSocketListener { - - private BinanceApiCallback callback; - - private Class eventClass; - - private TypeReference eventTypeReference; - - private boolean closing = false; - - public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) { - this.callback = callback; - this.eventClass = eventClass; - } - - public BinanceApiWebSocketListener(BinanceApiCallback callback) { - this.callback = callback; - this.eventTypeReference = new TypeReference() {}; - } - - @Override - public void onMessage(WebSocket webSocket, String text) { - ObjectMapper mapper = new ObjectMapper(); - try { - T event = null; - if (eventClass == null) { - event = mapper.readValue(text, eventTypeReference); - } else { - event = mapper.readValue(text, eventClass); - } - 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 3dc5c9b5a..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_SIGNED) - .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 a1c7905c1..62d100ef2 --- a/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java +++ b/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java @@ -1,76 +1,81 @@ -package com.binance.api.client.constant; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.market.Candlestick; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; - -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 new file mode 100755 index 000000000..f65e5eefe --- /dev/null +++ b/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java @@ -0,0 +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); + } +} \ No newline at end of file diff --git a/src/test/java/com/binance/api/client/impl/BinanceApiServiceGeneratorTest.java b/src/test/java/com/binance/api/client/impl/BinanceApiServiceGeneratorTest.java deleted file mode 100644 index 132809c75..000000000 --- a/src/test/java/com/binance/api/client/impl/BinanceApiServiceGeneratorTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.binance.api.client.impl; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author andy coates - * created 08/02/2018. - */ -public class BinanceApiServiceGeneratorTest { - @Test - public void shouldOnlyAddAuthInterceptorOnce() throws Exception { - // Given: - BinanceApiServiceGenerator.createService(BinanceApiService.class, "someKey", "someValue"); - final int initialSize = BinanceApiServiceGenerator.httpClient.interceptors().size(); - - // When: - BinanceApiServiceGenerator.createService(BinanceApiService.class, "someKey", "someValue"); - - // Then - assertEquals(BinanceApiServiceGenerator.httpClient.interceptors().size(), initialSize); - } -} \ 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 36346b1ea..03ce3e00d --- 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(), 123456L); - assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), 1L); - } 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\":\"outboundAccountPosition\",\"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(), "outboundAccountPosition"); + 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 af949ff6f..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\": \"REQUESTS\",\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.REQUESTS, 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..59978bb93 --- 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_POSITION_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_POSITION_UPDATE) { + // Override cached asset balances + for (AssetBalance assetBalance : response.getOutboundAccountPositionUpdateEvent().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 bdbaf7469..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(6000000L, 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); - } -} +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 560b4f27f..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, 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 e1724e321..25adc8c55 --- a/src/test/java/com/binance/api/examples/DepthCacheExample.java +++ b/src/test/java/com/binance/api/examples/DepthCacheExample.java @@ -1,201 +1,244 @@ -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.DepthEvent; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.OrderBookEntry; - -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. - */ -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 AtomicReference> wsCallback = new AtomicReference<>(); - private final Map> depthCache = new HashMap<>(); - - private long lastUpdateId = -1; - - public DepthCacheExample(String symbol) { - this.symbol = symbol; - - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - wsClient = factory.newWebSocketClient(); - restClient = factory.newRestClient(); - - // 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(); - - 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.set(pendingDeltas::add); - - wsClient.onDepthEvent(symbol.toLowerCase(), event -> wsCallback.get().accept(event)); - - 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.set(updateOrderBook); - }; - - wsCallback.set(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; - } - - /** - * 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"); - } -} +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 a97c7ec27..760d6f26a --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java @@ -1,39 +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.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; - -/** - * 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()); - } -} +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 8823f1824..96739a5c2 --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java @@ -1,38 +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.FilterType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; - -/** - * 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()); - }); - } -} +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..4cc4bf01f --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -0,0 +1,28 @@ +package com.binance.api.examples; + +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; + +/** + * 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(); + 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"); + System.out.println(repaid); + RepayQueryResult repayQueryResult = client.queryRepay("BNB", System.currentTimeMillis() - 1000); + System.out.println(repayQueryResult); + } +} 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..969ca784f --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginOrdersExample.java @@ -0,0 +1,49 @@ +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.MarginNewOrderResponse; +import com.binance.api.client.domain.account.NewOrderResponseType; +import com.binance.api.client.domain.account.Order; +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.MarginNewOrder.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 + MarginNewOrderResponse 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..b07a01792 --- /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.MarginNewOrder.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..6a27a5fa4 --- /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_POSITION_UPDATE) { + AccountUpdateEvent accountUpdateEvent = response.getOutboundAccountPositionUpdateEvent(); + // 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 0b8be5256..a1dd9d6cd --- a/src/test/java/com/binance/api/examples/OrdersExample.java +++ b/src/test/java/com/binance/api/examples/OrdersExample.java @@ -1,58 +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.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.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 { - client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); - } 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")); - 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 9f766ff02..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("Order has been canceled.")); - - // 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/SwapEndpointExample.java b/src/test/java/com/binance/api/examples/SwapEndpointExample.java new file mode 100755 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); + } + + +} diff --git a/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java b/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java new file mode 100755 index 000000000..5abfe04f1 --- /dev/null +++ b/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java @@ -0,0 +1,63 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.constant.Util; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.AssetBalance; + +/** + * Example how to get total of balances on your account + */ +public class TotalAccountBalanceExample { + + + 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()); + + // Get total account balance in BTC (spot only) + TotalAccountBalanceExample accountBalance = new TotalAccountBalanceExample(); + double totalBalanceInBTC = accountBalance.getTotalAccountBalance(client,account); + System.out.println(totalBalanceInBTC); + // Get total account balance in USDT (spot only) + double totalBalanceInUSDT = totalBalanceInBTC * Double.parseDouble(client.getPrice("BTCUSDT").getPrice()); + System.out.println(totalBalanceInUSDT); + + + + + } + + // Get total account balance in BTC (spot only) + public double getTotalAccountBalance(BinanceApiRestClient client, Account account) { + double totalBalance = 0; + for (AssetBalance balance : account.getBalances()) { + double free = Double.parseDouble(balance.getFree()); + double locked = Double.parseDouble(balance.getLocked()); + String ticker = balance.getAsset() + Util.BTC_TICKER; + String tickerReverse = Util.BTC_TICKER + balance.getAsset(); + if (free + locked != 0) { + if (Util.isFiatCurrency(balance.getAsset())) { + double price = Double.parseDouble(client.getPrice(tickerReverse).getPrice()); + double amount = (free + locked) / price; + totalBalance += amount; + } else { + double price = Double.parseDouble(client.getPrice(ticker).getPrice()); + double amount = price * (free + locked); + totalBalance += amount; + } + + } + } + + return totalBalance; + + } + + + +} 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..b74eed727 --- 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_POSITION_UPDATE) { + AccountUpdateEvent accountUpdateEvent = response.getOutboundAccountPositionUpdateEvent(); + // 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); + } +}