From 0c9354f7ef970c550ba70cf0a05aa16b136fd99b Mon Sep 17 00:00:00 2001 From: Andy Coates Date: Sun, 25 Feb 2018 20:40:22 +0000 Subject: [PATCH 01/83] Add reconnect & close logic --- .../api/examples/DepthCacheExample.java | 61 ++++++++++++++++--- 1 file changed, 52 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/binance/api/examples/DepthCacheExample.java b/src/test/java/com/binance/api/examples/DepthCacheExample.java index e1724e321..eb1975796 100644 --- a/src/test/java/com/binance/api/examples/DepthCacheExample.java +++ b/src/test/java/com/binance/api/examples/DepthCacheExample.java @@ -1,5 +1,6 @@ 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; @@ -7,6 +8,8 @@ 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; @@ -33,6 +36,8 @@ * 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 { @@ -42,24 +47,30 @@ public class DepthCacheExample { private final String symbol; private final BinanceApiRestClient restClient; private final BinanceApiWebSocketClient wsClient; - private final AtomicReference> wsCallback = new AtomicReference<>(); + 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(); - wsClient = factory.newWebSocketClient(); - restClient = factory.newRestClient(); + 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); } @@ -70,9 +81,9 @@ public DepthCacheExample(String symbol) { */ private List startDepthEventStreaming() { final List pendingDeltas = new CopyOnWriteArrayList<>(); - wsCallback.set(pendingDeltas::add); + wsCallback.setHandler(pendingDeltas::add); - wsClient.onDepthEvent(symbol.toLowerCase(), event -> wsCallback.get().accept(event)); + this.webSocket = wsClient.onDepthEvent(symbol.toLowerCase(), wsCallback); return pendingDeltas; } @@ -118,14 +129,15 @@ private void applyPendingDeltas(final List pendingDeltas) { // 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 + .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.setHandler(updateOrderBook); }; - wsCallback.set(drainPending); + wsCallback.setHandler(drainPending); } /** @@ -133,7 +145,8 @@ private void applyPendingDeltas(final List pendingDeltas) { * * Whenever the qty specified is ZERO, it means the price should was removed from the order book. */ - private void updateOrderBook(NavigableMap lastOrderBookEntries, List orderBookDeltas) { + private void updateOrderBook(NavigableMap lastOrderBookEntries, + List orderBookDeltas) { for (OrderBookEntry orderBookDelta : orderBookDeltas) { BigDecimal price = new BigDecimal(orderBookDelta.getPrice()); BigDecimal qty = new BigDecimal(orderBookDelta.getQty()); @@ -175,6 +188,10 @@ 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. */ @@ -198,4 +215,30 @@ private static String toDepthCacheEntryString(Map.Entry 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); + } + } } From 8571a99e76532bbb3f5b84b4a15588525e6ab274 Mon Sep 17 00:00:00 2001 From: TobCar Date: Tue, 13 Mar 2018 18:04:40 -0700 Subject: [PATCH 02/83] Add support for AllAssets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Although not a part of the official API, the getAllAsset page on Binance’s website is useful for determining whether an asset can be withdrawn. --- .../api/client/domain/general/AllAssets.java | 123 ++++++++++++++++++ .../api/client/impl/BinanceApiService.java | 10 +- 2 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/general/AllAssets.java diff --git a/src/main/java/com/binance/api/client/domain/general/AllAssets.java b/src/main/java/com/binance/api/client/domain/general/AllAssets.java new file mode 100644 index 000000000..3923021d7 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/general/AllAssets.java @@ -0,0 +1,123 @@ +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * All assets Binance supports. + */ + @JsonIgnoreProperties(ignoreUnknown = true) + public class AllAssets { + + @JsonProperty("id") + private String id; + + @JsonProperty("assetCode") + private String assetCode; + + @JsonProperty("assetName") + private String assetName; + + @JsonProperty("unit") + private String unit; + + @JsonProperty("transactionFee") + private long transactionFee; + + @JsonProperty("commissionRate") + private long commissionRate; + + @JsonProperty("freeAuditWithdrawAmt") + private long freeAuditWithdrawAmount; + + @JsonProperty("freeUserChargeAmount") + private long freeUserChargeAmount; + + @JsonProperty("minProductWithdraw") + private long minProductWithdraw; + + @JsonProperty("withdrawIntegerMultiple") + private long 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 long getTransactionFee() { + return transactionFee; + } + + public long getCommissionRate() { + return commissionRate; + } + + public long getFreeAuditWithdrawAmount() { + return freeAuditWithdrawAmount; + } + + public long getFreeUserChargeAmount() { + return freeUserChargeAmount; + } + + public long minProductWithdraw() { + return minProductWithdraw; + } + + public long getWithdrawIntegerMultiple() { + return withdrawIntegerMultiple; + } + + public long getConfirmTimes() { + return confirmTimes; + } + + public long canWithraw() { + return enableWithdraw; + } + + public long isLegalMoney() { + return isLegalMoney; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_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/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index b2d21cd4c..794282765 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -15,6 +15,7 @@ import com.binance.api.client.domain.event.ListenKey; import com.binance.api.client.domain.general.ExchangeInfo; import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.general.AllAssets; import com.binance.api.client.domain.market.AggTrade; import com.binance.api.client.domain.market.BookTicker; import com.binance.api.client.domain.market.Candlestick; @@ -47,6 +48,9 @@ public interface BinanceApiService { @GET("/api/v1/exchangeInfo") Call getExchangeInfo(); + @GET("/assetWithdraw/getAllAsset.html") + Call getAllAssets(); + // Market data endpoints @GET("/api/v1/depth") @@ -69,13 +73,13 @@ Call> getCandlestickBars(@Query("symbol") String symbol, @Quer @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); @@ -159,4 +163,4 @@ Call withdraw(@Query("asset") String asset, @Query("address") String addre @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) @DELETE("/api/v1/userDataStream") Call closeAliveUserDataStream(@Query("listenKey") String listenKey); -} \ No newline at end of file +} From 91dd28f957424d13b1cd625cb2303502ee64d49d Mon Sep 17 00:00:00 2001 From: TobCar Date: Sun, 25 Mar 2018 15:19:32 -0700 Subject: [PATCH 03/83] Expose getAllAssets JSON call --- .../binance/api/client/BinanceApiRestClient.java | 14 ++++++++++---- .../client/impl/BinanceApiAsyncRestClientImpl.java | 12 +++++++++--- .../api/client/impl/BinanceApiRestClientImpl.java | 8 +++++++- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index 97669356b..d9cc3b931 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -14,6 +14,7 @@ import com.binance.api.client.domain.account.request.OrderRequest; import com.binance.api.client.domain.account.request.OrderStatusRequest; import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.AllAssets; import com.binance.api.client.domain.market.AggTrade; import com.binance.api.client.domain.market.BookTicker; import com.binance.api.client.domain.market.Candlestick; @@ -43,6 +44,11 @@ public interface BinanceApiRestClient { */ Long getServerTime(); + /** + * @return All the assets Binance supports and whether or not they can be withdrawn. + */ + AllAssets getAllAssets(); + /** * @return Current exchange trading rules and symbol information */ @@ -123,7 +129,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 +139,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); @@ -286,4 +292,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/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java index 08b5f9ffd..e4237a056 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -17,6 +17,7 @@ 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.AllAssets; import com.binance.api.client.domain.general.ExchangeInfo; import com.binance.api.client.domain.general.ServerTime; import com.binance.api.client.domain.market.AggTrade; @@ -54,6 +55,11 @@ public void getServerTime(BinanceApiCallback callback) { binanceApiService.getServerTime().enqueue(new BinanceApiCallbackAdapter<>(callback)); } + @Override + public void getAllAssets(BinanceApiCallback callback) { + binanceApiService.getAllAssets().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + @Override public void getExchangeInfo(BinanceApiCallback callback) { binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); @@ -100,7 +106,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 +116,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)); @@ -230,4 +236,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/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index a88e9d731..7ba6f97e3 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -15,6 +15,7 @@ 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.general.AllAssets; import com.binance.api.client.domain.general.ExchangeInfo; import com.binance.api.client.domain.market.AggTrade; import com.binance.api.client.domain.market.BookTicker; @@ -52,6 +53,11 @@ public Long getServerTime() { return executeSync(binanceApiService.getServerTime()).getServerTime(); } + @Override + public AllAssets getAllAssets() { + return executeSync(binanceApiService.getAllAssets()); + } + @Override public ExchangeInfo getExchangeInfo() { return executeSync(binanceApiService.getExchangeInfo()); @@ -108,7 +114,7 @@ public List getAll24HrPriceStatistics() { public TickerPrice getPrice(String symbol) { return executeSync(binanceApiService.getLatestPrice(symbol)); } - + @Override public List getAllPrices() { return executeSync(binanceApiService.getLatestPrices()); From 69f56f5fcfc8aadf00fdbfe38cd0aaec80aa6da8 Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Mon, 26 Mar 2018 17:43:18 +0200 Subject: [PATCH 04/83] Fixes #103: Add support for fetching all assets. --- .../api/client/BinanceApiAsyncRestClient.java | 6 ++ .../api/client/BinanceApiRestClient.java | 10 +-- .../client/constant/BinanceApiConstants.java | 5 ++ .../general/{AllAssets.java => Asset.java} | 36 +++++----- .../impl/BinanceApiAsyncRestClientImpl.java | 11 ++-- .../client/impl/BinanceApiRestClientImpl.java | 10 +-- .../api/client/impl/BinanceApiService.java | 7 +- .../constant/BinanceApiConstantsTest.java | 65 ++++++++++--------- .../api/examples/GeneralEndpointsExample.java | 7 ++ .../GeneralEndpointsExampleAsync.java | 7 ++ 10 files changed, 98 insertions(+), 66 deletions(-) rename src/main/java/com/binance/api/client/domain/general/{AllAssets.java => Asset.java} (74%) diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java index 4916e16e6..69416d50a 100644 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -14,6 +14,7 @@ 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; @@ -48,6 +49,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 /** diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index d9cc3b931..3044363f7 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -14,7 +14,7 @@ import com.binance.api.client.domain.account.request.OrderRequest; import com.binance.api.client.domain.account.request.OrderStatusRequest; import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.AllAssets; +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; @@ -45,14 +45,14 @@ public interface BinanceApiRestClient { Long getServerTime(); /** - * @return All the assets Binance supports and whether or not they can be withdrawn. + * @return Current exchange trading rules and symbol information */ - AllAssets getAllAssets(); + ExchangeInfo getExchangeInfo(); /** - * @return Current exchange trading rules and symbol information + * @return All the supported assets and whether or not they can be withdrawn. */ - ExchangeInfo getExchangeInfo(); + List getAllAssets(); // Market Data endpoints diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java index 5fe72265b..00c4b2f71 100644 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -17,6 +17,11 @@ public class BinanceApiConstants { */ public static final String WS_API_BASE_URL = "wss://stream.binance.com:9443/ws"; + /** + * Asset info base URL. + */ + public static final String ASSET_INFO_API_BASE_URL = "https://binance.com/"; + /** * HTTP Header to be used for API-KEY authentication. */ diff --git a/src/main/java/com/binance/api/client/domain/general/AllAssets.java b/src/main/java/com/binance/api/client/domain/general/Asset.java similarity index 74% rename from src/main/java/com/binance/api/client/domain/general/AllAssets.java rename to src/main/java/com/binance/api/client/domain/general/Asset.java index 3923021d7..4a286acc6 100644 --- a/src/main/java/com/binance/api/client/domain/general/AllAssets.java +++ b/src/main/java/com/binance/api/client/domain/general/Asset.java @@ -1,15 +1,15 @@ 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; -import org.apache.commons.lang3.builder.ToStringStyle; /** - * All assets Binance supports. + * An asset Binance supports. */ @JsonIgnoreProperties(ignoreUnknown = true) - public class AllAssets { + public class Asset { @JsonProperty("id") private String id; @@ -24,22 +24,22 @@ public class AllAssets { private String unit; @JsonProperty("transactionFee") - private long transactionFee; + private String transactionFee; @JsonProperty("commissionRate") - private long commissionRate; + private String commissionRate; @JsonProperty("freeAuditWithdrawAmt") - private long freeAuditWithdrawAmount; + private String freeAuditWithdrawAmount; @JsonProperty("freeUserChargeAmount") - private long freeUserChargeAmount; + private String freeUserChargeAmount; @JsonProperty("minProductWithdraw") - private long minProductWithdraw; + private String minProductWithdraw; @JsonProperty("withdrawIntegerMultiple") - private long withdrawIntegerMultiple; + private String withdrawIntegerMultiple; @JsonProperty("confirmTimes") private long confirmTimes; @@ -66,27 +66,27 @@ public String getUnit() { return unit; } - public long getTransactionFee() { + public String getTransactionFee() { return transactionFee; } - public long getCommissionRate() { + public String getCommissionRate() { return commissionRate; } - public long getFreeAuditWithdrawAmount() { + public String getFreeAuditWithdrawAmount() { return freeAuditWithdrawAmount; } - public long getFreeUserChargeAmount() { + public String getFreeUserChargeAmount() { return freeUserChargeAmount; } - public long minProductWithdraw() { + public String minProductWithdraw() { return minProductWithdraw; } - public long getWithdrawIntegerMultiple() { + public String getWithdrawIntegerMultiple() { return withdrawIntegerMultiple; } @@ -94,17 +94,17 @@ public long getConfirmTimes() { return confirmTimes; } - public long canWithraw() { + public boolean canWithraw() { return enableWithdraw; } - public long isLegalMoney() { + public boolean isLegalMoney() { return isLegalMoney; } @Override public String toString() { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) .append("id", id) .append("assetCode", assetCode) .append("assetName", assetName) diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java index e4237a056..5f97af80c 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -17,7 +17,7 @@ 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.AllAssets; +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; @@ -56,13 +56,14 @@ public void getServerTime(BinanceApiCallback callback) { } @Override - public void getAllAssets(BinanceApiCallback callback) { - binanceApiService.getAllAssets().enqueue(new BinanceApiCallbackAdapter<>(callback)); + public void getExchangeInfo(BinanceApiCallback callback) { + binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); } @Override - public void getExchangeInfo(BinanceApiCallback callback) { - binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); + public void getAllAssets(BinanceApiCallback> callback) { + binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html") + .enqueue(new BinanceApiCallbackAdapter<>(callback)); } // Market Data endpoints diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index 7ba6f97e3..301a08aab 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -15,7 +15,7 @@ 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.general.AllAssets; +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; @@ -54,13 +54,13 @@ public Long getServerTime() { } @Override - public AllAssets getAllAssets() { - return executeSync(binanceApiService.getAllAssets()); + public ExchangeInfo getExchangeInfo() { + return executeSync(binanceApiService.getExchangeInfo()); } @Override - public ExchangeInfo getExchangeInfo() { - return executeSync(binanceApiService.getExchangeInfo()); + public List getAllAssets() { + return executeSync(binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html")); } // Market Data endpoints diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 794282765..5d7921df8 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -13,9 +13,9 @@ import com.binance.api.client.domain.account.TradeHistoryItem; import com.binance.api.client.domain.account.WithdrawHistory; 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.general.AllAssets; import com.binance.api.client.domain.market.AggTrade; import com.binance.api.client.domain.market.BookTicker; import com.binance.api.client.domain.market.Candlestick; @@ -29,6 +29,7 @@ import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Query; +import retrofit2.http.Url; import java.util.List; @@ -48,8 +49,8 @@ public interface BinanceApiService { @GET("/api/v1/exchangeInfo") Call getExchangeInfo(); - @GET("/assetWithdraw/getAllAsset.html") - Call getAllAssets(); + @GET + Call> getAllAssets(@Url String url); // Market data endpoints diff --git a/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java b/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java index a1c7905c1..d003a8d94 100644 --- 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.*; +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() { + + 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" - + " ]"; + + " 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/examples/GeneralEndpointsExample.java b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java index a97c7ec27..911cab374 100644 --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java @@ -2,11 +2,14 @@ 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. */ @@ -35,5 +38,9 @@ public static void main(String[] args) { 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 index 8823f1824..77bfd238e 100644 --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java @@ -2,10 +2,13 @@ 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. */ @@ -34,5 +37,9 @@ public static void main(String[] args) throws InterruptedException { 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())); } } From 97a08b04196588a7a357518a7cf55a0adef757d9 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Wed, 25 Apr 2018 23:04:26 +0200 Subject: [PATCH 05/83] Route exceptions via onFailure callback rather than throwing them --- .../api/client/impl/BinanceApiCallbackAdapter.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java index 6ec5a3614..10b896ac6 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java @@ -33,15 +33,19 @@ public void onResponse(Call call, Response response) { } try { BinanceApiError apiError = getBinanceApiError(response); - throw new BinanceApiException(apiError); + onFailure(call, new BinanceApiException(apiError)); } catch (IOException e) { - throw new BinanceApiException(e); + onFailure(call, new BinanceApiException(e)); } } } @Override public void onFailure(Call call, Throwable throwable) { - throw new BinanceApiException(throwable); + if (throwable instanceof BinanceApiException) { + callback.onFailure(throwable); + } else { + callback.onFailure(new BinanceApiException(throwable)); + } } } From 1c90686d4e915c3e6ab67b27ebcdb524776817c3 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Sun, 29 Apr 2018 20:06:49 +0200 Subject: [PATCH 06/83] Add support for newOrderRespType (v3 API) --- .../api/client/domain/account/NewOrder.java | 16 ++++ .../domain/account/NewOrderResponse.java | 84 +++++++++++++++++++ .../domain/account/NewOrderResponseType.java | 12 +++ .../impl/BinanceApiAsyncRestClientImpl.java | 4 +- .../client/impl/BinanceApiRestClientImpl.java | 4 +- .../api/client/impl/BinanceApiService.java | 7 +- 6 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java 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 index af76a78b2..635e1ddac 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -56,6 +56,11 @@ public class NewOrder { */ private String icebergQty; + /** + * Set the response JSON. ACK, RESULT, or FULL; default: RESULT. + */ + private NewOrderResponseType newOrderRespType; + /** * Receiving window. */ @@ -75,6 +80,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; } @@ -168,6 +174,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; } @@ -234,6 +249,7 @@ public String toString() { .append("newClientOrderId", newClientOrderId) .append("stopPrice", stopPrice) .append("icebergQty", icebergQty) + .append("newOrderRespType", newOrderRespType) .append("recvWindow", recvWindow) .append("timestamp", timestamp) .toString(); diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java index 7485f175e..c42246057 100644 --- 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,9 +1,16 @@ 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.List; +import java.util.stream.Collectors; + /** * Response returned when placing a new order on the system. * @@ -28,6 +35,20 @@ public class NewOrderResponse { */ private String clientOrderId; + private String price; + + private String executedQty; + + private OrderStatus status; + + private TimeInForce timeInForce; + + private OrderType type; + + private OrderSide side; + + private List fills; + /** * Transact time for this order. */ @@ -65,6 +86,62 @@ public void setTransactTime(Long transactTime) { this.transactTime = transactTime; } + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getExecutedQty() { + return executedQty; + } + + public void setExecutedQty(String executedQty) { + this.executedQty = executedQty; + } + + public OrderStatus getStatus() { + return status; + } + + public void setStatus(OrderStatus status) { + this.status = status; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public 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) @@ -72,6 +149,13 @@ public String toString() { .append("orderId", orderId) .append("clientOrderId", clientOrderId) .append("transactTime", transactTime) + .append("price", price) + .append("executedQty", executedQty) + .append("status", status) + .append("timeInForce", timeInForce) + .append("type", type) + .append("side", side) + .append("fills", fills.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 100644 index 000000000..c465f85a7 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java @@ -0,0 +1,12 @@ +package com.binance.api.client.domain.account; + +/** + * Desired response type of NewOrder requests. + * @see NewOrderResponse + */ +public enum NewOrderResponseType { + ACK, + RESULT, + FULL +} + diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java index 5f97af80c..e35a29e85 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -132,14 +132,14 @@ public void getBookTickers(BinanceApiCallback> callback) { 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)); + 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 diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index 301a08aab..364f48a58 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -129,14 +129,14 @@ public List getBookTickers() { 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())); + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); } @Override public void newOrderTest(NewOrder order) { executeSync(binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getRecvWindow(), order.getTimestamp())); + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); } // Account endpoints diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 5d7921df8..37b4cc881 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -8,6 +8,7 @@ import com.binance.api.client.domain.account.DepositAddress; import com.binance.api.client.domain.account.DepositHistory; import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.NewOrderResponseType; import com.binance.api.client.domain.account.Order; import com.binance.api.client.domain.account.Trade; import com.binance.api.client.domain.account.TradeHistoryItem; @@ -94,14 +95,16 @@ Call> getCandlestickBars(@Query("symbol") String symbol, @Quer 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); + @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("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @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") From 7b92e7a40f13c7a77710fc894d1eca354a5580dd Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Sun, 29 Apr 2018 20:11:33 +0200 Subject: [PATCH 07/83] Demonstrate use of newOrderRespType in OrdersExample --- src/test/java/com/binance/api/examples/OrdersExample.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/binance/api/examples/OrdersExample.java b/src/test/java/com/binance/api/examples/OrdersExample.java index 0b8be5256..c133e7432 100644 --- a/src/test/java/com/binance/api/examples/OrdersExample.java +++ b/src/test/java/com/binance/api/examples/OrdersExample.java @@ -4,6 +4,7 @@ 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; @@ -51,7 +52,7 @@ public static void main(String[] args) { client.newOrderTest(marketBuy("LINKETH", "1000")); // Placing a real LIMIT order - NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001")); + NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); System.out.println(newOrderResponse); } From ce38cb8c0903585de8e1bf2230afda32318242c3 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Sun, 29 Apr 2018 21:24:35 +0200 Subject: [PATCH 08/83] Parse both 'id' and 'tradeId' into Trade#id to deal with inconsistent API models on Binance --- .../com/binance/api/client/domain/account/Trade.java | 9 +++++++++ 1 file changed, 9 insertions(+) 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 index feb639faa..c64431118 100644 --- a/src/main/java/com/binance/api/client/domain/account/Trade.java +++ b/src/main/java/com/binance/api/client/domain/account/Trade.java @@ -2,6 +2,7 @@ import com.binance.api.client.constant.BinanceApiConstants; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; import org.apache.commons.lang3.builder.ToStringBuilder; /** @@ -54,10 +55,18 @@ 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; } From d7835f50356e3553235b5824039a0bcc63d5a814 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Sun, 29 Apr 2018 21:24:53 +0200 Subject: [PATCH 09/83] Add NewOrderResponse#origQty --- .../api/client/domain/account/NewOrderResponse.java | 11 +++++++++++ 1 file changed, 11 insertions(+) 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 index c42246057..e1c1e7569 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java @@ -37,6 +37,8 @@ public class NewOrderResponse { private String price; + private String origQty; + private String executedQty; private OrderStatus status; @@ -94,6 +96,14 @@ 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; } @@ -150,6 +160,7 @@ public String toString() { .append("clientOrderId", clientOrderId) .append("transactTime", transactTime) .append("price", price) + .append("origQty", origQty) .append("executedQty", executedQty) .append("status", status) .append("timeInForce", timeInForce) From 16e94f36983b0768811912c23affd2d847dd8396 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Sun, 29 Apr 2018 21:39:32 +0200 Subject: [PATCH 10/83] Demonstrate use of newOrderRespType in README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 46e008f74..102a0b1ac 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,8 @@ System.out.println(order.getExecutedQty()); #### Placing a MARKET order ```java -NewOrderResponse newOrderResponse = client.newOrder(marketBuy("LINKETH", "1000")); +NewOrderResponse newOrderResponse = client.newOrder(marketBuy("LINKETH", "1000").orderRespType(OrderResponseType.FULL)); +List fills = newOrderResponse.getFills(); System.out.println(newOrderResponse.getClientOrderId()); ```
From 6067b086f3d2d84d650a1b16a467c664753f802b Mon Sep 17 00:00:00 2001 From: Igor Ustinov Date: Fri, 4 May 2018 11:55:29 -0400 Subject: [PATCH 11/83] withdrawal status added, conflicts resolved --- .../api/client/BinanceApiAsyncRestClient.java | 4 +- .../api/client/BinanceApiRestClient.java | 4 +- .../client/domain/account/DepositHistory.java | 11 ++++ .../client/domain/account/WithdrawResult.java | 62 +++++++++++++++++++ .../impl/BinanceApiAsyncRestClientImpl.java | 5 +- .../client/impl/BinanceApiRestClientImpl.java | 5 +- .../api/client/impl/BinanceApiService.java | 5 +- .../api/examples/AccountEndpointsExample.java | 2 +- .../AccountEndpointsExampleAsync.java | 2 +- 9 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/account/WithdrawResult.java diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java index 69416d50a..3bf9317cb 100644 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -9,6 +9,7 @@ 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.OrderRequest; @@ -260,8 +261,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/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index 3044363f7..b0f1d165c 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -9,6 +9,7 @@ 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.OrderRequest; @@ -246,8 +247,9 @@ 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. */ - void withdraw(String asset, String address, String amount, String name); + WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag); /** * Fetch account deposit history. 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 index 0d45d32aa..792f3fa9d 100644 --- a/src/main/java/com/binance/api/client/domain/account/DepositHistory.java +++ b/src/main/java/com/binance/api/client/domain/account/DepositHistory.java @@ -18,6 +18,16 @@ public class DepositHistory { private boolean success; + private String msg; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + public List getDepositList() { return depositList; } @@ -39,6 +49,7 @@ 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/WithdrawResult.java b/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java new file mode 100644 index 000000000..fac00deba --- /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/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java index 5f97af80c..a7c0ce575 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -12,6 +12,7 @@ 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.OrderRequest; @@ -198,8 +199,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)); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index 301a08aab..539fda0ab 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -11,6 +11,7 @@ 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.OrderRequest; @@ -193,8 +194,8 @@ public List getMyTrades(String symbol) { } @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())); + 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 diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 5d7921df8..b26ae8b07 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -12,6 +12,7 @@ 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.event.ListenKey; import com.binance.api.client.domain.general.Asset; import com.binance.api.client.domain.general.ExchangeInfo; @@ -135,8 +136,8 @@ Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") In @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); + 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) diff --git a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java index bdbaf7469..a859ca8f1 100644 --- a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java @@ -35,6 +35,6 @@ public static void main(String[] args) { System.out.println(client.getDepositAddress("ETH")); // Withdraw - client.withdraw("ETH", "0x123", "0.1", null); + 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 index 560b4f27f..7e924fdf5 100644 --- a/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java @@ -26,6 +26,6 @@ public static void main(String[] args) { client.getDepositHistory("ETH", response -> System.out.println(response)); // Withdraw (async) - client.withdraw("ETH", "0x123", "0.1", null, response -> {}); + client.withdraw("ETH", "0x123", "0.1", null, null, response -> {}); } } From bf55921e292c19ad02e2fff6e6e31fee896c69fa Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Fri, 4 May 2018 18:36:07 +0200 Subject: [PATCH 12/83] Fix #125: Avoid 301 redirect for asset info API. --- .../com/binance/api/client/constant/BinanceApiConstants.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java index 00c4b2f71..8dddf6be8 100644 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -20,7 +20,7 @@ public class BinanceApiConstants { /** * Asset info base URL. */ - public static final String ASSET_INFO_API_BASE_URL = "https://binance.com/"; + public static final String ASSET_INFO_API_BASE_URL = "https://www.binance.com/"; /** * HTTP Header to be used for API-KEY authentication. From ff7db64d33b4b113c27bcccfef197a0853a20739 Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Sun, 6 May 2018 16:59:01 +0200 Subject: [PATCH 13/83] Fix #127 Remove meta header. --- .../binance/api/client/security/AuthenticationInterceptor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java b/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java index 3dc5c9b5a..a2eff2281 100644 --- a/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java +++ b/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java @@ -33,7 +33,7 @@ public Response intercept(Chain chain) throws IOException { 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) + newRequestBuilder.removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) .removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED); // Endpoint requires sending a valid API-KEY From aebcf157771d35357b06e0015778dc4393a93e88 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Tue, 15 May 2018 17:52:11 +0200 Subject: [PATCH 14/83] Cleanup the client/interceptor and errorBody converter mess in BinanceApiServiceGenerator --- .../impl/BinanceApiServiceGenerator.java | 38 +++++++++++-------- .../impl/BinanceApiServiceGeneratorTest.java | 24 ------------ 2 files changed, 22 insertions(+), 40 deletions(-) delete mode 100644 src/test/java/com/binance/api/client/impl/BinanceApiServiceGeneratorTest.java diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 6d7ee2b76..13c982b9e 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -5,8 +5,11 @@ import com.binance.api.client.exception.BinanceApiException; import com.binance.api.client.security.AuthenticationInterceptor; import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; import org.apache.commons.lang3.StringUtils; import retrofit2.Call; +import retrofit2.Converter; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; @@ -18,29 +21,33 @@ * Generates a Binance API implementation based on @see {@link BinanceApiService}. */ public class BinanceApiServiceGenerator { + private static final OkHttpClient sharedClient = new OkHttpClient.Builder().build(); + private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); - static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); - - private static Retrofit.Builder builder = - new Retrofit.Builder() - .baseUrl(BinanceApiConstants.API_BASE_URL) - .addConverterFactory(JacksonConverterFactory.create()); - - 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); } public static S createService(Class serviceClass, String apiKey, String secret) { - if (!StringUtils.isEmpty(apiKey) && !StringUtils.isEmpty(secret)) { + Retrofit.Builder retrofitBuilder = new Retrofit.Builder() + .baseUrl(BinanceApiConstants.API_BASE_URL) + .addConverterFactory(converterFactory); + + if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { + retrofitBuilder.client(sharedClient); + } else { + // `adaptedClient` will use its own interceptor, but share thread pool etc with the 'parent' client AuthenticationInterceptor interceptor = new AuthenticationInterceptor(apiKey, secret); - 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 +72,6 @@ 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()); } } \ 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 From bed23c0e95d0c009bbf36486a4259420856f593c Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Tue, 15 May 2018 18:09:36 +0200 Subject: [PATCH 15/83] Improve web socket creation: use the process-wide shared HTTP client and connection/thread pool --- .../api/client/BinanceApiClientFactory.java | 4 +++- .../api/client/BinanceApiWebSocketClient.java | 4 ++++ .../client/impl/BinanceApiServiceGenerator.java | 7 +++++++ .../impl/BinanceApiWebSocketClientImpl.java | 17 ++++++++--------- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java index b00d986c2..7c05f83bf 100644 --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -4,6 +4,8 @@ import com.binance.api.client.impl.BinanceApiRestClientImpl; import com.binance.api.client.impl.BinanceApiWebSocketClientImpl; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.getSharedClient; + /** * A factory for creating BinanceApi client objects. */ @@ -68,6 +70,6 @@ public BinanceApiRestClient newRestClient() { * Creates a new web socket client used for handling data streams. */ public BinanceApiWebSocketClient newWebSocketClient() { - return new BinanceApiWebSocketClientImpl(); + return new BinanceApiWebSocketClientImpl(getSharedClient()); } } diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java index b118efa9d..0b7f2446d 100644 --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -60,5 +60,9 @@ public interface BinanceApiWebSocketClient extends Closeable { */ Closeable onAllMarketTickersEvent(BinanceApiCallback> callback); + /** + * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. + */ + @Deprecated void close(); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 13c982b9e..c312a4162 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -74,4 +74,11 @@ public static T executeSync(Call call) { public static BinanceApiError getBinanceApiError(Response response) throws IOException, BinanceApiException { return errorBodyConverter.convert(response.errorBody()); } + + /** + * Returns the shared OkHttpClient instance. + */ + public static OkHttpClient getSharedClient() { + return sharedClient; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index 87ff981ab..2822779f9 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -9,7 +9,7 @@ import com.binance.api.client.domain.event.DepthEvent; import com.binance.api.client.domain.event.UserDataUpdateEvent; import com.binance.api.client.domain.market.CandlestickInterval; -import okhttp3.Dispatcher; + import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.WebSocket; @@ -22,12 +22,10 @@ */ 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) { @@ -55,10 +53,11 @@ public Closeable onAllMarketTickersEvent(BinanceApiCallback>(callback)); } + /** + * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. + */ @Override - public void close() { - client.dispatcher().executorService().shutdown(); - } + public void close() { } private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); From 95ab6bf6f0a161f6eb94f46da08457514d52e897 Mon Sep 17 00:00:00 2001 From: Nils Wiersema Date: Tue, 15 May 2018 18:16:34 +0200 Subject: [PATCH 16/83] Upgrade Retrofit, which upgrades OkHttp, which now properly honors pingInterval (to detect websocket disconnections) --- pom.xml | 2 +- .../binance/api/client/impl/BinanceApiServiceGenerator.java | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index f940bff48..7ad829cbd 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ 1.0.0 - 2.3.0 + 2.4.0 diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index c312a4162..490dd23dc 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -16,12 +16,16 @@ import java.io.IOException; import java.lang.annotation.Annotation; +import java.util.concurrent.TimeUnit; /** * Generates a Binance API implementation based on @see {@link BinanceApiService}. */ public class BinanceApiServiceGenerator { - private static final OkHttpClient sharedClient = new OkHttpClient.Builder().build(); + private static final OkHttpClient sharedClient = new OkHttpClient.Builder() + .pingInterval(20, TimeUnit.SECONDS) + .build(); + private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); @SuppressWarnings("unchecked") From a10a0e9ab8470f095a471a96f8c4a61e23fcf806 Mon Sep 17 00:00:00 2001 From: Miroslav Hruz Date: Thu, 19 Jul 2018 15:58:56 +0200 Subject: [PATCH 17/83] Cannot deserialize value of type `com.binance.api.client.domain.general.RateLimitType` from String "REQUEST_WEIGHT": value not one of declared Enum instance names: [REQUESTS, ORDERS] --- .../com/binance/api/client/domain/general/FilterType.java | 1 + .../com/binance/api/client/domain/general/RateLimitType.java | 2 +- .../api/domain/general/ExchangeInfoDeserializerTest.java | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 593b4ae5e..6a31f49b0 100644 --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -10,6 +10,7 @@ public enum FilterType { MIN_NOTIONAL, MAX_NUM_ORDERS, MAX_ALGO_ORDERS, + MAX_NUM_ALGO_ORDERS, // Exchange EXCHANGE_MAX_NUM_ORDERS, 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 index af438bebb..4ca0fadb8 100644 --- a/src/main/java/com/binance/api/client/domain/general/RateLimitType.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimitType.java @@ -4,6 +4,6 @@ * Rate limiters. */ public enum RateLimitType { - REQUESTS, + REQUEST_WEIGHT, ORDERS } diff --git a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java index af949ff6f..b865a8b68 100644 --- a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java @@ -31,7 +31,7 @@ public void testExchangeInfoDeserialization() { " \"timezone\": \"UTC\",\n" + " \"serverTime\": 1508631584636,\n" + " \"rateLimits\": [{\n" + - " \"rateLimitType\": \"REQUESTS\",\n" + + " \"rateLimitType\": \"REQUEST_WEIGHT\",\n" + " \"interval\": \"MINUTE\",\n" + " \"limit\": 1200\n" + " },\n" + @@ -81,7 +81,7 @@ public void testExchangeInfoDeserialization() { List rateLimits = exchangeInfo.getRateLimits(); assertEquals(rateLimits.size(), 3); - testRateLimit(rateLimits.get(0), RateLimitType.REQUESTS, RateLimitInterval.MINUTE, 1200); + 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); From 84adddb9716c40ff19813998450ba4d7bd509099 Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Thu, 19 Jul 2018 17:33:13 +0200 Subject: [PATCH 18/83] Add support for ICEBERG_PARTS and MAX_NUM_ALGO_ORDERS filter. --- .../api/client/domain/general/FilterType.java | 1 + .../client/domain/general/SymbolFilter.java | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 6a31f49b0..63fef1659 100644 --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -11,6 +11,7 @@ public enum FilterType { MAX_NUM_ORDERS, MAX_ALGO_ORDERS, MAX_NUM_ALGO_ORDERS, + ICEBERG_PARTS, // Exchange EXCHANGE_MAX_NUM_ORDERS, 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 index 8902b1188..4ad81163a 100644 --- a/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java @@ -59,9 +59,18 @@ public class SymbolFilter { */ 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; @@ -129,6 +138,15 @@ 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; } From 9dd24773c02566b0a3aea1e83c578b72205f4ea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20G=C3=BCng=C3=B6ren?= Date: Fri, 20 Jul 2018 10:27:57 +0300 Subject: [PATCH 19/83] ignore properties add for avoiding new fields deserialization exception --- .../java/com/binance/api/client/domain/ExecutionType.java | 3 +++ .../com/binance/api/client/domain/OrderRejectReason.java | 3 +++ src/main/java/com/binance/api/client/domain/OrderSide.java | 3 +++ src/main/java/com/binance/api/client/domain/OrderStatus.java | 3 +++ src/main/java/com/binance/api/client/domain/OrderType.java | 3 +++ src/main/java/com/binance/api/client/domain/TimeInForce.java | 3 +++ .../com/binance/api/client/domain/account/AssetBalance.java | 2 ++ .../binance/api/client/domain/account/DepositAddress.java | 2 ++ .../binance/api/client/domain/account/DepositHistory.java | 2 ++ .../java/com/binance/api/client/domain/account/NewOrder.java | 2 ++ .../api/client/domain/account/NewOrderResponseType.java | 3 +++ .../java/com/binance/api/client/domain/account/Trade.java | 2 ++ .../binance/api/client/domain/account/TradeHistoryItem.java | 2 ++ .../binance/api/client/domain/account/WithdrawHistory.java | 2 ++ .../api/client/domain/account/request/OrderRequest.java | 2 ++ .../binance/api/client/domain/event/CandlestickEvent.java | 2 ++ .../java/com/binance/api/client/domain/event/ListenKey.java | 3 +++ .../binance/api/client/domain/general/ExchangeFilter.java | 2 ++ .../com/binance/api/client/domain/general/FilterType.java | 3 +++ .../com/binance/api/client/domain/general/RateLimit.java | 2 ++ .../binance/api/client/domain/general/RateLimitInterval.java | 3 +++ .../com/binance/api/client/domain/general/RateLimitType.java | 5 ++++- .../com/binance/api/client/domain/general/ServerTime.java | 3 +++ .../com/binance/api/client/domain/general/SymbolFilter.java | 3 +++ .../com/binance/api/client/domain/general/SymbolStatus.java | 3 +++ .../com/binance/api/client/domain/market/BookTicker.java | 2 ++ .../api/client/domain/market/CandlestickInterval.java | 3 +++ .../java/com/binance/api/client/domain/market/OrderBook.java | 2 ++ .../com/binance/api/client/domain/market/OrderBookEntry.java | 2 ++ .../com/binance/api/client/domain/market/TickerPrice.java | 2 ++ .../api/domain/general/ExchangeInfoDeserializerTest.java | 4 ++-- 31 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/binance/api/client/domain/ExecutionType.java b/src/main/java/com/binance/api/client/domain/ExecutionType.java index b6760b794..4da14d863 100644 --- a/src/main/java/com/binance/api/client/domain/ExecutionType.java +++ b/src/main/java/com/binance/api/client/domain/ExecutionType.java @@ -1,8 +1,11 @@ package com.binance.api.client.domain; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + /** * Order execution type. */ +@JsonIgnoreProperties(ignoreUnknown = true) public enum ExecutionType { NEW, CANCELED, diff --git a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java index 7da9173b4..29f5e47f0 100644 --- a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java +++ b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java @@ -1,8 +1,11 @@ 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, diff --git a/src/main/java/com/binance/api/client/domain/OrderSide.java b/src/main/java/com/binance/api/client/domain/OrderSide.java index c477436bd..db74f9373 100644 --- a/src/main/java/com/binance/api/client/domain/OrderSide.java +++ b/src/main/java/com/binance/api/client/domain/OrderSide.java @@ -1,8 +1,11 @@ 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 index 478dd4d56..81656c722 100644 --- a/src/main/java/com/binance/api/client/domain/OrderStatus.java +++ b/src/main/java/com/binance/api/client/domain/OrderStatus.java @@ -1,8 +1,11 @@ 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, diff --git a/src/main/java/com/binance/api/client/domain/OrderType.java b/src/main/java/com/binance/api/client/domain/OrderType.java index 46eb162c2..11d484e5e 100644 --- a/src/main/java/com/binance/api/client/domain/OrderType.java +++ b/src/main/java/com/binance/api/client/domain/OrderType.java @@ -1,8 +1,11 @@ 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, diff --git a/src/main/java/com/binance/api/client/domain/TimeInForce.java b/src/main/java/com/binance/api/client/domain/TimeInForce.java index 49e266431..2d2f50db1 100644 --- a/src/main/java/com/binance/api/client/domain/TimeInForce.java +++ b/src/main/java/com/binance/api/client/domain/TimeInForce.java @@ -1,5 +1,7 @@ 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. * @@ -9,6 +11,7 @@ * * @see http://www.investopedia.com/terms/t/timeinforce.asp */ +@JsonIgnoreProperties(ignoreUnknown = true) public enum TimeInForce { GTC, IOC, 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 index 9f90aafa4..3dae789ec 100644 --- 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,6 +1,7 @@ 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; /** @@ -8,6 +9,7 @@ * * @see Account */ +@JsonIgnoreProperties(ignoreUnknown = true) public class AssetBalance { /** 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 index 2ca99502f..0aba6dc05 100644 --- 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,11 +1,13 @@ 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; 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 index 792f3fa9d..4ac86ee7c 100644 --- 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,6 +1,7 @@ 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; @@ -11,6 +12,7 @@ * * @see Deposit */ +@JsonIgnoreProperties(ignoreUnknown = true) public class DepositHistory { @JsonProperty("depositList") 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 index 635e1ddac..221c07d36 100644 --- 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 { /** 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 index c465f85a7..836a571d5 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java @@ -1,9 +1,12 @@ 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, 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 index c64431118..a3bad8ec5 100644 --- 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,6 +1,7 @@ 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; @@ -8,6 +9,7 @@ /** * Represents an executed trade. */ +@JsonIgnoreProperties(ignoreUnknown = true) public class Trade { /** 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 index a4470a0c1..68d017754 100644 --- 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,12 +1,14 @@ 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. 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 index 4694c0d09..3a3d50f12 100644 --- 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,6 +1,7 @@ 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; @@ -10,6 +11,7 @@ * * @see Withdraw */ +@JsonIgnoreProperties(ignoreUnknown = true) public class WithdrawHistory { private List withdrawList; 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 index 2221af12d..c890a01d9 100644 --- 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,11 +1,13 @@ 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; 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 index 31cbe1e4f..1019eb6f3 100644 --- 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,6 +1,7 @@ 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; @@ -11,6 +12,7 @@ */ @JsonDeserialize(using = CandlestickEventDeserializer.class) @JsonSerialize(using = CandlestickEventSerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) public class CandlestickEvent { private String eventType; 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 index 555d0af16..cfce64396 100644 --- 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,8 +1,11 @@ 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; 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 index ef4907925..e492111a8 100644 --- 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,6 +1,7 @@ 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; /** @@ -10,6 +11,7 @@ * * 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; diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 593b4ae5e..928fb47b4 100644 --- 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, 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 index 8f0e3fd1a..e8d963c33 100644 --- 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,11 +1,13 @@ 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; 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 index bc316061d..0c8f65fca 100644 --- 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,8 +1,11 @@ package com.binance.api.client.domain.general; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + /** * Rate limit intervals. */ +@JsonIgnoreProperties(ignoreUnknown = true) public enum RateLimitInterval { SECOND, MINUTE, 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 index af438bebb..db43d5d39 100644 --- 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,12 @@ package com.binance.api.client.domain.general; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + /** * Rate limiters. */ +@JsonIgnoreProperties(ignoreUnknown = true) public enum RateLimitType { - REQUESTS, + REQUEST_WEIGHT, ORDERS } diff --git a/src/main/java/com/binance/api/client/domain/general/ServerTime.java b/src/main/java/com/binance/api/client/domain/general/ServerTime.java index 9b7475271..ec4880313 100644 --- 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,8 +1,11 @@ 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; 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 index 8902b1188..4789e78f6 100644 --- 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,5 +1,7 @@ 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. * @@ -13,6 +15,7 @@ * * 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 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 index e9ddff627..c12647540 100644 --- 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,8 +1,11 @@ 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, 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 index c91f3a76f..67b007ea8 100644 --- 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,11 +1,13 @@ 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 { /** 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 index 3bd4887e3..b34334977 100644 --- 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,9 +1,12 @@ 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"), 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 index d5054a9e6..98ffb10e1 100644 --- 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,6 +1,7 @@ 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; @@ -8,6 +9,7 @@ /** * Order book of a symbol in Binance. */ +@JsonIgnoreProperties(ignoreUnknown = true) public class OrderBook { /** 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 index 3bc946a7d..7d4d2635b 100644 --- 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,6 +1,7 @@ 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; @@ -11,6 +12,7 @@ */ @JsonDeserialize(using = OrderBookEntryDeserializer.class) @JsonSerialize(using = OrderBookEntrySerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) public class OrderBookEntry { private String price; 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 index e2444cbc8..2c7a036ac 100644 --- 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,11 +1,13 @@ 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 { /** diff --git a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java index af949ff6f..b865a8b68 100644 --- a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java @@ -31,7 +31,7 @@ public void testExchangeInfoDeserialization() { " \"timezone\": \"UTC\",\n" + " \"serverTime\": 1508631584636,\n" + " \"rateLimits\": [{\n" + - " \"rateLimitType\": \"REQUESTS\",\n" + + " \"rateLimitType\": \"REQUEST_WEIGHT\",\n" + " \"interval\": \"MINUTE\",\n" + " \"limit\": 1200\n" + " },\n" + @@ -81,7 +81,7 @@ public void testExchangeInfoDeserialization() { List rateLimits = exchangeInfo.getRateLimits(); assertEquals(rateLimits.size(), 3); - testRateLimit(rateLimits.get(0), RateLimitType.REQUESTS, RateLimitInterval.MINUTE, 1200); + 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); From 137cfd478052b49530d766302458699d6e068c64 Mon Sep 17 00:00:00 2001 From: fferez Date: Fri, 20 Jul 2018 16:41:36 +0100 Subject: [PATCH 20/83] Issue 157: Exception when getting all trades of a symbol --- .../binance/api/client/domain/account/Trade.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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 index c64431118..574e16b7b 100644 --- a/src/main/java/com/binance/api/client/domain/account/Trade.java +++ b/src/main/java/com/binance/api/client/domain/account/Trade.java @@ -40,6 +40,11 @@ public class Trade { */ private long time; + /** + * The symbol of the trade. + */ + private String symbol; + @JsonProperty("isBuyer") private boolean buyer; @@ -107,6 +112,14 @@ 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; } @@ -143,6 +156,7 @@ public void setOrderId(String orderId) { 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("commission", commission) From bb8a3b6d2a127d128d2fea4ee76f7872d320d02b Mon Sep 17 00:00:00 2001 From: brintal Date: Sat, 21 Jul 2018 00:14:48 +0200 Subject: [PATCH 21/83] binance api change 2018-07-18: added param cummulativeQuoteQty to the order response --- .../api/client/domain/account/NewOrderResponse.java | 10 ++++++++++ 1 file changed, 10 insertions(+) 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 index e1c1e7569..c317bba55 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java @@ -41,6 +41,8 @@ public class NewOrderResponse { private String executedQty; + private String cummulativeQuoteQty; + private OrderStatus status; private TimeInForce timeInForce; @@ -112,6 +114,14 @@ 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; } From 6b4de682094b1e376c2a3f0dda26e754f3466b77 Mon Sep 17 00:00:00 2001 From: brintal Date: Sat, 21 Jul 2018 00:14:58 +0200 Subject: [PATCH 22/83] binance api change 2018-07-18: updated javadoc to reflect the new limits for max results o --- .../api/client/BinanceApiAsyncRestClient.java | 12 ++++++------ .../com/binance/api/client/BinanceApiRestClient.java | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java index 3bf9317cb..6a20c2cdf 100644 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -70,7 +70,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); @@ -79,7 +79,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 */ @@ -94,7 +94,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 @@ -114,7 +114,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 @@ -229,7 +229,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 */ @@ -239,7 +239,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); diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index b0f1d165c..6c6cdec48 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -69,7 +69,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); @@ -77,7 +77,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); @@ -91,7 +91,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 @@ -110,7 +110,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 @@ -215,7 +215,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 */ @@ -225,7 +225,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); From 9a6cd16dba1822a21fe350012a988d5d60babd47 Mon Sep 17 00:00:00 2001 From: Krasks Date: Tue, 24 Jul 2018 02:26:23 +0300 Subject: [PATCH 23/83] fixed market ticker event --- .../domain/event/AllMarketTickersEvent.java | 122 +++++++++--------- .../impl/BinanceApiWebSocketClientImpl.java | 3 +- .../impl/BinanceApiWebSocketListener.java | 4 +- 3 files changed, 65 insertions(+), 64 deletions(-) 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 index 336f0980e..8c07cb29a 100644 --- a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java @@ -20,43 +20,43 @@ public class AllMarketTickersEvent { private String symbol; @JsonProperty("p") - private double priceChange; + private String priceChange; @JsonProperty("P") - private double priceChangePercent; + private String priceChangePercent; @JsonProperty("w") - private double weightedAveragePrice; + private String weightedAveragePrice; @JsonProperty("x") - private double previousDaysClosePrice; + private String previousDaysClosePrice; @JsonProperty("c") - private double currentDaysClosePrice; + private String currentDaysClosePrice; @JsonProperty("Q") - private long closeTradesQuantity; + private String closeTradesQuantity; @JsonProperty("a") - private double bestAskPrice; + private String bestAskPrice; @JsonProperty("A") - private long bestAskQuantity; + private String bestAskQuantity; @JsonProperty("o") - private double openPrice; + private String openPrice; @JsonProperty("h") - private double highPrice; + private String highPrice; @JsonProperty("l") - private double lowPrice; + private String lowPrice; @JsonProperty("v") - private long totalTradedBaseAssetVolume; + private String totalTradedBaseAssetVolume; @JsonProperty("q") - private long totalTradedQuoteAssetVolume; + private String totalTradedQuoteAssetVolume; @JsonProperty("O") private long statisticesOpenTime; @@ -97,107 +97,107 @@ public void setSymbol(String symbol) { this.symbol = symbol; } - public double getPriceChange() { + public String getPriceChange() { return priceChange; } - public void setPriceChange(double priceChange) { + public void setPriceChange(String priceChange) { this.priceChange = priceChange; } - public double getPriceChangePercent() { + public String getPriceChangePercent() { return priceChangePercent; } - public void setPriceChangePercent(double priceChangePercent) { + public void setPriceChangePercent(String priceChangePercent) { this.priceChangePercent = priceChangePercent; } - public double getWeightedAveragePrice() { + public String getWeightedAveragePrice() { return weightedAveragePrice; } - public void setWeightedAveragePrice(double weightedAveragePrice) { + public void setWeightedAveragePrice(String weightedAveragePrice) { this.weightedAveragePrice = weightedAveragePrice; } - public double getPreviousDaysClosePrice() { + public String getPreviousDaysClosePrice() { return previousDaysClosePrice; } - public void setPreviousDaysClosePrice(double previousDaysClosePrice) { + public void setPreviousDaysClosePrice(String previousDaysClosePrice) { this.previousDaysClosePrice = previousDaysClosePrice; } - public double getCurrentDaysClosePrice() { + public String getCurrentDaysClosePrice() { return currentDaysClosePrice; } - public void setCurrentDaysClosePrice(double currentDaysClosePrice) { + public void setCurrentDaysClosePrice(String currentDaysClosePrice) { this.currentDaysClosePrice = currentDaysClosePrice; } - public long getCloseTradesQuantity() { + public String getCloseTradesQuantity() { return closeTradesQuantity; } - public void setCloseTradesQuantity(long closeTradesQuantity) { + public void setCloseTradesQuantity(String closeTradesQuantity) { this.closeTradesQuantity = closeTradesQuantity; } - public double getBestAskPrice() { + public String getBestAskPrice() { return bestAskPrice; } - public void setBestAskPrice(double bestAskPrice) { + public void setBestAskPrice(String bestAskPrice) { this.bestAskPrice = bestAskPrice; } - public long getBestAskQuantity() { + public String getBestAskQuantity() { return bestAskQuantity; } - public void setBestAskQuantity(long bestAskQuantity) { + public void setBestAskQuantity(String bestAskQuantity) { this.bestAskQuantity = bestAskQuantity; } - public double getOpenPrice() { + public String getOpenPrice() { return openPrice; } - public void setOpenPrice(double openPrice) { + public void setOpenPrice(String openPrice) { this.openPrice = openPrice; } - public double getHighPrice() { + public String getHighPrice() { return highPrice; } - public void setHighPrice(double highPrice) { + public void setHighPrice(String highPrice) { this.highPrice = highPrice; } - public double getLowPrice() { + public String getLowPrice() { return lowPrice; } - public void setLowPrice(double lowPrice) { + public void setLowPrice(String lowPrice) { this.lowPrice = lowPrice; } - public long getTotalTradedBaseAssetVolume() { + public String getTotalTradedBaseAssetVolume() { return totalTradedBaseAssetVolume; } - public void setTotalTradedBaseAssetVolume(long totalTradedBaseAssetVolume) { + public void setTotalTradedBaseAssetVolume(String totalTradedBaseAssetVolume) { this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; } - public long getTotalTradedQuoteAssetVolume() { + public String getTotalTradedQuoteAssetVolume() { return totalTradedQuoteAssetVolume; } - public void setTotalTradedQuoteAssetVolume(long totalTradedQuoteAssetVolume) { + public void setTotalTradedQuoteAssetVolume(String totalTradedQuoteAssetVolume) { this.totalTradedQuoteAssetVolume = totalTradedQuoteAssetVolume; } @@ -244,27 +244,27 @@ public void setTotalNumberOfTrades(long 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(); + .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/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index 87ff981ab..24c251ff0 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -9,6 +9,7 @@ import com.binance.api.client.domain.event.DepthEvent; import com.binance.api.client.domain.event.UserDataUpdateEvent; import com.binance.api.client.domain.market.CandlestickInterval; +import com.fasterxml.jackson.core.type.TypeReference; import okhttp3.Dispatcher; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -52,7 +53,7 @@ public Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback> callback) { final String channel = "!ticker@arr"; - return createNewWebSocket(channel, new BinanceApiWebSocketListener>(callback)); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() {})); } @Override diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java index 978317c08..8eb9df304 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java @@ -27,9 +27,9 @@ public BinanceApiWebSocketListener(BinanceApiCallback callback, Class even this.eventClass = eventClass; } - public BinanceApiWebSocketListener(BinanceApiCallback callback) { + public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) { this.callback = callback; - this.eventTypeReference = new TypeReference() {}; + this.eventTypeReference = eventTypeReference; } @Override From abe4e31c388f72ea166362601aae34ce461395f9 Mon Sep 17 00:00:00 2001 From: Lukasz Wolynczuk Date: Mon, 20 Aug 2018 18:56:18 +0200 Subject: [PATCH 24/83] Fix for ORDER_WOULD_TRIGGER_IMMEDIATELY --- .../java/com/binance/api/client/domain/OrderRejectReason.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java index 29f5e47f0..ff9374e8a 100644 --- a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java +++ b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java @@ -16,5 +16,6 @@ public enum OrderRejectReason { UNKNOWN_ACCOUNT, INSUFFICIENT_BALANCE, ACCOUNT_INACTIVE, - ACCOUNT_CANNOT_SETTLE + ACCOUNT_CANNOT_SETTLE, + ORDER_WOULD_TRIGGER_IMMEDIATELY } \ No newline at end of file From f0cf925458ea929e514506c8ccf9e4e2611d81c1 Mon Sep 17 00:00:00 2001 From: miron Date: Sun, 26 Aug 2018 20:32:56 +0100 Subject: [PATCH 25/83] multi-channel subscription on single websocket --- README.md | 34 +++++++++++++++++++ .../api/client/BinanceApiWebSocketClient.java | 20 +++++------ .../impl/BinanceApiWebSocketClientImpl.java | 26 ++++++++++---- 3 files changed, 63 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 102a0b1ac..bf74d5d02 100644 --- a/README.md +++ b/README.md @@ -280,6 +280,9 @@ client.closeUserDataStream(listenKey); BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient(); ``` +User needs to be aware that REST symbols which are `upper case` differ from WebSocket symbols which must be `lower case`. +In scenario of subscription with upper case styled symbol, server will return no error and subscribe to given channel - however, no events will be pushed. + #### Handling web socket errors Each of the methods on `BinanceApiWebSocketClient`, which opens a new web socket, takes a `BinanceApiCallback`, which is @@ -431,6 +434,37 @@ client.onUserDataUpdateEvent(listenKey, response -> { }); ``` +#### Multi-channel subscription +Client provides a way for user to subscribe to multiple channels using same websocket - to achieve that user needs to coma-separate symbols as it is in following examples. + +````java +client.onAggTradeEvent("ethbtc,ethusdt", (AggTradeEvent response) -> { + if (Objects.equals(response.getSymbol(),"ethbtc")) { + // handle ethbtc event + } else if(Objects.equals(response.getSymbol()),"ethusdt")) { + // handle ethusdt event + } +}); +```` +````java +client.onDepthEvent("ethbtc,ethusdt", (DepthEvent response) -> { + if (Objects.equals(response.getSymbol(),"ethbtc")) { + // handle ethbtc event + } else if(Objects.equals(response.getSymbol()),"ethusdt")) { + // handle ethusdt event + } +}); +```` +````java +client.onCandlestickEvent("ethbtc,ethusdt", CandlestickInterval.ONE_MINUTE, (CandlestickEvent response) -> { + if (Objects.equals(response.getSymbol(),"ethbtc")) { + // handle ethbtc event + } else if(Objects.equals(response.getSymbol()),"ethusdt")) { + // handle ethusdt event + } +}); +```` + ### 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. diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java index b118efa9d..631bb6b06 100644 --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -18,30 +18,30 @@ 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 callback the callback to call on new events + * @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 interval the interval of the candles tick events required - * @param callback the callback to call on new events + * @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 callback the callback to call on new events + * @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. diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index 87ff981ab..df0df2466 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -15,14 +15,16 @@ 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(); @@ -30,19 +32,29 @@ public BinanceApiWebSocketClientImpl() { this.client = new OkHttpClient.Builder().dispatcher(d).build(); } - 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)); } From 429c70453447901270ade80e88b4b09bda19e45c Mon Sep 17 00:00:00 2001 From: Miron Balcerzak Date: Mon, 3 Sep 2018 00:30:07 +0100 Subject: [PATCH 26/83] Preventing NPE while boxing/unboxing --- .../domain/event/OrderTradeUpdateEvent.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 index 0f26008a7..cf7ab86e3 100644 --- a/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java @@ -25,7 +25,7 @@ public class OrderTradeUpdateEvent { private String eventType; @JsonProperty("E") - private long eventTime; + private Long eventTime; @JsonProperty("s") private String symbol; @@ -137,11 +137,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 +225,7 @@ public void setOrderRejectReason(OrderRejectReason orderRejectReason) { this.orderRejectReason = orderRejectReason; } - public long getOrderId() { + public Long getOrderId() { return orderId; } @@ -273,19 +273,19 @@ 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; } From 8055ac1c560d152898c56ed84e52187f3380e8a7 Mon Sep 17 00:00:00 2001 From: Miron Balcerzak Date: Mon, 3 Sep 2018 00:36:39 +0100 Subject: [PATCH 27/83] Preventing NPE while boxing/unboxing - JUnit fix --- .../api/domain/event/UserDataUpdateEventDeserializerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java index 36346b1ea..23b1ced98 100644 --- a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java @@ -70,8 +70,8 @@ public void testOrderUpdateEventDeserializer() { assertEquals(orderTradeUpdateEvent.getOrderStatus(), OrderStatus.CANCELED); assertEquals(orderTradeUpdateEvent.getOrderRejectReason(), OrderRejectReason.NONE); - assertEquals(orderTradeUpdateEvent.getOrderId(), 123456L); - assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), 1L); + assertEquals(orderTradeUpdateEvent.getOrderId(), new Long(123456)); + assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), new Long(1)); } catch (IOException e) { fail(); } From 4363070508c6ea8fc02ad2fc1477cef309efc60c Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Thu, 13 Sep 2018 01:21:54 +0200 Subject: [PATCH 28/83] Add support for cancel order response. --- .../api/client/BinanceApiAsyncRestClient.java | 3 +- .../api/client/BinanceApiRestClient.java | 3 +- .../account/request/CancelOrderResponse.java | 68 +++++++++++++++++++ .../impl/BinanceApiAsyncRestClientImpl.java | 3 +- .../client/impl/BinanceApiRestClientImpl.java | 5 +- .../api/client/impl/BinanceApiService.java | 7 +- .../binance/api/examples/OrdersExample.java | 4 +- .../api/examples/OrdersExampleAsync.java | 2 +- 8 files changed, 85 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java index 6a20c2cdf..a6e7fe7ad 100644 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -12,6 +12,7 @@ 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; @@ -197,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). diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index 6c6cdec48..e405d4a7f 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -12,6 +12,7 @@ import com.binance.api.client.domain.account.WithdrawResult; import com.binance.api.client.domain.account.request.AllOrdersRequest; import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; import com.binance.api.client.domain.account.request.OrderRequest; import com.binance.api.client.domain.account.request.OrderStatusRequest; import com.binance.api.client.domain.general.ExchangeInfo; @@ -183,7 +184,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. 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 100644 index 000000000..88ede0268 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java @@ -0,0 +1,68 @@ +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Response object returned when an order is canceled. + * + * @see CancelOrderRequest for the request + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class CancelOrderResponse { + + private String symbol; + + private String origClientOrderId; + + private String orderId; + + private String clientOrderId; + + public String getSymbol() { + return symbol; + } + + public CancelOrderResponse setSymbol(String symbol) { + this.symbol = symbol; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + public String getOrderId() { + return orderId; + } + + public CancelOrderResponse setOrderId(String orderId) { + this.orderId = orderId; + return this; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public CancelOrderResponse setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("origClientOrderId", origClientOrderId) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java index 40104238f..97f02148c 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -15,6 +15,7 @@ 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; @@ -153,7 +154,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)); diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index 6ac012dac..aceb3799a 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -14,6 +14,7 @@ import com.binance.api.client.domain.account.WithdrawResult; import com.binance.api.client.domain.account.request.AllOrdersRequest; import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; import com.binance.api.client.domain.account.request.OrderRequest; import com.binance.api.client.domain.account.request.OrderStatusRequest; import com.binance.api.client.domain.general.Asset; @@ -150,8 +151,8 @@ public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { } @Override - public void cancelOrder(CancelOrderRequest cancelOrderRequest) { - executeSync(binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), + public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { + return executeSync(binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 77331890e..9643c8e90 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -14,6 +14,7 @@ import com.binance.api.client.domain.account.TradeHistoryItem; import com.binance.api.client.domain.account.WithdrawHistory; import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.CancelOrderResponse; import com.binance.api.client.domain.event.ListenKey; import com.binance.api.client.domain.general.Asset; import com.binance.api.client.domain.general.ExchangeInfo; @@ -115,9 +116,9 @@ Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Lon @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); + 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") diff --git a/src/test/java/com/binance/api/examples/OrdersExample.java b/src/test/java/com/binance/api/examples/OrdersExample.java index c133e7432..fc2185497 100644 --- a/src/test/java/com/binance/api/examples/OrdersExample.java +++ b/src/test/java/com/binance/api/examples/OrdersExample.java @@ -8,6 +8,7 @@ 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; @@ -40,7 +41,8 @@ public static void main(String[] args) { // Canceling an order try { - client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); + CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); + System.out.println(cancelOrderResponse); } catch (BinanceApiException e) { System.out.println(e.getError().getMsg()); } diff --git a/src/test/java/com/binance/api/examples/OrdersExampleAsync.java b/src/test/java/com/binance/api/examples/OrdersExampleAsync.java index 9f766ff02..cadb53a58 100644 --- a/src/test/java/com/binance/api/examples/OrdersExampleAsync.java +++ b/src/test/java/com/binance/api/examples/OrdersExampleAsync.java @@ -32,7 +32,7 @@ public static void main(String[] args) { // Canceling an order client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), - response -> System.out.println("Order has been canceled.")); + response -> System.out.println(response)); // Placing a test LIMIT order client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), From 2da945391f5728adafb2100aca43f71239a4ec67 Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Thu, 13 Sep 2018 02:15:27 +0200 Subject: [PATCH 29/83] Make fills toString null-safe. --- .../api/client/domain/account/NewOrderResponse.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 index c317bba55..f9ae9e447 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java @@ -8,7 +8,9 @@ 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; /** @@ -176,7 +178,10 @@ public String toString() { .append("timeInForce", timeInForce) .append("type", type) .append("side", side) - .append("fills", fills.stream().map(Object::toString).collect(Collectors.joining(", "))) + .append("fills", Optional.ofNullable(fills).orElse(Collections.emptyList()) + .stream() + .map(Object::toString) + .collect(Collectors.joining(", "))) .toString(); } } From e7995c0eeb65e5877c82d8d4ca209c0b331e9e0c Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Thu, 13 Sep 2018 02:24:31 +0200 Subject: [PATCH 30/83] Add unit tests for NewOrderResponse. --- .../domain/account/NewOrderResponse.java | 1 + .../domain/account/NewOrderResponseTest.java | 49 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java 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 index f9ae9e447..281e0361e 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java @@ -53,6 +53,7 @@ public class NewOrderResponse { private OrderSide side; + // @JsonSetter(nulls = Nulls.AS_EMPTY) private List fills; /** 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 100644 index 000000000..277a86162 --- /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 From d39139a78620862657f220c26ce9e3dd38ca25dd Mon Sep 17 00:00:00 2001 From: brintal Date: Thu, 15 Nov 2018 00:05:19 +0100 Subject: [PATCH 31/83] configure custom dispatcher for sharedClient to allow for more parallel requests --- .../client/impl/BinanceApiServiceGenerator.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 490dd23dc..8307f48b9 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -4,6 +4,7 @@ import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.exception.BinanceApiException; import com.binance.api.client.security.AuthenticationInterceptor; +import okhttp3.Dispatcher; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; @@ -22,12 +23,20 @@ * Generates a Binance API implementation based on @see {@link BinanceApiService}. */ public class BinanceApiServiceGenerator { - private static final OkHttpClient sharedClient = new OkHttpClient.Builder() - .pingInterval(20, TimeUnit.SECONDS) - .build(); + private static final OkHttpClient sharedClient; private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); + static { + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequestsPerHost(500); + dispatcher.setMaxRequests(500); + sharedClient = new OkHttpClient.Builder() + .dispatcher(dispatcher) + .pingInterval(20, TimeUnit.SECONDS) + .build(); + } + @SuppressWarnings("unchecked") private static final Converter errorBodyConverter = (Converter)converterFactory.responseBodyConverter( From d6801c2ab2cf5884b4722ef78db4760b109b9192 Mon Sep 17 00:00:00 2001 From: igorustinov Date: Tue, 4 Dec 2018 20:56:20 +0100 Subject: [PATCH 32/83] adds new filter type values --- .../java/com/binance/api/client/domain/general/FilterType.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 0ddedda51..1959f8ec5 100644 --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -15,6 +15,9 @@ public enum FilterType { MAX_ALGO_ORDERS, MAX_NUM_ALGO_ORDERS, ICEBERG_PARTS, + PERCENT_PRICE, + MARKET_LOT_SIZE, + MAX_NUM_ICEBERG_ORDERS, // Exchange EXCHANGE_MAX_NUM_ORDERS, From 7c2a4f42d5630cd2f03c8401d6cdce90d66ab3ea Mon Sep 17 00:00:00 2001 From: Tofig Hasanov Date: Sat, 12 Jan 2019 15:19:46 +0000 Subject: [PATCH 33/83] Add bid price and quantity to AllMarketTickersEvent --- .../domain/event/AllMarketTickersEvent.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) 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 index 8c07cb29a..85a14db29 100644 --- a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java @@ -37,6 +37,12 @@ public class AllMarketTickersEvent { @JsonProperty("Q") private String closeTradesQuantity; + @JsonProperty("b") + private String bestBidPrice; + + @JsonProperty("B") + private String bestBidQuantity; + @JsonProperty("a") private String bestAskPrice; @@ -145,6 +151,22 @@ 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; } @@ -253,6 +275,8 @@ public String toString() { .append("previousDaysClosePrice", previousDaysClosePrice) .append("currentDaysClosePrice", currentDaysClosePrice) .append("closeTradesQuantity", closeTradesQuantity) + .append("bestBidPrice", bestBidPrice) + .append("bestBidQuantity", bestBidQuantity) .append("bestAskPrice", bestAskPrice) .append("bestAskQuantity", bestAskQuantity) .append("openPrice", openPrice) From dd121acfa025ab7608d50921a4e5bbd48f62dbc3 Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Sun, 10 Mar 2019 11:43:20 +0100 Subject: [PATCH 34/83] Cache ObjectMapper. --- .../binance/api/client/impl/BinanceApiWebSocketListener.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java index 8eb9df304..e22bb8641 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java @@ -16,6 +16,8 @@ public class BinanceApiWebSocketListener extends WebSocketListener { private BinanceApiCallback callback; + private static final ObjectMapper mapper = new ObjectMapper(); + private Class eventClass; private TypeReference eventTypeReference; @@ -34,7 +36,6 @@ public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference @Override public void onMessage(WebSocket webSocket, String text) { - ObjectMapper mapper = new ObjectMapper(); try { T event = null; if (eventClass == null) { From 96bbbd155ff74aed76c901d97dfc9a4e2022ea6f Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Sun, 10 Mar 2019 16:12:49 +0100 Subject: [PATCH 35/83] Use ObjectReader instance for processing JSON. --- .../impl/BinanceApiWebSocketListener.java | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java index e22bb8641..8c84dbe3f 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java @@ -1,13 +1,15 @@ 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; +import com.fasterxml.jackson.databind.ObjectReader; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; + +import java.io.IOException; /** * Binance API WebSocket listener. @@ -18,31 +20,24 @@ public class BinanceApiWebSocketListener extends WebSocketListener { private static final ObjectMapper mapper = new ObjectMapper(); - private Class eventClass; - - private TypeReference eventTypeReference; + private final ObjectReader objectReader; private boolean closing = false; public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) { this.callback = callback; - this.eventClass = eventClass; + this.objectReader = mapper.readerFor(eventClass); } public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) { this.callback = callback; - this.eventTypeReference = eventTypeReference; + this.objectReader = mapper.readerFor(eventTypeReference); } @Override public void onMessage(WebSocket webSocket, String text) { try { - T event = null; - if (eventClass == null) { - event = mapper.readValue(text, eventTypeReference); - } else { - event = mapper.readValue(text, eventClass); - } + T event = objectReader.readValue(text); callback.onResponse(event); } catch (IOException e) { throw new BinanceApiException(e); From 5c4451c57b63b73a062fd60da4084e28a293b544 Mon Sep 17 00:00:00 2001 From: Marc Deveaux Date: Sat, 30 Mar 2019 20:08:27 -0400 Subject: [PATCH 36/83] add status and executedQty to CancelOrderResponse --- .../domain/account/request/CancelOrderResponse.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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 index 88ede0268..7b96a01eb 100644 --- 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 @@ -20,6 +20,9 @@ public class CancelOrderResponse { private String clientOrderId; + private String status; + private String executedQty; + public String getSymbol() { return symbol; } @@ -38,10 +41,16 @@ public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { return this; } + public String getStatus() { + return status; + } + public String getExecutedQty() { + return executedQty; + } + public String getOrderId() { return orderId; } - public CancelOrderResponse setOrderId(String orderId) { this.orderId = orderId; return this; From 22df744f0e29589824e84a1572328a2f727350de Mon Sep 17 00:00:00 2001 From: Ben Alex Date: Fri, 14 Jun 2019 12:15:50 +1000 Subject: [PATCH 37/83] Add license to POM for license-maven-plugin compatibility License metadata is useful for http://www.mojohaus.org/license-maven-plugin/ interoperability as well as a requirement of eventual listing in Maven Central (OSSHR) as per https://central.sonatype.org/pages/requirements.html. --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index 7ad829cbd..93401e33c 100644 --- a/pom.xml +++ b/pom.xml @@ -7,6 +7,12 @@ com.binance.api binance-api-client 1.0.0 + + + The MIT License + https://opensource.org/licenses/MIT + + 2.4.0 From 54bc694a158b9cd57698b0697468e988e5b32fe5 Mon Sep 17 00:00:00 2001 From: Ardiansyah Putra Date: Mon, 12 Aug 2019 14:18:15 +0700 Subject: [PATCH 38/83] Add Cummulative Quote Quantity `cummulativeQuoteQty` is needed to calculate the average price, for example when using market order --- .../binance/api/client/domain/account/Order.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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 index a0b5939b7..88beb54d7 100644 --- a/src/main/java/com/binance/api/client/domain/account/Order.java +++ b/src/main/java/com/binance/api/client/domain/account/Order.java @@ -78,6 +78,11 @@ public class Order { * Order timestamp. */ private long time; + + /** + * Used to calculate the average price + */ + private String cummulativeQuoteQty; public String getSymbol() { return symbol; @@ -182,6 +187,14 @@ public long getTime() { public void setTime(long time) { this.time = time; } + + public String getCummulativeQuoteQty() { + return cummulativeQuoteQty; + } + + public void setCummulativeQuoteQty(String cummulativeQuoteQty) { + this.cummulativeQuoteQty = cummulativeQuoteQty; + } @Override public String toString() { @@ -199,6 +212,7 @@ public String toString() { .append("stopPrice", stopPrice) .append("icebergQty", icebergQty) .append("time", time) + .append("cummulativeQuoteQty", cummulativeQuoteQty) .toString(); } } From 25a23ce9de4a7cf2a8e2d8204acfc521efa97e82 Mon Sep 17 00:00:00 2001 From: Martijn Courteaux Date: Sat, 17 Aug 2019 00:37:59 +0200 Subject: [PATCH 39/83] Fixed parsing of UserDataUpdateEvents with regard to the new 'outboundAccountPosition' events. --- .../api/client/domain/event/UserDataUpdateEvent.java | 8 +++++++- .../domain/event/UserDataUpdateEventDeserializer.java | 5 +++-- 2 files changed, 10 insertions(+), 3 deletions(-) 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 index 0af50e198..e0cd92bf2 100644 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java @@ -9,7 +9,8 @@ * User data update event which can be of two types: * * 1) outboundAccountInfo, whenever there is a change in the account (e.g. balance of an asset) - * 2) 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 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonDeserialize(using = UserDataUpdateEventDeserializer.class) @@ -62,6 +63,8 @@ public String toString() { .append("eventTime", eventTime); if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { sb.append("accountUpdateEvent", accountUpdateEvent); + } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + sb.append("accountPositionUpdateEvent", accountUpdateEvent); } else { sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); } @@ -70,6 +73,7 @@ public String toString() { public enum UserDataUpdateEventType { ACCOUNT_UPDATE("outboundAccountInfo"), + ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), ORDER_TRADE_UPDATE("executionReport"); private final String eventTypeId; @@ -87,6 +91,8 @@ public static UserDataUpdateEventType fromEventTypeId(String eventTypeId) { return ACCOUNT_UPDATE; } else if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { return ORDER_TRADE_UPDATE; + } else if (ACCOUNT_POSITION_UPDATE.eventTypeId.equals(eventTypeId)) { + return ACCOUNT_POSITION_UPDATE; } throw new IllegalArgumentException("Unrecognized user data update event type id: " + eventTypeId); } diff --git a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java index afc584636..8ef548e39 100644 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java @@ -38,7 +38,8 @@ public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx userDataUpdateEvent.setEventType(userDataUpdateEventType); userDataUpdateEvent.setEventTime(eventTime); - if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { + if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE || + userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); } else { // userDataUpdateEventType == UserDataUpdateEventType.ORDER_TRADE_UPDATE @@ -56,4 +57,4 @@ public T getUserDataUpdateEventDetail(String json, Class clazz, ObjectMap throw new BinanceApiException(e); } } -} \ No newline at end of file +} From a15902ab8b7f87bffde31aedda41b34d6d5bf10d Mon Sep 17 00:00:00 2001 From: joaopsilva Date: Sat, 17 Aug 2019 20:54:46 +0200 Subject: [PATCH 40/83] Adjusted recvWindow to 60000. --- .../api/client/constant/BinanceApiConstants.java | 2 +- .../binance/api/client/domain/account/Trade.java | 15 +++++++++++++++ .../api/examples/AccountEndpointsExample.java | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java index 8dddf6be8..bcc39452d 100644 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -42,7 +42,7 @@ 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 ToStringStyle used by toString methods. 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 index df0d14e3b..aa38a17b6 100644 --- a/src/main/java/com/binance/api/client/domain/account/Trade.java +++ b/src/main/java/com/binance/api/client/domain/account/Trade.java @@ -27,6 +27,12 @@ public class Trade { */ private String qty; + + /** + * Quote quantity for the trade (price * qty). + */ + private String quoteQty; + /** * Commission. */ @@ -90,6 +96,14 @@ 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; } @@ -161,6 +175,7 @@ public String toString() { .append("symbol", symbol) .append("price", price) .append("qty", qty) + .append("quoteQty", quoteQty) .append("commission", commission) .append("commissionAsset", commissionAsset) .append("time", time) diff --git a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java index a859ca8f1..bd7d56364 100644 --- a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java @@ -17,7 +17,7 @@ public static void main(String[] args) { BinanceApiRestClient client = factory.newRestClient(); // Get account balances - Account account = client.getAccount(6000000L, System.currentTimeMillis()); + Account account = client.getAccount(60_000L, System.currentTimeMillis()); System.out.println(account.getBalances()); System.out.println(account.getAssetBalance("ETH")); From 787d106defdd53777d4a8437d5da8987f79e9397 Mon Sep 17 00:00:00 2001 From: Oleg Yudin Date: Thu, 19 Dec 2019 19:14:08 +0700 Subject: [PATCH 41/83] Add TotalAccountBalanceExample --- .../com/binance/api/client/constant/Util.java | 24 +++++++ .../examples/TotalAccountBalanceExample.java | 62 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/main/java/com/binance/api/client/constant/Util.java create mode 100644 src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java 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 100644 index 000000000..e5dd0e416 --- /dev/null +++ b/src/main/java/com/binance/api/client/constant/Util.java @@ -0,0 +1,24 @@ +package com.binance.api.client.constant; + + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public final class Util { + + public static final List FIAT_CURRENCY = Collections.unmodifiableList(Arrays.asList("USDT", "BUSD", "PAX", "TUSD", "USDC", "NGN", "RUB", "USDS")); + + public static final String BTC_TICKER = "BTC"; + + private Util() { + throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } + + public static boolean isFiatCurrency(String symbol) { + for (String fiat : FIAT_CURRENCY) { + if (symbol.equals(fiat)) return true; + } + return false; + } +} 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 100644 index 000000000..7b0d4d01f --- /dev/null +++ b/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java @@ -0,0 +1,62 @@ +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; + + +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); + // Get total account balance in USDT (spot only) + double totalBalanceInUSDT = totalBalanceInBTC * Double.parseDouble(client.getPrice("BTCUSDT").getPrice()); + + System.out.println(totalBalanceInBTC); + 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 tickerRev = Util.BTC_TICKER + balance.getAsset(); + if (free + locked != 0) { + if (Util.isFiatCurrency(balance.getAsset())) { + double price = Double.parseDouble(client.getPrice(tickerRev).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; + + } + + + +} From e97c006c5cfcaeb0e07590d04efc1472b72fc8d8 Mon Sep 17 00:00:00 2001 From: Oleg Yudin Date: Fri, 20 Dec 2019 17:16:58 +0700 Subject: [PATCH 42/83] add turkish lira (TRY) --- src/main/java/com/binance/api/client/constant/Util.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/constant/Util.java b/src/main/java/com/binance/api/client/constant/Util.java index e5dd0e416..86dfc989f 100644 --- a/src/main/java/com/binance/api/client/constant/Util.java +++ b/src/main/java/com/binance/api/client/constant/Util.java @@ -7,7 +7,7 @@ public final class Util { - public static final List FIAT_CURRENCY = Collections.unmodifiableList(Arrays.asList("USDT", "BUSD", "PAX", "TUSD", "USDC", "NGN", "RUB", "USDS")); + 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"; From 64d121be6ef83ab80deee838d02f29d4c0aa574b Mon Sep 17 00:00:00 2001 From: Oleg Yudin Date: Fri, 20 Dec 2019 18:04:13 +0700 Subject: [PATCH 43/83] add comments --- .../java/com/binance/api/client/constant/Util.java | 9 +++++++++ .../api/examples/TotalAccountBalanceExample.java | 11 ++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/binance/api/client/constant/Util.java b/src/main/java/com/binance/api/client/constant/Util.java index 86dfc989f..f1d1a4ff5 100644 --- a/src/main/java/com/binance/api/client/constant/Util.java +++ b/src/main/java/com/binance/api/client/constant/Util.java @@ -5,8 +5,14 @@ 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"; @@ -15,6 +21,9 @@ private Util() { throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); } + /** + * Check if the ticker is fiat currency. + */ public static boolean isFiatCurrency(String symbol) { for (String fiat : FIAT_CURRENCY) { if (symbol.equals(fiat)) return true; diff --git a/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java b/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java index 7b0d4d01f..5abfe04f1 100644 --- a/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java +++ b/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java @@ -6,7 +6,9 @@ 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 { @@ -20,10 +22,9 @@ public static void main(String[] args) { // 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(totalBalanceInBTC); System.out.println(totalBalanceInUSDT); @@ -38,10 +39,10 @@ public double getTotalAccountBalance(BinanceApiRestClient client, Account accoun double free = Double.parseDouble(balance.getFree()); double locked = Double.parseDouble(balance.getLocked()); String ticker = balance.getAsset() + Util.BTC_TICKER; - String tickerRev = Util.BTC_TICKER + balance.getAsset(); + String tickerReverse = Util.BTC_TICKER + balance.getAsset(); if (free + locked != 0) { if (Util.isFiatCurrency(balance.getAsset())) { - double price = Double.parseDouble(client.getPrice(tickerRev).getPrice()); + double price = Double.parseDouble(client.getPrice(tickerReverse).getPrice()); double amount = (free + locked) / price; totalBalance += amount; } else { From 4c3e521971e56b0861175e8aab5c5ea853e96d3c Mon Sep 17 00:00:00 2001 From: Oleg Yudin Date: Sat, 21 Dec 2019 18:09:16 +0700 Subject: [PATCH 44/83] removing meaningless code from a private constructor --- src/main/java/com/binance/api/client/constant/Util.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/constant/Util.java b/src/main/java/com/binance/api/client/constant/Util.java index f1d1a4ff5..6e459c037 100644 --- a/src/main/java/com/binance/api/client/constant/Util.java +++ b/src/main/java/com/binance/api/client/constant/Util.java @@ -18,7 +18,7 @@ public final class Util { public static final String BTC_TICKER = "BTC"; private Util() { - throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } /** From 3a8dbff60742e718fb20e5981d4d1230142c6724 Mon Sep 17 00:00:00 2001 From: Dave Mc Date: Wed, 26 Feb 2020 17:56:50 -0700 Subject: [PATCH 45/83] Allow the base domain to be customized so that binance.us can be used instead of binance.com. --- .../api/client/config/BinanceApiConfig.java | 57 +++++++++++++++++++ .../client/constant/BinanceApiConstants.java | 21 +------ .../impl/BinanceApiAsyncRestClientImpl.java | 3 +- .../client/impl/BinanceApiRestClientImpl.java | 3 +- .../impl/BinanceApiServiceGenerator.java | 5 +- .../impl/BinanceApiWebSocketClientImpl.java | 3 +- 6 files changed, 69 insertions(+), 23 deletions(-) create mode 100644 src/main/java/com/binance/api/client/config/BinanceApiConfig.java 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 100644 index 000000000..c70ac2611 --- /dev/null +++ b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java @@ -0,0 +1,57 @@ +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"; + + /** + * Default receiving window. + */ + private static long DEFAULT_RECEIVING_WINDOW = 6_000_000L; + + /** + * 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()); + } + +} diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java index bcc39452d..4e3a9de27 100644 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -7,21 +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"; - - /** - * Asset info base URL. - */ - public static final String ASSET_INFO_API_BASE_URL = "https://www.binance.com/"; - /** * HTTP Header to be used for API-KEY authentication. */ @@ -43,10 +28,10 @@ public class BinanceApiConstants { * Default receiving window. */ public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; - + /** - * Default ToStringStyle used by toString methods. - * Override this to change the output format of the overridden toString methods. + * 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/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java index 97f02148c..ac0d21099 100644 --- 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; @@ -64,7 +65,7 @@ public void getExchangeInfo(BinanceApiCallback callback) { @Override public void getAllAssets(BinanceApiCallback> callback) { - binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html") + binanceApiService.getAllAssets(BinanceApiConfig.getAssetInfoApiBaseUrl() + "assetWithdraw/getAllAsset.html") .enqueue(new BinanceApiCallbackAdapter<>(callback)); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index aceb3799a..9add29ab0 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -1,6 +1,7 @@ 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; @@ -62,7 +63,7 @@ public ExchangeInfo getExchangeInfo() { @Override public List getAllAssets() { - return executeSync(binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html")); + return executeSync(binanceApiService.getAllAssets(BinanceApiConfig.getAssetInfoApiBaseUrl() + "assetWithdraw/getAllAsset.html")); } // Market Data endpoints diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 8307f48b9..7bab3ad1e 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -1,6 +1,7 @@ package com.binance.api.client.impl; import com.binance.api.client.BinanceApiError; +import com.binance.api.client.config.BinanceApiConfig; import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.exception.BinanceApiException; import com.binance.api.client.security.AuthenticationInterceptor; @@ -48,7 +49,7 @@ public static S createService(Class serviceClass) { public static S createService(Class serviceClass, String apiKey, String secret) { Retrofit.Builder retrofitBuilder = new Retrofit.Builder() - .baseUrl(BinanceApiConstants.API_BASE_URL) + .baseUrl(BinanceApiConfig.getApiBaseUrl()) .addConverterFactory(converterFactory); if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { @@ -94,4 +95,4 @@ public static BinanceApiError getBinanceApiError(Response response) throws IO public static OkHttpClient getSharedClient() { return sharedClient; } -} \ No newline at end of file +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index b9e530b0a..e9be1f690 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -2,6 +2,7 @@ import com.binance.api.client.BinanceApiCallback; import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.config.BinanceApiConfig; import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.event.AggTradeEvent; import com.binance.api.client.domain.event.AllMarketTickersEvent; @@ -73,7 +74,7 @@ public Closeable onAllMarketTickersEvent(BinanceApiCallback listener) { - String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); + String streamingUrl = String.format("%s/%s", BinanceApiConfig.getStreamApiBaseUrl(), channel); Request request = new Request.Builder().url(streamingUrl).build(); final WebSocket webSocket = client.newWebSocket(request, listener); return () -> { From 720dabfc8f7a64a3b28ef4cb166330b87c4b01fc Mon Sep 17 00:00:00 2001 From: Dave Mc Date: Wed, 26 Feb 2020 19:08:03 -0700 Subject: [PATCH 46/83] Cleaned out an unused testing variable. --- .../java/com/binance/api/client/config/BinanceApiConfig.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/com/binance/api/client/config/BinanceApiConfig.java b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java index c70ac2611..d05538efb 100644 --- a/src/main/java/com/binance/api/client/config/BinanceApiConfig.java +++ b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java @@ -10,11 +10,6 @@ public class BinanceApiConfig { */ private static String BASE_DOMAIN = "binance.com"; - /** - * Default receiving window. - */ - private static long DEFAULT_RECEIVING_WINDOW = 6_000_000L; - /** * Set the URL base domain name (e.g., binance.com). * From ab6bef0db775c724b6872cbaf0163769a161b512 Mon Sep 17 00:00:00 2001 From: "Mikhail.Petrov" Date: Sun, 15 Mar 2020 15:27:58 +0300 Subject: [PATCH 47/83] =?UTF-8?q?replace=20symbol=20`=C3=A7`=20to=20`c`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/binance/api/client/BinanceApiAsyncRestClient.java | 2 +- src/main/java/com/binance/api/client/BinanceApiRestClient.java | 2 +- .../java/com/binance/api/client/BinanceApiWebSocketClient.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java index a6e7fe7ad..d0e3b1c01 100644 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -30,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 { diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index e405d4a7f..f05cc0268 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -28,7 +28,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 { diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java index 7961efc49..1e8421e79 100644 --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -11,7 +11,7 @@ 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 { From 877d2cab385cd2def1241b0c032a08795ddb1a88 Mon Sep 17 00:00:00 2001 From: Peter Chovanec Date: Fri, 3 Apr 2020 20:50:21 +0200 Subject: [PATCH 48/83] updated model according to the latest Binance api spec, custom exception for unknown event type, new version 1.0.1 --- pom.xml | 4 +- .../api/client/domain/account/NewOrder.java | 15 ++++ .../api/client/domain/account/Order.java | 54 ++++++++++-- .../domain/event/BalanceUpdateEvent.java | 83 +++++++++++++++++++ .../domain/event/OrderTradeUpdateEvent.java | 68 +++++++++++++-- .../client/domain/event/TopOrdersEvent.java | 51 ++++++++++++ .../domain/event/UserDataUpdateEvent.java | 30 +++++-- .../UserDataUpdateEventDeserializer.java | 8 +- .../exception/UnsupportedEventException.java | 9 ++ .../impl/BinanceApiAsyncRestClientImpl.java | 14 +++- .../client/impl/BinanceApiRestClientImpl.java | 42 ++++------ .../api/client/impl/BinanceApiService.java | 8 ++ 12 files changed, 337 insertions(+), 49 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/event/BalanceUpdateEvent.java create mode 100644 src/main/java/com/binance/api/client/domain/event/TopOrdersEvent.java create mode 100644 src/main/java/com/binance/api/client/exception/UnsupportedEventException.java diff --git a/pom.xml b/pom.xml index 93401e33c..863f5c234 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.binance.api binance-api-client - 1.0.0 + 1.0.1 The MIT License @@ -60,4 +60,4 @@ - \ No newline at end of file + 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 index 221c07d36..b3ebd8bee 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -38,6 +38,11 @@ public class NewOrder { */ private String quantity; + /** + * Quote quantity. + */ + private String quoteOrderQty; + /** * Price. */ @@ -140,6 +145,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; } @@ -247,6 +261,7 @@ public String toString() { .append("type", type) .append("timeInForce", timeInForce) .append("quantity", quantity) + .append("quoteOrderQty", quoteOrderQty) .append("price", price) .append("newClientOrderId", newClientOrderId) .append("stopPrice", stopPrice) 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 index 88beb54d7..c2ba19457 100644 --- 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; /** @@ -78,12 +79,28 @@ public class Order { * Order timestamp. */ private long time; - + /** - * Used to calculate the average price - */ + * 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; } @@ -187,13 +204,37 @@ public long getTime() { public void setTime(long time) { this.time = time; } - + public String getCummulativeQuoteQty() { return cummulativeQuoteQty; } public void setCummulativeQuoteQty(String cummulativeQuoteQty) { - this.cummulativeQuoteQty = 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 @@ -213,6 +254,9 @@ public String toString() { .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/event/BalanceUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/BalanceUpdateEvent.java new file mode 100644 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/OrderTradeUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java index cf7ab86e3..d2bf6fc84 100644 --- 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 @@ -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; } @@ -289,6 +308,37 @@ 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/TopOrdersEvent.java b/src/main/java/com/binance/api/client/domain/event/TopOrdersEvent.java new file mode 100644 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 index e0cd92bf2..d95662df1 100644 --- 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,16 +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) 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) @@ -22,6 +26,8 @@ public class UserDataUpdateEvent { private AccountUpdateEvent accountUpdateEvent; + private BalanceUpdateEvent balanceUpdateEvent; + private OrderTradeUpdateEvent orderTradeUpdateEvent; public UserDataUpdateEventType getEventType() { @@ -48,6 +54,14 @@ public void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { this.accountUpdateEvent = accountUpdateEvent; } + public BalanceUpdateEvent getBalanceUpdateEvent() { + return balanceUpdateEvent; + } + + public void setBalanceUpdateEvent(BalanceUpdateEvent balanceUpdateEvent) { + this.balanceUpdateEvent = balanceUpdateEvent; + } + public OrderTradeUpdateEvent getOrderTradeUpdateEvent() { return orderTradeUpdateEvent; } @@ -64,7 +78,9 @@ public String toString() { if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { sb.append("accountUpdateEvent", accountUpdateEvent); } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { - sb.append("accountPositionUpdateEvent", accountUpdateEvent); + sb.append("accountPositionUpdateEvent", accountUpdateEvent); + } else if (eventType == UserDataUpdateEventType.BALANCE_UPDATE) { + sb.append("balanceUpdateEvent", balanceUpdateEvent); } else { sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); } @@ -74,7 +90,9 @@ public String toString() { public enum UserDataUpdateEventType { ACCOUNT_UPDATE("outboundAccountInfo"), ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), - ORDER_TRADE_UPDATE("executionReport"); + BALANCE_UPDATE("balanceUpdate"), + ORDER_TRADE_UPDATE("executionReport"), + ; private final String eventTypeId; @@ -93,8 +111,10 @@ public static UserDataUpdateEventType fromEventTypeId(String 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 index 8ef548e39..8888bb624 100644 --- 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> callback) { @Override public void newOrder(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + 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 diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index aceb3799a..121b44ac6 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -2,30 +2,12 @@ import com.binance.api.client.BinanceApiRestClient; import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.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; @@ -129,9 +111,19 @@ public List getBookTickers() { @Override public NewOrderResponse newOrder(NewOrder order) { - return executeSync(binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + 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 diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 9643c8e90..6f6c293db 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -100,6 +100,14 @@ Call newOrder(@Query("symbol") String symbol, @Query("side") O @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, From 108b877f8e6b92cdc007b811963a0de32351b5ec Mon Sep 17 00:00:00 2001 From: truong ha Date: Thu, 30 Apr 2020 12:39:41 +0700 Subject: [PATCH 49/83] Clone --- .../BinanceApiAsyncMarginRestClient.java | 109 +++ .../api/client/BinanceApiAsyncRestClient.java | 626 ++++++++--------- .../api/client/BinanceApiCallback.java | 46 +- .../api/client/BinanceApiClientFactory.java | 163 ++--- .../binance/api/client/BinanceApiError.java | 88 +-- .../client/BinanceApiMarginRestClient.java | 103 +++ .../api/client/BinanceApiRestClient.java | 596 ++++++++-------- .../api/client/BinanceApiWebSocketClient.java | 136 ++-- .../client/constant/BinanceApiConstants.java | 111 +-- .../api/client/domain/ExecutionType.java | 30 +- .../binance/api/client/domain/LoanStatus.java | 11 + .../api/client/domain/OrderRejectReason.java | 40 +- .../binance/api/client/domain/OrderSide.java | 24 +- .../api/client/domain/OrderStatus.java | 34 +- .../binance/api/client/domain/OrderType.java | 34 +- .../api/client/domain/TimeInForce.java | 38 +- .../api/client/domain/TransferType.java | 21 + .../api/client/domain/account/Account.java | 330 ++++----- .../client/domain/account/AssetBalance.java | 124 ++-- .../api/client/domain/account/Deposit.java | 176 ++--- .../client/domain/account/DepositAddress.java | 122 ++-- .../client/domain/account/DepositHistory.java | 114 ++-- .../api/client/domain/account/Loan.java | 51 ++ .../domain/account/LoanQueryResult.java | 33 + .../client/domain/account/MarginAccount.java | 121 ++++ .../domain/account/MarginAssetBalance.java | 103 +++ .../domain/account/MarginTransaction.java | 29 + .../api/client/domain/account/NewOrder.java | 518 +++++++------- .../domain/account/NewOrderResponse.java | 376 +++++------ .../domain/account/NewOrderResponseType.java | 30 +- .../api/client/domain/account/Order.java | 436 ++++++------ .../api/client/domain/account/Trade.java | 376 +++++------ .../domain/account/TradeHistoryItem.java | 208 +++--- .../api/client/domain/account/Withdraw.java | 248 +++---- .../domain/account/WithdrawHistory.java | 88 +-- .../client/domain/account/WithdrawResult.java | 124 ++-- .../account/request/AllOrdersRequest.java | 94 +-- .../account/request/CancelOrderRequest.java | 130 ++-- .../account/request/CancelOrderResponse.java | 154 ++--- .../domain/account/request/OrderRequest.java | 110 +-- .../account/request/OrderStatusRequest.java | 100 +-- .../domain/event/AccountUpdateEvent.java | 128 ++-- .../client/domain/event/AggTradeEvent.java | 114 ++-- .../domain/event/AllMarketTickersEvent.java | 588 ++++++++-------- .../event/AssetBalanceDeserializer.java | 62 +- .../client/domain/event/CandlestickEvent.java | 440 ++++++------ .../event/CandlestickEventDeserializer.java | 98 +-- .../event/CandlestickEventSerializer.java | 88 +-- .../api/client/domain/event/DepthEvent.java | 262 ++++---- .../api/client/domain/event/ListenKey.java | 50 +- .../domain/event/OrderTradeUpdateEvent.java | 636 +++++++++--------- .../domain/event/UserDataUpdateEvent.java | 200 +++--- .../UserDataUpdateEventDeserializer.java | 120 ++-- .../api/client/domain/general/Asset.java | 246 +++---- .../client/domain/general/ExchangeFilter.java | 88 +-- .../client/domain/general/ExchangeInfo.java | 156 ++--- .../api/client/domain/general/FilterType.java | 50 +- .../api/client/domain/general/RateLimit.java | 102 +-- .../domain/general/RateLimitInterval.java | 24 +- .../client/domain/general/RateLimitType.java | 24 +- .../api/client/domain/general/ServerTime.java | 48 +- .../client/domain/general/SymbolFilter.java | 320 ++++----- .../api/client/domain/general/SymbolInfo.java | 262 ++++---- .../client/domain/general/SymbolStatus.java | 34 +- .../api/client/domain/market/AggTrade.java | 206 +++--- .../api/client/domain/market/BookTicker.java | 176 ++--- .../api/client/domain/market/Candlestick.java | 286 ++++---- .../domain/market/CandlestickInterval.java | 72 +- .../api/client/domain/market/OrderBook.java | 124 ++-- .../client/domain/market/OrderBookEntry.java | 88 +-- .../market/OrderBookEntryDeserializer.java | 58 +- .../market/OrderBookEntrySerializer.java | 42 +- .../api/client/domain/market/TickerPrice.java | 92 +-- .../domain/market/TickerStatistics.java | 512 +++++++------- .../client/exception/BinanceApiException.java | 148 ++-- .../BinanceApiAsyncMarginRestClientImpl.java | 103 +++ .../impl/BinanceApiAsyncRestClientImpl.java | 484 ++++++------- .../impl/BinanceApiCallbackAdapter.java | 102 +-- .../impl/BinanceApiMarginRestClientImpl.java | 101 +++ .../client/impl/BinanceApiRestClientImpl.java | 466 ++++++------- .../api/client/impl/BinanceApiService.java | 393 ++++++----- .../impl/BinanceApiServiceGenerator.java | 192 +++--- .../impl/BinanceApiWebSocketClientImpl.java | 172 ++--- .../impl/BinanceApiWebSocketListener.java | 114 ++-- .../security/AuthenticationInterceptor.java | 182 ++--- .../api/client/security/HmacSHA256Signer.java | 58 +- .../constant/BinanceApiConstantsTest.java | 160 ++--- .../domain/account/NewOrderResponseTest.java | 96 +-- .../WithdrawHistoryDeserializerTest.java | 88 +-- .../CandlestickEventDeserializerTest.java | 136 ++-- .../UserDataUpdateEventDeserializerTest.java | 162 ++--- .../general/ExchangeInfoDeserializerTest.java | 256 +++---- .../market/CandlestickDeserializerTest.java | 102 +-- .../examples/AccountBalanceCacheExample.java | 162 ++--- .../api/examples/AccountEndpointsExample.java | 80 +-- .../AccountEndpointsExampleAsync.java | 62 +- .../api/examples/AggTradesCacheExample.java | 160 ++--- .../api/examples/AllMarketTickersExample.java | 42 +- .../examples/CandlesticksCacheExample.java | 172 ++--- .../api/examples/DepthCacheExample.java | 488 +++++++------- .../api/examples/GeneralEndpointsExample.java | 92 +-- .../GeneralEndpointsExampleAsync.java | 90 +-- .../MarginAccountEndpointsExample.java | 41 ++ .../MarginAccountEndpointsExampleAsync.java | 36 + ...arginAccountEndpointsLoanQueryExample.java | 24 + .../api/examples/MarginOrdersExample.java | 46 ++ .../examples/MarginOrdersExampleAsync.java | 36 + .../examples/MarginUserDataStreamExample.java | 55 ++ .../examples/MarketDataEndpointsExample.java | 114 ++-- .../MarketDataEndpointsExampleAsync.java | 114 ++-- .../api/examples/MarketDataStreamExample.java | 56 +- .../binance/api/examples/OrdersExample.java | 122 ++-- .../api/examples/OrdersExampleAsync.java | 96 +-- .../api/examples/UserDataStreamExample.java | 108 +-- 114 files changed, 9501 insertions(+), 8411 deletions(-) create mode 100755 src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiCallback.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiClientFactory.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiError.java create mode 100755 src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiRestClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java mode change 100644 => 100755 src/main/java/com/binance/api/client/constant/BinanceApiConstants.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/ExecutionType.java create mode 100755 src/main/java/com/binance/api/client/domain/LoanStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderRejectReason.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderSide.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OrderType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/TimeInForce.java create mode 100755 src/main/java/com/binance/api/client/domain/TransferType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Account.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/AssetBalance.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Deposit.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/DepositAddress.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/DepositHistory.java create mode 100755 src/main/java/com/binance/api/client/domain/account/Loan.java create mode 100755 src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java create mode 100755 src/main/java/com/binance/api/client/domain/account/MarginAccount.java create mode 100755 src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java create mode 100755 src/main/java/com/binance/api/client/domain/account/MarginTransaction.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOrder.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Order.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Trade.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Withdraw.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/WithdrawResult.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/DepthEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/ListenKey.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/Asset.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/FilterType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/RateLimit.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/RateLimitType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/ServerTime.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/SymbolFilter.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/SymbolInfo.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/SymbolStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/AggTrade.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/BookTicker.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/Candlestick.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBook.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/TickerPrice.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/market/TickerStatistics.java mode change 100644 => 100755 src/main/java/com/binance/api/client/exception/BinanceApiException.java create mode 100755 src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java create mode 100755 src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiService.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java mode change 100644 => 100755 src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java mode change 100644 => 100755 src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java mode change 100644 => 100755 src/main/java/com/binance/api/client/security/HmacSHA256Signer.java mode change 100644 => 100755 src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java mode change 100644 => 100755 src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AccountEndpointsExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AggTradesCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/AllMarketTickersExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/CandlesticksCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/DepthCacheExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/GeneralEndpointsExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java create mode 100755 src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java create mode 100755 src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java create mode 100755 src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java create mode 100755 src/test/java/com/binance/api/examples/MarginOrdersExample.java create mode 100755 src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java create mode 100755 src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/MarketDataStreamExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/OrdersExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/OrdersExampleAsync.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/UserDataStreamExample.java diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java new file mode 100755 index 000000000..cbab0781c --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java @@ -0,0 +1,109 @@ +package com.binance.api.client; + +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; + +import java.util.List; + +/** + * Binance API façade, supporting asynchronous/non-blocking access Binance's Margin REST API. + */ +public interface BinanceApiAsyncMarginRestClient { + + // Account endpoints + + /** + * Get current margin account information (async). + */ + void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback); + + /** + * Get current margin account information using default parameters (async). + */ + void getAccount(BinanceApiCallback callback); + + /** + * Get all open orders on margin account for a symbol (async). + * + * @param orderRequest order request parameters + * @param callback the callback that handles the response + */ + void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback); + + /** + * Send in a new margin order (async). + * + * @param order the new order to submit. + * @return a response containing details about the newly placed order. + */ + void newOrder(NewOrder order, BinanceApiCallback callback); + + /** + * Cancel an active margin order (async). + * + * @param cancelOrderRequest order status request parameters + */ + void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); + + /** + * Check margin order's status (async). + * + * @param orderStatusRequest order status request options/filters + * @return an order + */ + void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback); + + /** + * Get margin trades for a specific symbol (async). + * + * @param symbol symbol to get trades from + * @return a list of trades + */ + void getMyTrades(String symbol, BinanceApiCallback> callback); + + // User stream endpoints + + /** + * Start a new user data stream (async). + * + * @return a listen key that can be used with data streams + */ + void startUserDataStream(BinanceApiCallback callback); + + /** + * PING a user data stream to prevent a time out (async). + * + * @param listenKey listen key that identifies a data stream + */ + void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback); + + /** + * Execute transfer between spot account and margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + void transfer(String asset, String amount, TransferType type, BinanceApiCallback callback); + + /** + * Apply for a loan + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + void borrow(String asset, String amount, BinanceApiCallback callback); + + /** + * Repay loan for margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + void repay(String asset, String amount, BinanceApiCallback callback); + +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java old mode 100644 new mode 100755 index a6e7fe7ad..a51a2bb9f --- a/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncRestClient.java @@ -1,314 +1,314 @@ -package com.binance.api.client; - -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.event.ListenKey; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.ServerTime; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -/** - * Binance API façade, supporting asynchronous/non-blocking access Binance's REST API. - */ -public interface BinanceApiAsyncRestClient { - - // General endpoints - - /** - * Test connectivity to the Rest API. - */ - void ping(BinanceApiCallback callback); - - /** - * Check server time. - */ - void getServerTime(BinanceApiCallback callback); - - /** - * Current exchange trading rules and symbol information - */ - void getExchangeInfo(BinanceApiCallback callback); - - /** - * ALL supported assets and whether or not they can be withdrawn. - */ - void getAllAssets(BinanceApiCallback> callback); - - // Market Data endpoints - - /** - * Get order book of a symbol (asynchronous) - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit depth of the order book (max 100) - * @param callback the callback that handles the response - */ - void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback); - - /** - * Get recent trades (up to last 500). Weight: 1 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - * @param callback the callback that handles the response - */ - void getTrades(String symbol, Integer limit, BinanceApiCallback> callback); - - /** - * Get older trades. Weight: 5 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - * @param fromId TradeId to fetch from. Default gets most recent trades. - * @param callback the callback that handles the response - */ - void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback); - - /** - * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with - * the same price will have the quantity aggregated. - * - * If both startTime and endTime are sent, limitshould not - * be sent AND the distance between startTime and endTime must be less than 24 hours. - * - * @param symbol symbol to aggregate (mandatory) - * @param fromId ID to get aggregate trades from INCLUSIVE (optional) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). - * @param callback the callback that handles the response - * @return a list of aggregate trades for the given symbol - */ - void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); - - /** - * Return the most recent aggregate trades for symbol - * - * @see #getAggTrades(String, String, Integer, Long, Long, BinanceApiCallback) - */ - void getAggTrades(String symbol, BinanceApiCallback> callback); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @param symbol symbol to aggregate (mandatory) - * @param interval candlestick interval (mandatory) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). - * @param callback the callback that handles the response containing a candlestick bar for the given symbol and interval - */ - void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @see #getCandlestickBars(String, CandlestickInterval, BinanceApiCallback) - */ - void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback); - - /** - * Get 24 hour price change statistics (asynchronous). - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param callback the callback that handles the response - */ - void get24HrPriceStatistics(String symbol, BinanceApiCallback callback); - - /** - * Get 24 hour price change statistics for all symbols (asynchronous). - * - * @param callback the callback that handles the response - */ - void getAll24HrPriceStatistics(BinanceApiCallback> callback); - - /** - * Get Latest price for all symbols (asynchronous). - * - * @param callback the callback that handles the response - */ - void getAllPrices(BinanceApiCallback> callback); - - /** - * Get latest price for symbol (asynchronous). - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param callback the callback that handles the response - */ - void getPrice(String symbol , BinanceApiCallback callback); - - /** - * Get best price/qty on the order book for all symbols (asynchronous). - * - * @param callback the callback that handles the response - */ - void getBookTickers(BinanceApiCallback> callback); - - // Account endpoints - - /** - * Send in a new order (asynchronous) - * - * @param order the new order to submit. - * @param callback the callback that handles the response - */ - void newOrder(NewOrder order, BinanceApiCallback callback); - - /** - * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. - * - * @param order the new TEST order to submit. - * @param callback the callback that handles the response - */ - void newOrderTest(NewOrder order, BinanceApiCallback callback); - - /** - * Check an order's status (asynchronous). - * - * @param orderStatusRequest order status request parameters - * @param callback the callback that handles the response - */ - void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback); - - /** - * Cancel an active order (asynchronous). - * - * @param cancelOrderRequest order status request parameters - * @param callback the callback that handles the response - */ - void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); - - /** - * Get all open orders on a symbol (asynchronous). - * - * @param orderRequest order request parameters - * @param callback the callback that handles the response - */ - void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback); - - /** - * Get all account orders; active, canceled, or filled. - * - * @param orderRequest order request parameters - * @param callback the callback that handles the response - */ - void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback); - - /** - * Get current account information (async). - */ - void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback); - - /** - * Get current account information using default parameters (async). - */ - void getAccount(BinanceApiCallback callback); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @param fromId TradeId to fetch from. Default gets most recent trades. - * @param callback the callback that handles the response with a list of trades - */ - void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @param callback the callback that handles the response with a list of trades - */ - void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param callback the callback that handles the response with a list of trades - */ - void getMyTrades(String symbol, BinanceApiCallback> callback); - - /** - * Submit a withdraw request. - * - * Enable Withdrawals option has to be active in the API settings. - * - * @param asset asset symbol to withdraw - * @param address address to withdraw to - * @param amount amount to withdraw - * @param name description/alias of the address - * @param addressTag Secondary address identifier for coins like XRP,XMR etc. - */ - void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback); - - /** - * Fetch account deposit history. - * - * @param callback the callback that handles the response and returns the deposit history - */ - void getDepositHistory(String asset, BinanceApiCallback callback); - - /** - * Fetch account withdraw history. - * - * @param callback the callback that handles the response and returns the withdraw history - */ - void getWithdrawHistory(String asset, BinanceApiCallback callback); - - /** - * Fetch deposit address. - * - * @param callback the callback that handles the response and returns the deposit address - */ - void getDepositAddress(String asset, BinanceApiCallback callback); - - // User stream endpoints - - /** - * Start a new user data stream. - * - * @param callback the callback that handles the response which contains a listenKey - */ - void startUserDataStream(BinanceApiCallback callback); - - /** - * PING a user data stream to prevent a time out. - * - * @param listenKey listen key that identifies a data stream - * @param callback the callback that handles the response which contains a listenKey - */ - void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback); - - /** - * Close out a new user data stream. - * - * @param listenKey listen key that identifies a data stream - * @param callback the callback that handles the response which contains a listenKey - */ - void closeUserDataStream(String listenKey, BinanceApiCallback callback); +package com.binance.api.client; + +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +/** + * Binance API façade, supporting asynchronous/non-blocking access Binance's REST API. + */ +public interface BinanceApiAsyncRestClient { + + // General endpoints + + /** + * Test connectivity to the Rest API. + */ + void ping(BinanceApiCallback callback); + + /** + * Check server time. + */ + void getServerTime(BinanceApiCallback callback); + + /** + * Current exchange trading rules and symbol information + */ + void getExchangeInfo(BinanceApiCallback callback); + + /** + * ALL supported assets and whether or not they can be withdrawn. + */ + void getAllAssets(BinanceApiCallback> callback); + + // Market Data endpoints + + /** + * Get order book of a symbol (asynchronous) + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit depth of the order book (max 100) + * @param callback the callback that handles the response + */ + void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback); + + /** + * Get recent trades (up to last 500). Weight: 1 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + * @param callback the callback that handles the response + */ + void getTrades(String symbol, Integer limit, BinanceApiCallback> callback); + + /** + * Get older trades. Weight: 5 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + * @param fromId TradeId to fetch from. Default gets most recent trades. + * @param callback the callback that handles the response + */ + void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback); + + /** + * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with + * the same price will have the quantity aggregated. + * + * If both startTime and endTime are sent, limitshould not + * be sent AND the distance between startTime and endTime must be less than 24 hours. + * + * @param symbol symbol to aggregate (mandatory) + * @param fromId ID to get aggregate trades from INCLUSIVE (optional) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). + * @param callback the callback that handles the response + * @return a list of aggregate trades for the given symbol + */ + void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); + + /** + * Return the most recent aggregate trades for symbol + * + * @see #getAggTrades(String, String, Integer, Long, Long, BinanceApiCallback) + */ + void getAggTrades(String symbol, BinanceApiCallback> callback); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @param symbol symbol to aggregate (mandatory) + * @param interval candlestick interval (mandatory) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). + * @param callback the callback that handles the response containing a candlestick bar for the given symbol and interval + */ + void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @see #getCandlestickBars(String, CandlestickInterval, BinanceApiCallback) + */ + void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback); + + /** + * Get 24 hour price change statistics (asynchronous). + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param callback the callback that handles the response + */ + void get24HrPriceStatistics(String symbol, BinanceApiCallback callback); + + /** + * Get 24 hour price change statistics for all symbols (asynchronous). + * + * @param callback the callback that handles the response + */ + void getAll24HrPriceStatistics(BinanceApiCallback> callback); + + /** + * Get Latest price for all symbols (asynchronous). + * + * @param callback the callback that handles the response + */ + void getAllPrices(BinanceApiCallback> callback); + + /** + * Get latest price for symbol (asynchronous). + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param callback the callback that handles the response + */ + void getPrice(String symbol , BinanceApiCallback callback); + + /** + * Get best price/qty on the order book for all symbols (asynchronous). + * + * @param callback the callback that handles the response + */ + void getBookTickers(BinanceApiCallback> callback); + + // Account endpoints + + /** + * Send in a new order (asynchronous) + * + * @param order the new order to submit. + * @param callback the callback that handles the response + */ + void newOrder(NewOrder order, BinanceApiCallback callback); + + /** + * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. + * + * @param order the new TEST order to submit. + * @param callback the callback that handles the response + */ + void newOrderTest(NewOrder order, BinanceApiCallback callback); + + /** + * Check an order's status (asynchronous). + * + * @param orderStatusRequest order status request parameters + * @param callback the callback that handles the response + */ + void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback); + + /** + * Cancel an active order (asynchronous). + * + * @param cancelOrderRequest order status request parameters + * @param callback the callback that handles the response + */ + void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback); + + /** + * Get all open orders on a symbol (asynchronous). + * + * @param orderRequest order request parameters + * @param callback the callback that handles the response + */ + void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback); + + /** + * Get all account orders; active, canceled, or filled. + * + * @param orderRequest order request parameters + * @param callback the callback that handles the response + */ + void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback); + + /** + * Get current account information (async). + */ + void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback); + + /** + * Get current account information using default parameters (async). + */ + void getAccount(BinanceApiCallback callback); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @param fromId TradeId to fetch from. Default gets most recent trades. + * @param callback the callback that handles the response with a list of trades + */ + void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @param callback the callback that handles the response with a list of trades + */ + void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param callback the callback that handles the response with a list of trades + */ + void getMyTrades(String symbol, BinanceApiCallback> callback); + + /** + * Submit a withdraw request. + * + * Enable Withdrawals option has to be active in the API settings. + * + * @param asset asset symbol to withdraw + * @param address address to withdraw to + * @param amount amount to withdraw + * @param name description/alias of the address + * @param addressTag Secondary address identifier for coins like XRP,XMR etc. + */ + void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback); + + /** + * Fetch account deposit history. + * + * @param callback the callback that handles the response and returns the deposit history + */ + void getDepositHistory(String asset, BinanceApiCallback callback); + + /** + * Fetch account withdraw history. + * + * @param callback the callback that handles the response and returns the withdraw history + */ + void getWithdrawHistory(String asset, BinanceApiCallback callback); + + /** + * Fetch deposit address. + * + * @param callback the callback that handles the response and returns the deposit address + */ + void getDepositAddress(String asset, BinanceApiCallback callback); + + // User stream endpoints + + /** + * Start a new user data stream. + * + * @param callback the callback that handles the response which contains a listenKey + */ + void startUserDataStream(BinanceApiCallback callback); + + /** + * PING a user data stream to prevent a time out. + * + * @param listenKey listen key that identifies a data stream + * @param callback the callback that handles the response which contains a listenKey + */ + void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback); + + /** + * Close out a new user data stream. + * + * @param listenKey listen key that identifies a data stream + * @param callback the callback that handles the response which contains a listenKey + */ + void closeUserDataStream(String listenKey, BinanceApiCallback callback); } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/BinanceApiCallback.java b/src/main/java/com/binance/api/client/BinanceApiCallback.java old mode 100644 new mode 100755 index f492cc1da..3112bd793 --- a/src/main/java/com/binance/api/client/BinanceApiCallback.java +++ b/src/main/java/com/binance/api/client/BinanceApiCallback.java @@ -1,24 +1,24 @@ -package com.binance.api.client; - -/** - * BinanceApiCallback is a functional interface used together with the BinanceApiAsyncClient to provide a non-blocking REST client. - * - * @param the return type from the callback - */ -@FunctionalInterface -public interface BinanceApiCallback { - - /** - * Called whenever a response comes back from the Binance API. - * - * @param response the expected response object - */ - void onResponse(T response); - - /** - * Called whenever an error occurs. - * - * @param cause the cause of the failure - */ - default void onFailure(Throwable cause) {} +package com.binance.api.client; + +/** + * BinanceApiCallback is a functional interface used together with the BinanceApiAsyncClient to provide a non-blocking REST client. + * + * @param the return type from the callback + */ +@FunctionalInterface +public interface BinanceApiCallback { + + /** + * Called whenever a response comes back from the Binance API. + * + * @param response the expected response object + */ + void onResponse(T response); + + /** + * Called whenever an error occurs. + * + * @param cause the cause of the failure + */ + default void onFailure(Throwable cause) {} } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java old mode 100644 new mode 100755 index 7c05f83bf..a529e237c --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -1,75 +1,88 @@ -package com.binance.api.client; - -import com.binance.api.client.impl.BinanceApiAsyncRestClientImpl; -import com.binance.api.client.impl.BinanceApiRestClientImpl; -import com.binance.api.client.impl.BinanceApiWebSocketClientImpl; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.getSharedClient; - -/** - * A factory for creating BinanceApi client objects. - */ -public class BinanceApiClientFactory { - - /** - * API Key - */ - private String apiKey; - - /** - * Secret. - */ - private String secret; - - /** - * Instantiates a new binance api client factory. - * - * @param apiKey the API key - * @param secret the Secret - */ - private BinanceApiClientFactory(String apiKey, String secret) { - this.apiKey = apiKey; - this.secret = secret; - } - - /** - * New instance. - * - * @param apiKey the API key - * @param secret the Secret - * - * @return the binance api client factory - */ - public static BinanceApiClientFactory newInstance(String apiKey, String secret) { - return new BinanceApiClientFactory(apiKey, secret); - } - - /** - * New instance without authentication. - * - * @return the binance api client factory - */ - public static BinanceApiClientFactory newInstance() { - return new BinanceApiClientFactory(null, null); - } - - /** - * Creates a new synchronous/blocking REST client. - */ - public BinanceApiRestClient newRestClient() { - return new BinanceApiRestClientImpl(apiKey, secret); - } - - /** - * Creates a new asynchronous/non-blocking REST client. - */ - public BinanceApiAsyncRestClient newAsyncRestClient() {return new BinanceApiAsyncRestClientImpl(apiKey, secret); - } - - /** - * Creates a new web socket client used for handling data streams. - */ - public BinanceApiWebSocketClient newWebSocketClient() { - return new BinanceApiWebSocketClientImpl(getSharedClient()); - } -} +package com.binance.api.client; + +import com.binance.api.client.impl.*; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.getSharedClient; + +/** + * A factory for creating BinanceApi client objects. + */ +public class BinanceApiClientFactory { + + /** + * API Key + */ + private String apiKey; + + /** + * Secret. + */ + private String secret; + + /** + * Instantiates a new binance api client factory. + * + * @param apiKey the API key + * @param secret the Secret + */ + private BinanceApiClientFactory(String apiKey, String secret) { + this.apiKey = apiKey; + this.secret = secret; + } + + /** + * New instance. + * + * @param apiKey the API key + * @param secret the Secret + * + * @return the binance api client factory + */ + public static BinanceApiClientFactory newInstance(String apiKey, String secret) { + return new BinanceApiClientFactory(apiKey, secret); + } + + /** + * New instance without authentication. + * + * @return the binance api client factory + */ + public static BinanceApiClientFactory newInstance() { + return new BinanceApiClientFactory(null, null); + } + + /** + * Creates a new synchronous/blocking REST client. + */ + public BinanceApiRestClient newRestClient() { + return new BinanceApiRestClientImpl(apiKey, secret); + } + + /** + * Creates a new asynchronous/non-blocking REST client. + */ + public BinanceApiAsyncRestClient newAsyncRestClient() { + return new BinanceApiAsyncRestClientImpl(apiKey, secret); + } + + /** + * Creates a new asynchronous/non-blocking Margin REST client. + */ + public BinanceApiAsyncMarginRestClient newAsyncMarginRestClient() { + return new BinanceApiAsyncMarginRestClientImpl(apiKey, secret); + } + + /** + * Creates a new synchronous/blocking Margin REST client. + */ + public BinanceApiMarginRestClient newMarginRestClient() { + return new BinanceApiMarginRestClientImpl(apiKey, secret); + } + + /** + * Creates a new web socket client used for handling data streams. + */ + public BinanceApiWebSocketClient newWebSocketClient() { + return new BinanceApiWebSocketClientImpl(getSharedClient()); + } +} diff --git a/src/main/java/com/binance/api/client/BinanceApiError.java b/src/main/java/com/binance/api/client/BinanceApiError.java old mode 100644 new mode 100755 index c5adc184e..b0d98ab8c --- a/src/main/java/com/binance/api/client/BinanceApiError.java +++ b/src/main/java/com/binance/api/client/BinanceApiError.java @@ -1,44 +1,44 @@ -package com.binance.api.client; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Binance API error object. - */ -public class BinanceApiError { - - /** - * Error code. - */ - private int code; - - /** - * Error message. - */ - private String msg; - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("code", code) - .append("msg", msg) - .toString(); - } -} +package com.binance.api.client; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Binance API error object. + */ +public class BinanceApiError { + + /** + * Error code. + */ + private int code; + + /** + * Error message. + */ + private String msg; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("code", code) + .append("msg", msg) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java new file mode 100755 index 000000000..3e146ee39 --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -0,0 +1,103 @@ +package com.binance.api.client; + +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import java.util.List; + +public interface BinanceApiMarginRestClient { + /** + * Get current margin account information using default parameters. + */ + MarginAccount getAccount(); + + /** + * Get all open orders on margin account for a symbol. + * + * @param orderRequest order request parameters + */ + List getOpenOrders(OrderRequest orderRequest); + + /** + * Send in a new margin order. + * + * @param order the new order to submit. + * @return a response containing details about the newly placed order. + */ + NewOrderResponse newOrder(NewOrder order); + + /** + * Cancel an active margin order. + * + * @param cancelOrderRequest order status request parameters + */ + CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); + + /** + * Check margin order's status. + * @param orderStatusRequest order status request options/filters + * + * @return an order + */ + Order getOrderStatus(OrderStatusRequest orderStatusRequest); + + /** + * Get margin trades for a specific symbol. + * + * @param symbol symbol to get trades from + * @return a list of trades + */ + List getMyTrades(String symbol); + + // User stream endpoints + + /** + * Start a new user data stream. + * + * @return a listen key that can be used with data streams + */ + String startUserDataStream(); + + /** + * PING a user data stream to prevent a time out. + * + * @param listenKey listen key that identifies a data stream + */ + void keepAliveUserDataStream(String listenKey); + + /** + * Execute transfer between spot account and margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + MarginTransaction transfer(String asset, String amount, TransferType type); + + /** + * Apply for a loan + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + MarginTransaction borrow(String asset, String amount); + + /** + * Repay loan for margin account + * @param asset asset to repay + * @param amount amount to repay + * @return transaction id + */ + MarginTransaction repay(String asset, String amount); + + /** + * Query loan record + * @param asset asset to query + * @param txId the tranId in POST /sapi/v1/margin/loan + * @return loan records + */ + LoanQueryResult queryLoan(String asset, String txId); +} diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java old mode 100644 new mode 100755 index e405d4a7f..82a6a2be9 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -1,298 +1,298 @@ -package com.binance.api.client; - -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -/** - * Binance API façade, supporting synchronous/blocking access Binance's REST API. - */ -public interface BinanceApiRestClient { - - // General endpoints - - /** - * Test connectivity to the Rest API. - */ - void ping(); - - /** - * Test connectivity to the Rest API and get the current server time. - * - * @return current server time. - */ - Long getServerTime(); - - /** - * @return Current exchange trading rules and symbol information - */ - ExchangeInfo getExchangeInfo(); - - /** - * @return All the supported assets and whether or not they can be withdrawn. - */ - List getAllAssets(); - - // Market Data endpoints - - /** - * Get order book of a symbol. - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit depth of the order book (max 100) - */ - OrderBook getOrderBook(String symbol, Integer limit); - - /** - * Get recent trades (up to last 500). Weight: 1 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - */ - List getTrades(String symbol, Integer limit); - - /** - * Get older trades. Weight: 5 - * - * @param symbol ticker symbol (e.g. ETHBTC) - * @param limit of last trades (Default 500; max 1000.) - * @param fromId TradeId to fetch from. Default gets most recent trades. - */ - List getHistoricalTrades(String symbol, Integer limit, Long fromId); - - /** - * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with - * the same price will have the quantity aggregated. - * - * If both startTime and endTime are sent, limitshould not - * be sent AND the distance between startTime and endTime must be less than 24 hours. - * - * @param symbol symbol to aggregate (mandatory) - * @param fromId ID to get aggregate trades from INCLUSIVE (optional) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). - * @return a list of aggregate trades for the given symbol - */ - List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime); - - /** - * Return the most recent aggregate trades for symbol - * - * @see #getAggTrades(String, String, Integer, Long, Long) - */ - List getAggTrades(String symbol); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @param symbol symbol to aggregate (mandatory) - * @param interval candlestick interval (mandatory) - * @param limit Default 500; max 1000 (optional) - * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). - * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). - * @return a candlestick bar for the given symbol and interval - */ - List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime); - - /** - * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - * - * @see #getCandlestickBars(String, CandlestickInterval, Integer, Long, Long) - */ - List getCandlestickBars(String symbol, CandlestickInterval interval); - - /** - * Get 24 hour price change statistics. - * - * @param symbol ticker symbol (e.g. ETHBTC) - */ - TickerStatistics get24HrPriceStatistics(String symbol); - - /** - * Get 24 hour price change statistics for all symbols. - */ - List getAll24HrPriceStatistics(); - - /** - * Get Latest price for all symbols. - */ - List getAllPrices(); - - /** - * Get latest price for symbol. - * - * @param symbol ticker symbol (e.g. ETHBTC) - */ - TickerPrice getPrice(String symbol); - - /** - * Get best price/qty on the order book for all symbols. - */ - List getBookTickers(); - - // Account endpoints - - /** - * Send in a new order. - * - * @param order the new order to submit. - * @return a response containing details about the newly placed order. - */ - NewOrderResponse newOrder(NewOrder order); - - /** - * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. - * - * @param order the new TEST order to submit. - */ - void newOrderTest(NewOrder order); - - /** - * Check an order's status. - * @param orderStatusRequest order status request options/filters - * - * @return an order - */ - Order getOrderStatus(OrderStatusRequest orderStatusRequest); - - /** - * Cancel an active order. - * - * @param cancelOrderRequest order status request parameters - */ - CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); - - /** - * Get all open orders on a symbol. - * - * @param orderRequest order request parameters - * @return a list of all account open orders on a symbol. - */ - List getOpenOrders(OrderRequest orderRequest); - - /** - * Get all account orders; active, canceled, or filled. - * - * @param orderRequest order request parameters - * @return a list of all account orders - */ - List getAllOrders(AllOrdersRequest orderRequest); - - /** - * Get current account information. - */ - Account getAccount(Long recvWindow, Long timestamp); - - /** - * Get current account information using default parameters. - */ - Account getAccount(); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @param fromId TradeId to fetch from. Default gets most recent trades. - * @return a list of trades - */ - List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @param limit default 500; max 1000 - * @return a list of trades - */ - List getMyTrades(String symbol, Integer limit); - - /** - * Get trades for a specific account and symbol. - * - * @param symbol symbol to get trades from - * @return a list of trades - */ - List getMyTrades(String symbol); - - /** - * Submit a withdraw request. - * - * Enable Withdrawals option has to be active in the API settings. - * - * @param asset asset symbol to withdraw - * @param address address to withdraw to - * @param amount amount to withdraw - * @param name description/alias of the address - * @param addressTag Secondary address identifier for coins like XRP,XMR etc. - */ - WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag); - - /** - * Fetch account deposit history. - * - * @return deposit history, containing a list of deposits - */ - DepositHistory getDepositHistory(String asset); - - /** - * Fetch account withdraw history. - * - * @return withdraw history, containing a list of withdrawals - */ - WithdrawHistory getWithdrawHistory(String asset); - - /** - * Fetch deposit address. - * - * @return deposit address for a given asset. - */ - DepositAddress getDepositAddress(String asset); - - // User stream endpoints - - /** - * Start a new user data stream. - * - * @return a listen key that can be used with data streams - */ - String startUserDataStream(); - - /** - * PING a user data stream to prevent a time out. - * - * @param listenKey listen key that identifies a data stream - */ - void keepAliveUserDataStream(String listenKey); - - /** - * Close out a new user data stream. - * - * @param listenKey listen key that identifies a data stream - */ - void closeUserDataStream(String listenKey); -} +package com.binance.api.client; + +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +/** + * Binance API façade, supporting synchronous/blocking access Binance's REST API. + */ +public interface BinanceApiRestClient { + + // General endpoints + + /** + * Test connectivity to the Rest API. + */ + void ping(); + + /** + * Test connectivity to the Rest API and get the current server time. + * + * @return current server time. + */ + Long getServerTime(); + + /** + * @return Current exchange trading rules and symbol information + */ + ExchangeInfo getExchangeInfo(); + + /** + * @return All the supported assets and whether or not they can be withdrawn. + */ + List getAllAssets(); + + // Market Data endpoints + + /** + * Get order book of a symbol. + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit depth of the order book (max 100) + */ + OrderBook getOrderBook(String symbol, Integer limit); + + /** + * Get recent trades (up to last 500). Weight: 1 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + */ + List getTrades(String symbol, Integer limit); + + /** + * Get older trades. Weight: 5 + * + * @param symbol ticker symbol (e.g. ETHBTC) + * @param limit of last trades (Default 500; max 1000.) + * @param fromId TradeId to fetch from. Default gets most recent trades. + */ + List getHistoricalTrades(String symbol, Integer limit, Long fromId); + + /** + * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with + * the same price will have the quantity aggregated. + * + * If both startTime and endTime are sent, limitshould not + * be sent AND the distance between startTime and endTime must be less than 24 hours. + * + * @param symbol symbol to aggregate (mandatory) + * @param fromId ID to get aggregate trades from INCLUSIVE (optional) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get aggregate trades from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get aggregate trades until INCLUSIVE (optional). + * @return a list of aggregate trades for the given symbol + */ + List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime); + + /** + * Return the most recent aggregate trades for symbol + * + * @see #getAggTrades(String, String, Integer, Long, Long) + */ + List getAggTrades(String symbol); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @param symbol symbol to aggregate (mandatory) + * @param interval candlestick interval (mandatory) + * @param limit Default 500; max 1000 (optional) + * @param startTime Timestamp in ms to get candlestick bars from INCLUSIVE (optional). + * @param endTime Timestamp in ms to get candlestick bars until INCLUSIVE (optional). + * @return a candlestick bar for the given symbol and interval + */ + List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime); + + /** + * Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. + * + * @see #getCandlestickBars(String, CandlestickInterval, Integer, Long, Long) + */ + List getCandlestickBars(String symbol, CandlestickInterval interval); + + /** + * Get 24 hour price change statistics. + * + * @param symbol ticker symbol (e.g. ETHBTC) + */ + TickerStatistics get24HrPriceStatistics(String symbol); + + /** + * Get 24 hour price change statistics for all symbols. + */ + List getAll24HrPriceStatistics(); + + /** + * Get Latest price for all symbols. + */ + List getAllPrices(); + + /** + * Get latest price for symbol. + * + * @param symbol ticker symbol (e.g. ETHBTC) + */ + TickerPrice getPrice(String symbol); + + /** + * Get best price/qty on the order book for all symbols. + */ + List getBookTickers(); + + // Account endpoints + + /** + * Send in a new order. + * + * @param order the new order to submit. + * @return a response containing details about the newly placed order. + */ + NewOrderResponse newOrder(NewOrder order); + + /** + * Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. + * + * @param order the new TEST order to submit. + */ + void newOrderTest(NewOrder order); + + /** + * Check an order's status. + * @param orderStatusRequest order status request options/filters + * + * @return an order + */ + Order getOrderStatus(OrderStatusRequest orderStatusRequest); + + /** + * Cancel an active order. + * + * @param cancelOrderRequest order status request parameters + */ + CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest); + + /** + * Get all open orders on a symbol. + * + * @param orderRequest order request parameters + * @return a list of all account open orders on a symbol. + */ + List getOpenOrders(OrderRequest orderRequest); + + /** + * Get all account orders; active, canceled, or filled. + * + * @param orderRequest order request parameters + * @return a list of all account orders + */ + List getAllOrders(AllOrdersRequest orderRequest); + + /** + * Get current account information. + */ + Account getAccount(Long recvWindow, Long timestamp); + + /** + * Get current account information using default parameters. + */ + Account getAccount(); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @param fromId TradeId to fetch from. Default gets most recent trades. + * @return a list of trades + */ + List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @param limit default 500; max 1000 + * @return a list of trades + */ + List getMyTrades(String symbol, Integer limit); + + /** + * Get trades for a specific account and symbol. + * + * @param symbol symbol to get trades from + * @return a list of trades + */ + List getMyTrades(String symbol); + + /** + * Submit a withdraw request. + * + * Enable Withdrawals option has to be active in the API settings. + * + * @param asset asset symbol to withdraw + * @param address address to withdraw to + * @param amount amount to withdraw + * @param name description/alias of the address + * @param addressTag Secondary address identifier for coins like XRP,XMR etc. + */ + WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag); + + /** + * Fetch account deposit history. + * + * @return deposit history, containing a list of deposits + */ + DepositHistory getDepositHistory(String asset); + + /** + * Fetch account withdraw history. + * + * @return withdraw history, containing a list of withdrawals + */ + WithdrawHistory getWithdrawHistory(String asset); + + /** + * Fetch deposit address. + * + * @return deposit address for a given asset. + */ + DepositAddress getDepositAddress(String asset); + + // User stream endpoints + + /** + * Start a new user data stream. + * + * @return a listen key that can be used with data streams + */ + String startUserDataStream(); + + /** + * PING a user data stream to prevent a time out. + * + * @param listenKey listen key that identifies a data stream + */ + void keepAliveUserDataStream(String listenKey); + + /** + * Close out a new user data stream. + * + * @param listenKey listen key that identifies a data stream + */ + void closeUserDataStream(String listenKey); +} diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java old mode 100644 new mode 100755 index 7961efc49..ba78819ac --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -1,68 +1,68 @@ -package com.binance.api.client; - -import com.binance.api.client.domain.event.AggTradeEvent; -import com.binance.api.client.domain.event.AllMarketTickersEvent; -import com.binance.api.client.domain.event.CandlestickEvent; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; -import com.binance.api.client.domain.market.CandlestickInterval; - -import java.io.Closeable; -import java.util.List; - -/** - * Binance API data streaming façade, supporting streaming of events through web sockets. - */ -public interface BinanceApiWebSocketClient extends Closeable { - - /** - * Open a new web socket to receive {@link DepthEvent depthEvents} on a callback. - * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onDepthEvent(String symbols, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link CandlestickEvent candlestickEvents} on a callback. - * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param interval the interval of the candles tick events required - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link AggTradeEvent aggTradeEvents} on a callback. - * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link UserDataUpdateEvent userDataUpdateEvents} on a callback. - * - * @param listenKey the listen key to subscribe to. - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback); - - /** - * Open a new web socket to receive {@link AllMarketTickersEvent allMarketTickersEvents} on a callback. - * - * @param callback the callback to call on new events - * @return a {@link Closeable} that allows the underlying web socket to be closed. - */ - Closeable onAllMarketTickersEvent(BinanceApiCallback> callback); - - /** - * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. - */ - @Deprecated - void close(); -} +package com.binance.api.client; + +import com.binance.api.client.domain.event.AggTradeEvent; +import com.binance.api.client.domain.event.AllMarketTickersEvent; +import com.binance.api.client.domain.event.CandlestickEvent; +import com.binance.api.client.domain.event.DepthEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.binance.api.client.domain.market.CandlestickInterval; + +import java.io.Closeable; +import java.util.List; + +/** + * Binance API data streaming façade, supporting streaming of events through web sockets. + */ +public interface BinanceApiWebSocketClient extends Closeable { + + /** + * Open a new web socket to receive {@link DepthEvent depthEvents} on a callback. + * + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onDepthEvent(String symbols, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link CandlestickEvent candlestickEvents} on a callback. + * + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param interval the interval of the candles tick events required + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link AggTradeEvent aggTradeEvents} on a callback. + * + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link UserDataUpdateEvent userDataUpdateEvents} on a callback. + * + * @param listenKey the listen key to subscribe to. + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback); + + /** + * Open a new web socket to receive {@link AllMarketTickersEvent allMarketTickersEvents} on a callback. + * + * @param callback the callback to call on new events + * @return a {@link Closeable} that allows the underlying web socket to be closed. + */ + Closeable onAllMarketTickersEvent(BinanceApiCallback> callback); + + /** + * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. + */ + @Deprecated + void close(); +} diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java old mode 100644 new mode 100755 index bcc39452d..7d829f119 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -1,53 +1,58 @@ -package com.binance.api.client.constant; - -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * Constants used throughout Binance's API. - */ -public class BinanceApiConstants { - - /** - * REST API base URL. - */ - public static final String API_BASE_URL = "https://api.binance.com"; - - /** - * Streaming API base URL. - */ - public static final String WS_API_BASE_URL = "wss://stream.binance.com:9443/ws"; - - /** - * Asset info base URL. - */ - public static final String ASSET_INFO_API_BASE_URL = "https://www.binance.com/"; - - /** - * HTTP Header to be used for API-KEY authentication. - */ - public static final String API_KEY_HEADER = "X-MBX-APIKEY"; - - /** - * Decorator to indicate that an endpoint requires an API key. - */ - public static final String ENDPOINT_SECURITY_TYPE_APIKEY = "APIKEY"; - public static final String ENDPOINT_SECURITY_TYPE_APIKEY_HEADER = ENDPOINT_SECURITY_TYPE_APIKEY + ": #"; - - /** - * Decorator to indicate that an endpoint requires a signature. - */ - public static final String ENDPOINT_SECURITY_TYPE_SIGNED = "SIGNED"; - public static final String ENDPOINT_SECURITY_TYPE_SIGNED_HEADER = ENDPOINT_SECURITY_TYPE_SIGNED + ": #"; - - /** - * Default receiving window. - */ - public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; - - /** - * Default ToStringStyle used by toString methods. - * Override this to change the output format of the overridden toString methods. - * - Example ToStringStyle.JSON_STYLE - */ - public static ToStringStyle TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; -} +package com.binance.api.client.constant; + +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * Constants used throughout Binance's API. + */ +public class BinanceApiConstants { + + /** + * REST API base URL. + */ + public static final String API_BASE_URL = "https://api.binance.com"; + + /** + * Streaming API base URL. + */ + public static final String WS_API_BASE_URL = "wss://stream.binance.com:9443/ws"; + + /** + * Asset info base URL. + */ + public static final String ASSET_INFO_API_BASE_URL = "https://www.binance.com/"; + + /** + * HTTP Header to be used for API-KEY authentication. + */ + public static final String API_KEY_HEADER = "X-MBX-APIKEY"; + + /** + * Decorator to indicate that an endpoint requires an API key. + */ + public static final String ENDPOINT_SECURITY_TYPE_APIKEY = "APIKEY"; + public static final String ENDPOINT_SECURITY_TYPE_APIKEY_HEADER = ENDPOINT_SECURITY_TYPE_APIKEY + ": #"; + + /** + * Decorator to indicate that an endpoint requires a signature. + */ + public static final String ENDPOINT_SECURITY_TYPE_SIGNED = "SIGNED"; + public static final String ENDPOINT_SECURITY_TYPE_SIGNED_HEADER = ENDPOINT_SECURITY_TYPE_SIGNED + ": #"; + + /** + * Default receiving window. + */ + public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; + + /** + * Default margin receiving window. + */ + public static final long DEFAULT_MARGIN_RECEIVING_WINDOW = 5_000L; + + /** + * Default ToStringStyle used by toString methods. + * Override this to change the output format of the overridden toString methods. + * - Example ToStringStyle.JSON_STYLE + */ + public static ToStringStyle TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; +} diff --git a/src/main/java/com/binance/api/client/domain/ExecutionType.java b/src/main/java/com/binance/api/client/domain/ExecutionType.java old mode 100644 new mode 100755 index 4da14d863..1e2a5e4f8 --- a/src/main/java/com/binance/api/client/domain/ExecutionType.java +++ b/src/main/java/com/binance/api/client/domain/ExecutionType.java @@ -1,16 +1,16 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Order execution type. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum ExecutionType { - NEW, - CANCELED, - REPLACED, - REJECTED, - TRADE, - EXPIRED +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Order execution type. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum ExecutionType { + NEW, + CANCELED, + REPLACED, + REJECTED, + TRADE, + EXPIRED } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/LoanStatus.java b/src/main/java/com/binance/api/client/domain/LoanStatus.java new file mode 100755 index 000000000..802e9981b --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/LoanStatus.java @@ -0,0 +1,11 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a submitted order. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum LoanStatus { + PENDING, CONFIRMED, FAILED +} diff --git a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java old mode 100644 new mode 100755 index ff9374e8a..52a1e3990 --- a/src/main/java/com/binance/api/client/domain/OrderRejectReason.java +++ b/src/main/java/com/binance/api/client/domain/OrderRejectReason.java @@ -1,21 +1,21 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Order reject reason values. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderRejectReason { - NONE, - UNKNOWN_INSTRUMENT, - MARKET_CLOSED, - PRICE_QTY_EXCEED_HARD_LIMITS, - UNKNOWN_ORDER, - DUPLICATE_ORDER, - UNKNOWN_ACCOUNT, - INSUFFICIENT_BALANCE, - ACCOUNT_INACTIVE, - ACCOUNT_CANNOT_SETTLE, - ORDER_WOULD_TRIGGER_IMMEDIATELY +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Order reject reason values. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderRejectReason { + NONE, + UNKNOWN_INSTRUMENT, + MARKET_CLOSED, + PRICE_QTY_EXCEED_HARD_LIMITS, + UNKNOWN_ORDER, + DUPLICATE_ORDER, + UNKNOWN_ACCOUNT, + INSUFFICIENT_BALANCE, + ACCOUNT_INACTIVE, + ACCOUNT_CANNOT_SETTLE, + ORDER_WOULD_TRIGGER_IMMEDIATELY } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/OrderSide.java b/src/main/java/com/binance/api/client/domain/OrderSide.java old mode 100644 new mode 100755 index db74f9373..2f01d92db --- a/src/main/java/com/binance/api/client/domain/OrderSide.java +++ b/src/main/java/com/binance/api/client/domain/OrderSide.java @@ -1,12 +1,12 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Buy/Sell order side. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderSide { - BUY, - SELL -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Buy/Sell order side. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderSide { + BUY, + SELL +} diff --git a/src/main/java/com/binance/api/client/domain/OrderStatus.java b/src/main/java/com/binance/api/client/domain/OrderStatus.java old mode 100644 new mode 100755 index 81656c722..7b15e980b --- a/src/main/java/com/binance/api/client/domain/OrderStatus.java +++ b/src/main/java/com/binance/api/client/domain/OrderStatus.java @@ -1,17 +1,17 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Status of a submitted order. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderStatus { - NEW, - PARTIALLY_FILLED, - FILLED, - CANCELED, - PENDING_CANCEL, - REJECTED, - EXPIRED -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a submitted order. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderStatus { + NEW, + PARTIALLY_FILLED, + FILLED, + CANCELED, + PENDING_CANCEL, + REJECTED, + EXPIRED +} diff --git a/src/main/java/com/binance/api/client/domain/OrderType.java b/src/main/java/com/binance/api/client/domain/OrderType.java old mode 100644 new mode 100755 index 11d484e5e..78ee6b6fe --- a/src/main/java/com/binance/api/client/domain/OrderType.java +++ b/src/main/java/com/binance/api/client/domain/OrderType.java @@ -1,17 +1,17 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Type of order to submit to the system. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum OrderType { - LIMIT, - MARKET, - STOP_LOSS, - STOP_LOSS_LIMIT, - TAKE_PROFIT, - TAKE_PROFIT_LIMIT, - LIMIT_MAKER -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Type of order to submit to the system. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum OrderType { + LIMIT, + MARKET, + STOP_LOSS, + STOP_LOSS_LIMIT, + TAKE_PROFIT, + TAKE_PROFIT_LIMIT, + LIMIT_MAKER +} diff --git a/src/main/java/com/binance/api/client/domain/TimeInForce.java b/src/main/java/com/binance/api/client/domain/TimeInForce.java old mode 100644 new mode 100755 index 2d2f50db1..83043ce7f --- a/src/main/java/com/binance/api/client/domain/TimeInForce.java +++ b/src/main/java/com/binance/api/client/domain/TimeInForce.java @@ -1,19 +1,19 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Time in force to indicate how long an order will remain active before it is executed or expires. - * - * GTC (Good-Til-Canceled) orders are effective until they are executed or canceled. - * IOC (Immediate or Cancel) orders fills all or part of an order immediately and cancels the remaining part of the order. - * FOK (Fill or Kill) orders fills all in its entirety, otherwise, the entire order will be cancelled. - * - * @see http://www.investopedia.com/terms/t/timeinforce.asp - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum TimeInForce { - GTC, - IOC, - FOK -} +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Time in force to indicate how long an order will remain active before it is executed or expires. + * + * GTC (Good-Til-Canceled) orders are effective until they are executed or canceled. + * IOC (Immediate or Cancel) orders fills all or part of an order immediately and cancels the remaining part of the order. + * FOK (Fill or Kill) orders fills all in its entirety, otherwise, the entire order will be cancelled. + * + * @see http://www.investopedia.com/terms/t/timeinforce.asp + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum TimeInForce { + GTC, + IOC, + FOK +} diff --git a/src/main/java/com/binance/api/client/domain/TransferType.java b/src/main/java/com/binance/api/client/domain/TransferType.java new file mode 100755 index 000000000..7d39d18a7 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/TransferType.java @@ -0,0 +1,21 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a submitted order. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum TransferType { + SPOT_TO_MARGIN("1"), MARGIN_TO_SPOT("2"); + + private String value; + + TransferType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Account.java b/src/main/java/com/binance/api/client/domain/account/Account.java old mode 100644 new mode 100755 index e14edaeaa..4356bfccb --- a/src/main/java/com/binance/api/client/domain/account/Account.java +++ b/src/main/java/com/binance/api/client/domain/account/Account.java @@ -1,165 +1,165 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Account information. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Account { - - /** - * Maker commission. - */ - private int makerCommission; - - /** - * Taker commission. - */ - private int takerCommission; - - /** - * Buyer commission. - */ - private int buyerCommission; - - /** - * Seller commission. - */ - private int sellerCommission; - - /** - * Whether or not this account can trade. - */ - private boolean canTrade; - - /** - * Whether or not it is possible to withdraw from this account. - */ - private boolean canWithdraw; - - /** - * Whether or not it is possible to deposit into this account. - */ - private boolean canDeposit; - - /** - * Last account update time. - */ - private long updateTime; - - /** - * List of asset balances of this account. - */ - private List balances; - - public int getMakerCommission() { - return makerCommission; - } - - public void setMakerCommission(int makerCommission) { - this.makerCommission = makerCommission; - } - - public int getTakerCommission() { - return takerCommission; - } - - public void setTakerCommission(int takerCommission) { - this.takerCommission = takerCommission; - } - - public int getBuyerCommission() { - return buyerCommission; - } - - public void setBuyerCommission(int buyerCommission) { - this.buyerCommission = buyerCommission; - } - - public int getSellerCommission() { - return sellerCommission; - } - - public void setSellerCommission(int sellerCommission) { - this.sellerCommission = sellerCommission; - } - - public boolean isCanTrade() { - return canTrade; - } - - public void setCanTrade(boolean canTrade) { - this.canTrade = canTrade; - } - - public boolean isCanWithdraw() { - return canWithdraw; - } - - public void setCanWithdraw(boolean canWithdraw) { - this.canWithdraw = canWithdraw; - } - - public boolean isCanDeposit() { - return canDeposit; - } - - public void setCanDeposit(boolean canDeposit) { - this.canDeposit = canDeposit; - } - - public long getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(long updateTime) { - this.updateTime = updateTime; - } - - public List getBalances() { - return balances; - } - - public void setBalances(List balances) { - this.balances = balances; - } - - /** - * Returns the asset balance for a given symbol. - * - * @param symbol asset symbol to obtain the balances from - * @return an asset balance for the given symbol which can be 0 in case the symbol has no balance in the account - */ - public AssetBalance getAssetBalance(String symbol) { - for (AssetBalance assetBalance : balances) { - if (symbol.equals(assetBalance.getAsset())) { - return assetBalance; - } - } - AssetBalance emptyBalance = new AssetBalance(); - emptyBalance.setAsset(symbol); - emptyBalance.setFree("0"); - emptyBalance.setLocked("0"); - return emptyBalance; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("makerCommission", makerCommission) - .append("takerCommission", takerCommission) - .append("buyerCommission", buyerCommission) - .append("sellerCommission", sellerCommission) - .append("canTrade", canTrade) - .append("canWithdraw", canWithdraw) - .append("canDeposit", canDeposit) - .append("updateTime", updateTime) - .append("balances", balances) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Account information. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Account { + + /** + * Maker commission. + */ + private int makerCommission; + + /** + * Taker commission. + */ + private int takerCommission; + + /** + * Buyer commission. + */ + private int buyerCommission; + + /** + * Seller commission. + */ + private int sellerCommission; + + /** + * Whether or not this account can trade. + */ + private boolean canTrade; + + /** + * Whether or not it is possible to withdraw from this account. + */ + private boolean canWithdraw; + + /** + * Whether or not it is possible to deposit into this account. + */ + private boolean canDeposit; + + /** + * Last account update time. + */ + private long updateTime; + + /** + * List of asset balances of this account. + */ + private List balances; + + public int getMakerCommission() { + return makerCommission; + } + + public void setMakerCommission(int makerCommission) { + this.makerCommission = makerCommission; + } + + public int getTakerCommission() { + return takerCommission; + } + + public void setTakerCommission(int takerCommission) { + this.takerCommission = takerCommission; + } + + public int getBuyerCommission() { + return buyerCommission; + } + + public void setBuyerCommission(int buyerCommission) { + this.buyerCommission = buyerCommission; + } + + public int getSellerCommission() { + return sellerCommission; + } + + public void setSellerCommission(int sellerCommission) { + this.sellerCommission = sellerCommission; + } + + public boolean isCanTrade() { + return canTrade; + } + + public void setCanTrade(boolean canTrade) { + this.canTrade = canTrade; + } + + public boolean isCanWithdraw() { + return canWithdraw; + } + + public void setCanWithdraw(boolean canWithdraw) { + this.canWithdraw = canWithdraw; + } + + public boolean isCanDeposit() { + return canDeposit; + } + + public void setCanDeposit(boolean canDeposit) { + this.canDeposit = canDeposit; + } + + public long getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(long updateTime) { + this.updateTime = updateTime; + } + + public List getBalances() { + return balances; + } + + public void setBalances(List balances) { + this.balances = balances; + } + + /** + * Returns the asset balance for a given symbol. + * + * @param symbol asset symbol to obtain the balances from + * @return an asset balance for the given symbol which can be 0 in case the symbol has no balance in the account + */ + public AssetBalance getAssetBalance(String symbol) { + for (AssetBalance assetBalance : balances) { + if (symbol.equals(assetBalance.getAsset())) { + return assetBalance; + } + } + AssetBalance emptyBalance = new AssetBalance(); + emptyBalance.setAsset(symbol); + emptyBalance.setFree("0"); + emptyBalance.setLocked("0"); + return emptyBalance; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("makerCommission", makerCommission) + .append("takerCommission", takerCommission) + .append("buyerCommission", buyerCommission) + .append("sellerCommission", sellerCommission) + .append("canTrade", canTrade) + .append("canWithdraw", canWithdraw) + .append("canDeposit", canDeposit) + .append("updateTime", updateTime) + .append("balances", balances) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/AssetBalance.java b/src/main/java/com/binance/api/client/domain/account/AssetBalance.java old mode 100644 new mode 100755 index 3dae789ec..1d75d6307 --- a/src/main/java/com/binance/api/client/domain/account/AssetBalance.java +++ b/src/main/java/com/binance/api/client/domain/account/AssetBalance.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An asset balance in an Account. - * - * @see Account - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AssetBalance { - - /** - * Asset symbol. - */ - private String asset; - - /** - * Available balance. - */ - private String free; - - /** - * Locked by open orders. - */ - private String locked; - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - public String getFree() { - return free; - } - - public void setFree(String free) { - this.free = free; - } - - public String getLocked() { - return locked; - } - - public void setLocked(String locked) { - this.locked = locked; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("asset", asset) - .append("free", free) - .append("locked", locked) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An asset balance in an Account. + * + * @see Account + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AssetBalance { + + /** + * Asset symbol. + */ + private String asset; + + /** + * Available balance. + */ + private String free; + + /** + * Locked by open orders. + */ + private String locked; + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getFree() { + return free; + } + + public void setFree(String free) { + this.free = free; + } + + public String getLocked() { + return locked; + } + + public void setLocked(String locked) { + this.locked = locked; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("asset", asset) + .append("free", free) + .append("locked", locked) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Deposit.java b/src/main/java/com/binance/api/client/domain/account/Deposit.java old mode 100644 new mode 100755 index 14e8f779f..bfddd85e1 --- a/src/main/java/com/binance/api/client/domain/account/Deposit.java +++ b/src/main/java/com/binance/api/client/domain/account/Deposit.java @@ -1,88 +1,88 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A deposit that was done to a Binance account. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Deposit { - - /** - * Amount deposited. - */ - private String amount; - - /** - * Symbol. - */ - private String asset; - - /** - * Deposit time. - */ - private String insertTime; - - /** - * Transaction id - */ - private String txId; - - /** - * (0:pending,1:success) - */ - private int status; - - public String getAmount() { - return amount; - } - - public void setAmount(String amount) { - this.amount = amount; - } - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - public String getInsertTime() { - return insertTime; - } - - public void setInsertTime(String insertTime) { - this.insertTime = insertTime; - } - - public String getTxId() { - return txId; - } - - public void setTxId(String txId) { - this.txId = txId; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("amount", amount) - .append("asset", asset) - .append("insertTime", insertTime) - .append("txId", txId) - .append("status", status) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A deposit that was done to a Binance account. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Deposit { + + /** + * Amount deposited. + */ + private String amount; + + /** + * Symbol. + */ + private String asset; + + /** + * Deposit time. + */ + private String insertTime; + + /** + * Transaction id + */ + private String txId; + + /** + * (0:pending,1:success) + */ + private int status; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getInsertTime() { + return insertTime; + } + + public void setInsertTime(String insertTime) { + this.insertTime = insertTime; + } + + public String getTxId() { + return txId; + } + + public void setTxId(String txId) { + this.txId = txId; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("amount", amount) + .append("asset", asset) + .append("insertTime", insertTime) + .append("txId", txId) + .append("status", status) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/DepositAddress.java b/src/main/java/com/binance/api/client/domain/account/DepositAddress.java old mode 100644 new mode 100755 index 0aba6dc05..b13eb0dec --- a/src/main/java/com/binance/api/client/domain/account/DepositAddress.java +++ b/src/main/java/com/binance/api/client/domain/account/DepositAddress.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A deposit address for a given asset. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class DepositAddress { - - private String address; - - private boolean success; - - private String addressTag; - - private String asset; - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getAddressTag() { - return addressTag; - } - - public void setAddressTag(String addressTag) { - this.addressTag = addressTag; - } - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("address", address) - .append("success", success) - .append("addressTag", addressTag) - .append("asset", asset) - .toString(); - } +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A deposit address for a given asset. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DepositAddress { + + private String address; + + private boolean success; + + private String addressTag; + + private String asset; + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getAddressTag() { + return addressTag; + } + + public void setAddressTag(String addressTag) { + this.addressTag = addressTag; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("address", address) + .append("success", success) + .append("addressTag", addressTag) + .append("asset", asset) + .toString(); + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/DepositHistory.java b/src/main/java/com/binance/api/client/domain/account/DepositHistory.java old mode 100644 new mode 100755 index 4ac86ee7c..fc8d814e8 --- a/src/main/java/com/binance/api/client/domain/account/DepositHistory.java +++ b/src/main/java/com/binance/api/client/domain/account/DepositHistory.java @@ -1,57 +1,57 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * History of account deposits. - * - * @see Deposit - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class DepositHistory { - - @JsonProperty("depositList") - private List depositList; - - private boolean success; - - private String msg; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public List getDepositList() { - return depositList; - } - - public void setDepositList(List depositList) { - this.depositList = depositList; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("depositList", depositList) - .append("success", success) - .append("msg", msg) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * History of account deposits. + * + * @see Deposit + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DepositHistory { + + @JsonProperty("depositList") + private List depositList; + + private boolean success; + + private String msg; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public List getDepositList() { + return depositList; + } + + public void setDepositList(List depositList) { + this.depositList = depositList; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("depositList", depositList) + .append("success", success) + .append("msg", msg) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Loan.java b/src/main/java/com/binance/api/client/domain/account/Loan.java new file mode 100755 index 000000000..5424c9b17 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Loan.java @@ -0,0 +1,51 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.LoanStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents an executed trade history item. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Loan { + + private String asset; + private String principal; + private long timestamp; + private LoanStatus status; + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getPrincipal() { + return principal; + } + + public void setPrincipal(String principal) { + this.principal = principal; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public LoanStatus getStatus() { + return status; + } + + public void setStatus(LoanStatus status) { + this.status = status; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java b/src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java new file mode 100755 index 000000000..46a696531 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/LoanQueryResult.java @@ -0,0 +1,33 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * History of account withdrawals. + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class LoanQueryResult { + + private int total; + private List rows; + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + public List getRows() { + return rows; + } + + public void setRows(List rows) { + this.rows = rows; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginAccount.java b/src/main/java/com/binance/api/client/domain/account/MarginAccount.java new file mode 100755 index 000000000..86bd64f27 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginAccount.java @@ -0,0 +1,121 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Account information. + */ +@JsonIgnoreProperties +public class MarginAccount { + + private boolean borrowEnabled; + + private String marginLevel; + + private String totalAssetOfBtc; + + private String totalLiabilityOfBtc; + + private String totalNetAssetOfBtc; + + private boolean tradeEnabled; + + private boolean transferEnabled; + + private List userAssets; + + public boolean isBorrowEnabled() { + return borrowEnabled; + } + + public void setBorrowEnabled(boolean borrowEnabled) { + this.borrowEnabled = borrowEnabled; + } + + public String getMarginLevel() { + return marginLevel; + } + + public void setMarginLevel(String marginLevel) { + this.marginLevel = marginLevel; + } + + public String getTotalAssetOfBtc() { + return totalAssetOfBtc; + } + + public void setTotalAssetOfBtc(String totalAssetOfBtc) { + this.totalAssetOfBtc = totalAssetOfBtc; + } + + public String getTotalLiabilityOfBtc() { + return totalLiabilityOfBtc; + } + + public void setTotalLiabilityOfBtc(String totalLiabilityOfBtc) { + this.totalLiabilityOfBtc = totalLiabilityOfBtc; + } + + public String getTotalNetAssetOfBtc() { + return totalNetAssetOfBtc; + } + + public void setTotalNetAssetOfBtc(String totalNetAssetOfBtc) { + this.totalNetAssetOfBtc = totalNetAssetOfBtc; + } + + public boolean isTradeEnabled() { + return tradeEnabled; + } + + public void setTradeEnabled(boolean tradeEnabled) { + this.tradeEnabled = tradeEnabled; + } + + public boolean isTransferEnabled() { + return transferEnabled; + } + + public void setTransferEnabled(boolean transferEnabled) { + this.transferEnabled = transferEnabled; + } + + public List getUserAssets() { + return userAssets; + } + + public void setUserAssets(List userAssets) { + this.userAssets = userAssets; + } + + /** + * Returns the asset balance for a given symbol. + * + * @param symbol asset symbol to obtain the balances from + * @return an asset balance for the given symbol which can be 0 in case the symbol has no balance in the account + */ + public MarginAssetBalance getAssetBalance(final String symbol) { + return userAssets.stream() + .filter(marginAssetBalance -> marginAssetBalance.getAsset().equals(symbol)) + .findFirst() + .orElse(MarginAssetBalance.of(symbol)); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("borrowEnabled", borrowEnabled) + .append("marginLevel", marginLevel) + .append("totalAssetOfBtc", totalAssetOfBtc) + .append("totalLiabilityOfBtc", totalLiabilityOfBtc) + .append("totalNetAssetOfBtc", totalNetAssetOfBtc) + .append("tradeEnabled", tradeEnabled) + .append("transferEnabled", transferEnabled) + .append("userAssets", userAssets) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java b/src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java new file mode 100755 index 000000000..db949e851 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginAssetBalance.java @@ -0,0 +1,103 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An asset balance in an Account. + * + * @see Account + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class MarginAssetBalance { + + public static MarginAssetBalance of(final String asset) { + final MarginAssetBalance marginAssetBalance = new MarginAssetBalance(); + + marginAssetBalance.setAsset(asset); + + return marginAssetBalance; + } + + /** + * Asset symbol. + */ + private String asset; + + private String borrowed = "0"; + + /** + * Available balance. + */ + private String free = "0"; + + private String interest = "0"; + + /** + * Locked by open orders. + */ + private String locked = "0"; + + private String netAsset = "0"; + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getBorrowed() { + return borrowed; + } + + public void setBorrowed(String borrowed) { + this.borrowed = borrowed; + } + + public String getFree() { + return free; + } + + public void setFree(String free) { + this.free = free; + } + + public String getInterest() { + return interest; + } + + public void setInterest(String interest) { + this.interest = interest; + } + + public String getLocked() { + return locked; + } + + public void setLocked(String locked) { + this.locked = locked; + } + + public String getNetAsset() { + return netAsset; + } + + public void setNetAsset(String netAsset) { + this.netAsset = netAsset; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("asset", asset) + .append("borrowed", borrowed) + .append("free", free) + .append("interest", interest) + .append("locked", locked) + .append("netAsset", netAsset) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java b/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java new file mode 100755 index 000000000..116439379 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java @@ -0,0 +1,29 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * MarginTransaction information. + */ +@JsonIgnoreProperties +public class MarginTransaction { + + private String tranId; + + public String getTranId() { + return tranId; + } + + public void setTranId(String tranId) { + this.tranId = tranId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("transactionId", tranId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrder.java b/src/main/java/com/binance/api/client/domain/account/NewOrder.java old mode 100644 new mode 100755 index 221c07d36..19d951b63 --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -1,259 +1,259 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A trade order to enter or exit a position. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class NewOrder { - - /** - * Symbol to place the order on. - */ - private String symbol; - - /** - * Buy/Sell order side. - */ - private OrderSide side; - - /** - * Type of order. - */ - private OrderType type; - - /** - * Time in force to indicate how long will the order remain active. - */ - private TimeInForce timeInForce; - - /** - * Quantity. - */ - private String quantity; - - /** - * Price. - */ - private String price; - - /** - * A unique id for the order. Automatically generated if not sent. - */ - private String newClientOrderId; - - /** - * Used with stop orders. - */ - private String stopPrice; - - /** - * Used with iceberg orders. - */ - private String icebergQty; - - /** - * Set the response JSON. ACK, RESULT, or FULL; default: RESULT. - */ - private NewOrderResponseType newOrderRespType; - - /** - * Receiving window. - */ - private Long recvWindow; - - /** - * Order timestamp. - */ - private long timestamp; - - /** - * Creates a new order with all required parameters. - */ - public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity) { - this.symbol = symbol; - this.side = side; - this.type = type; - this.timeInForce = timeInForce; - this.quantity = quantity; - this.newOrderRespType = NewOrderResponseType.RESULT; - this.timestamp = System.currentTimeMillis(); - this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; - } - - /** - * Creates a new order with all required parameters plus price, which is optional for MARKET orders. - */ - public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity, String price) { - this(symbol, side, type, timeInForce, quantity); - this.price = price; - } - - public String getSymbol() { - return symbol; - } - - public NewOrder symbol(String symbol) { - this.symbol = symbol; - return this; - } - - public OrderSide getSide() { - return side; - } - - public NewOrder side(OrderSide side) { - this.side = side; - return this; - } - - public OrderType getType() { - return type; - } - - public NewOrder type(OrderType type) { - this.type = type; - return this; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public NewOrder timeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - return this; - } - - public String getQuantity() { - return quantity; - } - - public NewOrder quantity(String quantity) { - this.quantity = quantity; - return this; - } - - public String getPrice() { - return price; - } - - public NewOrder price(String price) { - this.price = price; - return this; - } - - public String getNewClientOrderId() { - return newClientOrderId; - } - - public NewOrder newClientOrderId(String newClientOrderId) { - this.newClientOrderId = newClientOrderId; - return this; - } - - public String getStopPrice() { - return stopPrice; - } - - public NewOrder stopPrice(String stopPrice) { - this.stopPrice = stopPrice; - return this; - } - - public String getIcebergQty() { - return icebergQty; - } - - public NewOrder icebergQty(String icebergQty) { - this.icebergQty = icebergQty; - return this; - } - - public NewOrderResponseType getNewOrderRespType() { - return newOrderRespType; - } - - public NewOrder newOrderRespType(NewOrderResponseType newOrderRespType) { - this.newOrderRespType = newOrderRespType; - return this; - } - - public Long getRecvWindow() { - return recvWindow; - } - - public NewOrder recvWindow(Long recvWindow) { - this.recvWindow = recvWindow; - return this; - } - - public long getTimestamp() { - return timestamp; - } - - public NewOrder timestamp(long timestamp) { - this.timestamp = timestamp; - return this; - } - - /** - * Places a MARKET buy order for the given quantity. - * - * @return a new order which is pre-configured with MARKET as the order type and BUY as the order side. - */ - public static NewOrder marketBuy(String symbol, String quantity) { - return new NewOrder(symbol, OrderSide.BUY, OrderType.MARKET, null, quantity); - } - - /** - * Places a MARKET sell order for the given quantity. - * - * @return a new order which is pre-configured with MARKET as the order type and SELL as the order side. - */ - public static NewOrder marketSell(String symbol, String quantity) { - return new NewOrder(symbol, OrderSide.SELL, OrderType.MARKET, null, quantity); - } - - /** - * Places a LIMIT buy order for the given quantity and price. - * - * @return a new order which is pre-configured with LIMIT as the order type and BUY as the order side. - */ - public static NewOrder limitBuy(String symbol, TimeInForce timeInForce, String quantity, String price) { - return new NewOrder(symbol, OrderSide.BUY, OrderType.LIMIT, timeInForce, quantity, price); - } - - /** - * Places a LIMIT sell order for the given quantity and price. - * - * @return a new order which is pre-configured with LIMIT as the order type and SELL as the order side. - */ - public static NewOrder limitSell(String symbol, TimeInForce timeInForce, String quantity, String price) { - return new NewOrder(symbol, OrderSide.SELL, OrderType.LIMIT, timeInForce, quantity, price); - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("side", side) - .append("type", type) - .append("timeInForce", timeInForce) - .append("quantity", quantity) - .append("price", price) - .append("newClientOrderId", newClientOrderId) - .append("stopPrice", stopPrice) - .append("icebergQty", icebergQty) - .append("newOrderRespType", newOrderRespType) - .append("recvWindow", recvWindow) - .append("timestamp", timestamp) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A trade order to enter or exit a position. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOrder { + + /** + * Symbol to place the order on. + */ + private String symbol; + + /** + * Buy/Sell order side. + */ + private OrderSide side; + + /** + * Type of order. + */ + private OrderType type; + + /** + * Time in force to indicate how long will the order remain active. + */ + private TimeInForce timeInForce; + + /** + * Quantity. + */ + private String quantity; + + /** + * Price. + */ + private String price; + + /** + * A unique id for the order. Automatically generated if not sent. + */ + private String newClientOrderId; + + /** + * Used with stop orders. + */ + private String stopPrice; + + /** + * Used with iceberg orders. + */ + private String icebergQty; + + /** + * Set the response JSON. ACK, RESULT, or FULL; default: RESULT. + */ + private NewOrderResponseType newOrderRespType; + + /** + * Receiving window. + */ + private Long recvWindow; + + /** + * Order timestamp. + */ + private long timestamp; + + /** + * Creates a new order with all required parameters. + */ + public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity) { + this.symbol = symbol; + this.side = side; + this.type = type; + this.timeInForce = timeInForce; + this.quantity = quantity; + this.newOrderRespType = NewOrderResponseType.RESULT; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + /** + * Creates a new order with all required parameters plus price, which is optional for MARKET orders. + */ + public NewOrder(String symbol, OrderSide side, OrderType type, TimeInForce timeInForce, String quantity, String price) { + this(symbol, side, type, timeInForce, quantity); + this.price = price; + } + + public String getSymbol() { + return symbol; + } + + public NewOrder symbol(String symbol) { + this.symbol = symbol; + return this; + } + + public OrderSide getSide() { + return side; + } + + public NewOrder side(OrderSide side) { + this.side = side; + return this; + } + + public OrderType getType() { + return type; + } + + public NewOrder type(OrderType type) { + this.type = type; + return this; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public NewOrder timeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + return this; + } + + public String getQuantity() { + return quantity; + } + + public NewOrder quantity(String quantity) { + this.quantity = quantity; + return this; + } + + public String getPrice() { + return price; + } + + public NewOrder price(String price) { + this.price = price; + return this; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public NewOrder newClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + return this; + } + + public String getStopPrice() { + return stopPrice; + } + + public NewOrder stopPrice(String stopPrice) { + this.stopPrice = stopPrice; + return this; + } + + public String getIcebergQty() { + return icebergQty; + } + + public NewOrder icebergQty(String icebergQty) { + this.icebergQty = icebergQty; + return this; + } + + public NewOrderResponseType getNewOrderRespType() { + return newOrderRespType; + } + + public NewOrder newOrderRespType(NewOrderResponseType newOrderRespType) { + this.newOrderRespType = newOrderRespType; + return this; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public NewOrder recvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + return this; + } + + public long getTimestamp() { + return timestamp; + } + + public NewOrder timestamp(long timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Places a MARKET buy order for the given quantity. + * + * @return a new order which is pre-configured with MARKET as the order type and BUY as the order side. + */ + public static NewOrder marketBuy(String symbol, String quantity) { + return new NewOrder(symbol, OrderSide.BUY, OrderType.MARKET, null, quantity); + } + + /** + * Places a MARKET sell order for the given quantity. + * + * @return a new order which is pre-configured with MARKET as the order type and SELL as the order side. + */ + public static NewOrder marketSell(String symbol, String quantity) { + return new NewOrder(symbol, OrderSide.SELL, OrderType.MARKET, null, quantity); + } + + /** + * Places a LIMIT buy order for the given quantity and price. + * + * @return a new order which is pre-configured with LIMIT as the order type and BUY as the order side. + */ + public static NewOrder limitBuy(String symbol, TimeInForce timeInForce, String quantity, String price) { + return new NewOrder(symbol, OrderSide.BUY, OrderType.LIMIT, timeInForce, quantity, price); + } + + /** + * Places a LIMIT sell order for the given quantity and price. + * + * @return a new order which is pre-configured with LIMIT as the order type and SELL as the order side. + */ + public static NewOrder limitSell(String symbol, TimeInForce timeInForce, String quantity, String price) { + return new NewOrder(symbol, OrderSide.SELL, OrderType.LIMIT, timeInForce, quantity, price); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("side", side) + .append("type", type) + .append("timeInForce", timeInForce) + .append("quantity", quantity) + .append("price", price) + .append("newClientOrderId", newClientOrderId) + .append("stopPrice", stopPrice) + .append("icebergQty", icebergQty) + .append("newOrderRespType", newOrderRespType) + .append("recvWindow", recvWindow) + .append("timestamp", timestamp) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java old mode 100644 new mode 100755 index 281e0361e..a1aa9fb12 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponse.java @@ -1,188 +1,188 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -/** - * Response returned when placing a new order on the system. - * - * @see NewOrder for the request - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class NewOrderResponse { - - /** - * Order symbol. - */ - private String symbol; - - /** - * Order id. - */ - private Long orderId; - - /** - * This will be either a generated one, or the newClientOrderId parameter - * which was passed when creating the new order. - */ - private String clientOrderId; - - private String price; - - private String origQty; - - private String executedQty; - - private String cummulativeQuoteQty; - - private OrderStatus status; - - private TimeInForce timeInForce; - - private OrderType type; - - private OrderSide side; - - // @JsonSetter(nulls = Nulls.AS_EMPTY) - private List fills; - - /** - * Transact time for this order. - */ - private Long transactTime; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - - public String getClientOrderId() { - return clientOrderId; - } - - public void setClientOrderId(String clientOrderId) { - this.clientOrderId = clientOrderId; - } - - public Long getTransactTime() { - return transactTime; - } - - public void setTransactTime(Long transactTime) { - this.transactTime = transactTime; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getOrigQty() { - return origQty; - } - - public void setOrigQty(String origQty) { - this.origQty = origQty; - } - - public String getExecutedQty() { - return executedQty; - } - - public void setExecutedQty(String executedQty) { - this.executedQty = executedQty; - } - - public String getCummulativeQuoteQty() { - return cummulativeQuoteQty; - } - - public void setCummulativeQuoteQty(String cummulativeQuoteQty) { - this.cummulativeQuoteQty = cummulativeQuoteQty; - } - - public OrderStatus getStatus() { - return status; - } - - public void setStatus(OrderStatus status) { - this.status = status; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public void setTimeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - } - - public OrderType getType() { - return type; - } - - public void setType(OrderType type) { - this.type = type; - } - - public OrderSide getSide() { - return side; - } - - public void setSide(OrderSide side) { - this.side = side; - } - - public List getFills() { - return fills; - } - - public void setFills(List fills) { - this.fills = fills; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("orderId", orderId) - .append("clientOrderId", clientOrderId) - .append("transactTime", transactTime) - .append("price", price) - .append("origQty", origQty) - .append("executedQty", executedQty) - .append("status", status) - .append("timeInForce", timeInForce) - .append("type", type) - .append("side", side) - .append("fills", Optional.ofNullable(fills).orElse(Collections.emptyList()) - .stream() - .map(Object::toString) - .collect(Collectors.joining(", "))) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * Response returned when placing a new order on the system. + * + * @see NewOrder for the request + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOrderResponse { + + /** + * Order symbol. + */ + private String symbol; + + /** + * Order id. + */ + private Long orderId; + + /** + * This will be either a generated one, or the newClientOrderId parameter + * which was passed when creating the new order. + */ + private String clientOrderId; + + private String price; + + private String origQty; + + private String executedQty; + + private String cummulativeQuoteQty; + + private OrderStatus status; + + private TimeInForce timeInForce; + + private OrderType type; + + private OrderSide side; + + // @JsonSetter(nulls = Nulls.AS_EMPTY) + private List fills; + + /** + * Transact time for this order. + */ + private Long transactTime; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + public Long getTransactTime() { + return transactTime; + } + + public void setTransactTime(Long transactTime) { + this.transactTime = transactTime; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getOrigQty() { + return origQty; + } + + public void setOrigQty(String origQty) { + this.origQty = origQty; + } + + public String getExecutedQty() { + return executedQty; + } + + public void setExecutedQty(String executedQty) { + this.executedQty = executedQty; + } + + public String getCummulativeQuoteQty() { + return cummulativeQuoteQty; + } + + public void setCummulativeQuoteQty(String cummulativeQuoteQty) { + this.cummulativeQuoteQty = cummulativeQuoteQty; + } + + public OrderStatus getStatus() { + return status; + } + + public void setStatus(OrderStatus status) { + this.status = status; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public List getFills() { + return fills; + } + + public void setFills(List fills) { + this.fills = fills; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .append("transactTime", transactTime) + .append("price", price) + .append("origQty", origQty) + .append("executedQty", executedQty) + .append("status", status) + .append("timeInForce", timeInForce) + .append("type", type) + .append("side", side) + .append("fills", Optional.ofNullable(fills).orElse(Collections.emptyList()) + .stream() + .map(Object::toString) + .collect(Collectors.joining(", "))) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java old mode 100644 new mode 100755 index 836a571d5..fe1d00e55 --- a/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrderResponseType.java @@ -1,15 +1,15 @@ -package com.binance.api.client.domain.account; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Desired response type of NewOrder requests. - * @see NewOrderResponse - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum NewOrderResponseType { - ACK, - RESULT, - FULL -} - +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Desired response type of NewOrder requests. + * @see NewOrderResponse + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum NewOrderResponseType { + ACK, + RESULT, + FULL +} + diff --git a/src/main/java/com/binance/api/client/domain/account/Order.java b/src/main/java/com/binance/api/client/domain/account/Order.java old mode 100644 new mode 100755 index 88beb54d7..a5eef58a4 --- a/src/main/java/com/binance/api/client/domain/account/Order.java +++ b/src/main/java/com/binance/api/client/domain/account/Order.java @@ -1,218 +1,218 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Trade order information. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Order { - - /** - * Symbol that the order was put on. - */ - private String symbol; - - /** - * Order id. - */ - private Long orderId; - - /** - * Client order id. - */ - private String clientOrderId; - - /** - * Price. - */ - private String price; - - /** - * Original quantity. - */ - private String origQty; - - /** - * Original quantity. - */ - private String executedQty; - - /** - * Order status. - */ - private OrderStatus status; - - /** - * Time in force to indicate how long will the order remain active. - */ - private TimeInForce timeInForce; - - /** - * Type of order. - */ - private OrderType type; - - /** - * Buy/Sell order side. - */ - private OrderSide side; - - /** - * Used with stop orders. - */ - private String stopPrice; - - /** - * Used with iceberg orders. - */ - private String icebergQty; - - /** - * Order timestamp. - */ - private long time; - - /** - * Used to calculate the average price - */ - private String cummulativeQuoteQty; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - - public String getClientOrderId() { - return clientOrderId; - } - - public void setClientOrderId(String clientOrderId) { - this.clientOrderId = clientOrderId; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getOrigQty() { - return origQty; - } - - public void setOrigQty(String origQty) { - this.origQty = origQty; - } - - public String getExecutedQty() { - return executedQty; - } - - public void setExecutedQty(String executedQty) { - this.executedQty = executedQty; - } - - public OrderStatus getStatus() { - return status; - } - - public void setStatus(OrderStatus status) { - this.status = status; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public void setTimeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - } - - public OrderType getType() { - return type; - } - - public void setType(OrderType type) { - this.type = type; - } - - public OrderSide getSide() { - return side; - } - - public void setSide(OrderSide side) { - this.side = side; - } - - public String getStopPrice() { - return stopPrice; - } - - public void setStopPrice(String stopPrice) { - this.stopPrice = stopPrice; - } - - public String getIcebergQty() { - return icebergQty; - } - - public void setIcebergQty(String icebergQty) { - this.icebergQty = icebergQty; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public String getCummulativeQuoteQty() { - return cummulativeQuoteQty; - } - - public void setCummulativeQuoteQty(String cummulativeQuoteQty) { - this.cummulativeQuoteQty = cummulativeQuoteQty; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("orderId", orderId) - .append("clientOrderId", clientOrderId) - .append("price", price) - .append("origQty", origQty) - .append("executedQty", executedQty) - .append("status", status) - .append("timeInForce", timeInForce) - .append("type", type) - .append("side", side) - .append("stopPrice", stopPrice) - .append("icebergQty", icebergQty) - .append("time", time) - .append("cummulativeQuoteQty", cummulativeQuoteQty) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Trade order information. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Order { + + /** + * Symbol that the order was put on. + */ + private String symbol; + + /** + * Order id. + */ + private Long orderId; + + /** + * Client order id. + */ + private String clientOrderId; + + /** + * Price. + */ + private String price; + + /** + * Original quantity. + */ + private String origQty; + + /** + * Original quantity. + */ + private String executedQty; + + /** + * Order status. + */ + private OrderStatus status; + + /** + * Time in force to indicate how long will the order remain active. + */ + private TimeInForce timeInForce; + + /** + * Type of order. + */ + private OrderType type; + + /** + * Buy/Sell order side. + */ + private OrderSide side; + + /** + * Used with stop orders. + */ + private String stopPrice; + + /** + * Used with iceberg orders. + */ + private String icebergQty; + + /** + * Order timestamp. + */ + private long time; + + /** + * Used to calculate the average price + */ + private String cummulativeQuoteQty; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public void setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getOrigQty() { + return origQty; + } + + public void setOrigQty(String origQty) { + this.origQty = origQty; + } + + public String getExecutedQty() { + return executedQty; + } + + public void setExecutedQty(String executedQty) { + this.executedQty = executedQty; + } + + public OrderStatus getStatus() { + return status; + } + + public void setStatus(OrderStatus status) { + this.status = status; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public String getStopPrice() { + return stopPrice; + } + + public void setStopPrice(String stopPrice) { + this.stopPrice = stopPrice; + } + + public String getIcebergQty() { + return icebergQty; + } + + public void setIcebergQty(String icebergQty) { + this.icebergQty = icebergQty; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public String getCummulativeQuoteQty() { + return cummulativeQuoteQty; + } + + public void setCummulativeQuoteQty(String cummulativeQuoteQty) { + this.cummulativeQuoteQty = cummulativeQuoteQty; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .append("price", price) + .append("origQty", origQty) + .append("executedQty", executedQty) + .append("status", status) + .append("timeInForce", timeInForce) + .append("type", type) + .append("side", side) + .append("stopPrice", stopPrice) + .append("icebergQty", icebergQty) + .append("time", time) + .append("cummulativeQuoteQty", cummulativeQuoteQty) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Trade.java b/src/main/java/com/binance/api/client/domain/account/Trade.java old mode 100644 new mode 100755 index aa38a17b6..903805b28 --- a/src/main/java/com/binance/api/client/domain/account/Trade.java +++ b/src/main/java/com/binance/api/client/domain/account/Trade.java @@ -1,188 +1,188 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents an executed trade. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Trade { - - /** - * Trade id. - */ - private Long id; - - /** - * Price. - */ - private String price; - - /** - * Quantity. - */ - private String qty; - - - /** - * Quote quantity for the trade (price * qty). - */ - private String quoteQty; - - /** - * Commission. - */ - private String commission; - - /** - * Asset on which commission is taken - */ - private String commissionAsset; - - /** - * Trade execution time. - */ - private long time; - - /** - * The symbol of the trade. - */ - private String symbol; - - @JsonProperty("isBuyer") - private boolean buyer; - - @JsonProperty("isMaker") - private boolean maker; - - @JsonProperty("isBestMatch") - private boolean bestMatch; - - private String orderId; - - public Long getId() { - return id; - } - - @JsonSetter("id") - public void setId(Long id) { - this.id = id; - } - - @JsonSetter("tradeId") - public void setTradeId(Long id) { - if (this.id == null) { - setId(id); - } - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQty() { - return qty; - } - - public void setQty(String qty) { - this.qty = qty; - } - - public String getQuoteQty() { - return quoteQty; - } - - public void setQuoteQty(String quoteQty) { - this.quoteQty = quoteQty; - } - - public String getCommission() { - return commission; - } - - public void setCommission(String commission) { - this.commission = commission; - } - - public String getCommissionAsset() { - return commissionAsset; - } - - public void setCommissionAsset(String commissionAsset) { - this.commissionAsset = commissionAsset; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public boolean isBuyer() { - return buyer; - } - - public void setBuyer(boolean buyer) { - this.buyer = buyer; - } - - public boolean isMaker() { - return maker; - } - - public void setMaker(boolean maker) { - this.maker = maker; - } - - public boolean isBestMatch() { - return bestMatch; - } - - public void setBestMatch(boolean bestMatch) { - this.bestMatch = bestMatch; - } - - public String getOrderId() { - return orderId; - } - - public void setOrderId(String orderId) { - this.orderId = orderId; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("id", id) - .append("symbol", symbol) - .append("price", price) - .append("qty", qty) - .append("quoteQty", quoteQty) - .append("commission", commission) - .append("commissionAsset", commissionAsset) - .append("time", time) - .append("buyer", buyer) - .append("maker", maker) - .append("bestMatch", bestMatch) - .append("orderId", orderId) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents an executed trade. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Trade { + + /** + * Trade id. + */ + private Long id; + + /** + * Price. + */ + private String price; + + /** + * Quantity. + */ + private String qty; + + + /** + * Quote quantity for the trade (price * qty). + */ + private String quoteQty; + + /** + * Commission. + */ + private String commission; + + /** + * Asset on which commission is taken + */ + private String commissionAsset; + + /** + * Trade execution time. + */ + private long time; + + /** + * The symbol of the trade. + */ + private String symbol; + + @JsonProperty("isBuyer") + private boolean buyer; + + @JsonProperty("isMaker") + private boolean maker; + + @JsonProperty("isBestMatch") + private boolean bestMatch; + + private String orderId; + + public Long getId() { + return id; + } + + @JsonSetter("id") + public void setId(Long id) { + this.id = id; + } + + @JsonSetter("tradeId") + public void setTradeId(Long id) { + if (this.id == null) { + setId(id); + } + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQty() { + return qty; + } + + public void setQty(String qty) { + this.qty = qty; + } + + public String getQuoteQty() { + return quoteQty; + } + + public void setQuoteQty(String quoteQty) { + this.quoteQty = quoteQty; + } + + public String getCommission() { + return commission; + } + + public void setCommission(String commission) { + this.commission = commission; + } + + public String getCommissionAsset() { + return commissionAsset; + } + + public void setCommissionAsset(String commissionAsset) { + this.commissionAsset = commissionAsset; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public boolean isBuyer() { + return buyer; + } + + public void setBuyer(boolean buyer) { + this.buyer = buyer; + } + + public boolean isMaker() { + return maker; + } + + public void setMaker(boolean maker) { + this.maker = maker; + } + + public boolean isBestMatch() { + return bestMatch; + } + + public void setBestMatch(boolean bestMatch) { + this.bestMatch = bestMatch; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("id", id) + .append("symbol", symbol) + .append("price", price) + .append("qty", qty) + .append("quoteQty", quoteQty) + .append("commission", commission) + .append("commissionAsset", commissionAsset) + .append("time", time) + .append("buyer", buyer) + .append("maker", maker) + .append("bestMatch", bestMatch) + .append("orderId", orderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java b/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java old mode 100644 new mode 100755 index 68d017754..babc10760 --- a/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java +++ b/src/main/java/com/binance/api/client/domain/account/TradeHistoryItem.java @@ -1,104 +1,104 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents an executed trade history item. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class TradeHistoryItem { - /** - * Trade id. - */ - private long id; - - /** - * Price. - */ - private String price; - - /** - * Quantity. - */ - private String qty; - - /** - * Trade execution time. - */ - private long time; - - /** - * Is buyer maker ? - */ - @JsonProperty("isBuyerMaker") - private boolean isBuyerMaker; - - /** - * Is best match ? - */ - @JsonProperty("isBestMatch") - private boolean isBestMatch; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQty() { - return qty; - } - - public void setQty(String qty) { - this.qty = qty; - } - - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; - } - - public boolean isBuyerMaker() { - return isBuyerMaker; - } - - public void setBuyerMaker(boolean buyerMaker) { - isBuyerMaker = buyerMaker; - } - - public boolean isBestMatch() { - return isBestMatch; - } - - public void setBestMatch(boolean bestMatch) { - isBestMatch = bestMatch; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("id", id) - .append("price", price) - .append("qty", qty) - .append("time", time) - .append("isBuyerMaker", isBuyerMaker) - .append("isBestMatch", isBestMatch) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents an executed trade history item. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TradeHistoryItem { + /** + * Trade id. + */ + private long id; + + /** + * Price. + */ + private String price; + + /** + * Quantity. + */ + private String qty; + + /** + * Trade execution time. + */ + private long time; + + /** + * Is buyer maker ? + */ + @JsonProperty("isBuyerMaker") + private boolean isBuyerMaker; + + /** + * Is best match ? + */ + @JsonProperty("isBestMatch") + private boolean isBestMatch; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQty() { + return qty; + } + + public void setQty(String qty) { + this.qty = qty; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public boolean isBuyerMaker() { + return isBuyerMaker; + } + + public void setBuyerMaker(boolean buyerMaker) { + isBuyerMaker = buyerMaker; + } + + public boolean isBestMatch() { + return isBestMatch; + } + + public void setBestMatch(boolean bestMatch) { + isBestMatch = bestMatch; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("id", id) + .append("price", price) + .append("qty", qty) + .append("time", time) + .append("isBuyerMaker", isBuyerMaker) + .append("isBestMatch", isBestMatch) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Withdraw.java b/src/main/java/com/binance/api/client/domain/account/Withdraw.java old mode 100644 new mode 100755 index 9d6858fdd..69635ee99 --- a/src/main/java/com/binance/api/client/domain/account/Withdraw.java +++ b/src/main/java/com/binance/api/client/domain/account/Withdraw.java @@ -1,124 +1,124 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A withdraw that was done to a Binance account. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class Withdraw { - - /** - * Amount withdrawn. - */ - private String amount; - - /** - * Destination address. - */ - private String address; - - /** - * Symbol. - */ - private String asset; - - private String applyTime; - - private String successTime; - - /** - * Transaction id. - */ - private String txId; - - /** - * Id. - */ - private String id; - - /** - * (0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6:Completed) - */ - private int status; - - public String getAmount() { - return amount; - } - - public void setAmount(String amount) { - this.amount = amount; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getAsset() { - return asset; - } - - public void setAsset(String asset) { - this.asset = asset; - } - - public String getApplyTime() { - return applyTime; - } - - public void setApplyTime(String applyTime) { - this.applyTime = applyTime; - } - - public String getSuccessTime() { - return successTime; - } - - public void setSuccessTime(String successTime) { - this.successTime = successTime; - } - - public String getTxId() { - return txId; - } - - public void setTxId(String txId) { - this.txId = txId; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("amount", amount) - .append("address", address) - .append("asset", asset) - .append("applyTime", applyTime) - .append("successTime", successTime) - .append("txId", txId) - .append("id", id) - .append("status", status) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A withdraw that was done to a Binance account. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class Withdraw { + + /** + * Amount withdrawn. + */ + private String amount; + + /** + * Destination address. + */ + private String address; + + /** + * Symbol. + */ + private String asset; + + private String applyTime; + + private String successTime; + + /** + * Transaction id. + */ + private String txId; + + /** + * Id. + */ + private String id; + + /** + * (0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6:Completed) + */ + private int status; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getApplyTime() { + return applyTime; + } + + public void setApplyTime(String applyTime) { + this.applyTime = applyTime; + } + + public String getSuccessTime() { + return successTime; + } + + public void setSuccessTime(String successTime) { + this.successTime = successTime; + } + + public String getTxId() { + return txId; + } + + public void setTxId(String txId) { + this.txId = txId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("amount", amount) + .append("address", address) + .append("asset", asset) + .append("applyTime", applyTime) + .append("successTime", successTime) + .append("txId", txId) + .append("id", id) + .append("status", status) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java b/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java old mode 100644 new mode 100755 index 3a3d50f12..df57f89a5 --- a/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java +++ b/src/main/java/com/binance/api/client/domain/account/WithdrawHistory.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.account; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * History of account withdrawals. - * - * @see Withdraw - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class WithdrawHistory { - - private List withdrawList; - - private boolean success; - - public List getWithdrawList() { - return withdrawList; - } - - public void setWithdrawList(List withdrawList) { - this.withdrawList = withdrawList; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("withdrawList", withdrawList) - .append("success", success) - .toString(); - } -} +package com.binance.api.client.domain.account; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * History of account withdrawals. + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class WithdrawHistory { + + private List withdrawList; + + private boolean success; + + public List getWithdrawList() { + return withdrawList; + } + + public void setWithdrawList(List withdrawList) { + this.withdrawList = withdrawList; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("withdrawList", withdrawList) + .append("success", success) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java b/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java old mode 100644 new mode 100755 index fac00deba..b9ebded80 --- a/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java +++ b/src/main/java/com/binance/api/client/domain/account/WithdrawResult.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.account; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** - * A withdraw result that was done to a Binance account. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class WithdrawResult { - - /** - * Withdraw message. - */ - private String msg; - - /** - * Withdraw success. - */ - private boolean success; - - /** - * Withdraw id. - */ - private String id; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String toString() { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("msg", msg) - .append("success", success) - .append("id", id) - .toString(); - } - - -} +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * A withdraw result that was done to a Binance account. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class WithdrawResult { + + /** + * Withdraw message. + */ + private String msg; + + /** + * Withdraw success. + */ + private boolean success; + + /** + * Withdraw id. + */ + private String id; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + .append("msg", msg) + .append("success", success) + .append("id", id) + .toString(); + } + + +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java b/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java old mode 100644 new mode 100755 index 9a7c455d6..d58fca1da --- a/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/AllOrdersRequest.java @@ -1,47 +1,47 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A specialized order request with additional filters. - */ -public class AllOrdersRequest extends OrderRequest { - - private static final Integer DEFAULT_LIMIT = 500; - - private Long orderId; - - private Integer limit; - - public AllOrdersRequest(String symbol) { - super(symbol); - this.limit = DEFAULT_LIMIT; - } - - public Long getOrderId() { - return orderId; - } - - public AllOrdersRequest orderId(Long orderId) { - this.orderId = orderId; - return this; - } - - public Integer getLimit() { - return limit; - } - - public AllOrdersRequest limit(Integer limit) { - this.limit = limit; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("orderId", orderId) - .append("limit", limit) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A specialized order request with additional filters. + */ +public class AllOrdersRequest extends OrderRequest { + + private static final Integer DEFAULT_LIMIT = 500; + + private Long orderId; + + private Integer limit; + + public AllOrdersRequest(String symbol) { + super(symbol); + this.limit = DEFAULT_LIMIT; + } + + public Long getOrderId() { + return orderId; + } + + public AllOrdersRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + + public Integer getLimit() { + return limit; + } + + public AllOrdersRequest limit(Integer limit) { + this.limit = limit; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderId", orderId) + .append("limit", limit) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java old mode 100644 new mode 100755 index 010e23ef8..2dc89c725 --- a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderRequest.java @@ -1,65 +1,65 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Request object for canceling an order. - */ -public class CancelOrderRequest extends OrderRequest { - - private Long orderId; - - private String origClientOrderId; - - public CancelOrderRequest(String symbol, Long orderId) { - super(symbol); - this.orderId = orderId; - } - - public CancelOrderRequest(String symbol, String origClientOrderId) { - super(symbol); - this.origClientOrderId = origClientOrderId; - } - - /** - * Used to uniquely identify this cancel. Automatically generated by default. - */ - private String newClientOrderId; - - public Long getOrderId() { - return orderId; - } - - public CancelOrderRequest orderId(Long orderId) { - this.orderId = orderId; - return this; - } - - public String getOrigClientOrderId() { - return origClientOrderId; - } - - public CancelOrderRequest origClientOrderId(String origClientOrderId) { - this.origClientOrderId = origClientOrderId; - return this; - } - - public String getNewClientOrderId() { - return newClientOrderId; - } - - public CancelOrderRequest newClientOrderId(String newClientOrderId) { - this.newClientOrderId = newClientOrderId; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("orderId", orderId) - .append("origClientOrderId", origClientOrderId) - .append("newClientOrderId", newClientOrderId) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Request object for canceling an order. + */ +public class CancelOrderRequest extends OrderRequest { + + private Long orderId; + + private String origClientOrderId; + + public CancelOrderRequest(String symbol, Long orderId) { + super(symbol); + this.orderId = orderId; + } + + public CancelOrderRequest(String symbol, String origClientOrderId) { + super(symbol); + this.origClientOrderId = origClientOrderId; + } + + /** + * Used to uniquely identify this cancel. Automatically generated by default. + */ + private String newClientOrderId; + + public Long getOrderId() { + return orderId; + } + + public CancelOrderRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public CancelOrderRequest origClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public CancelOrderRequest newClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderId", orderId) + .append("origClientOrderId", origClientOrderId) + .append("newClientOrderId", newClientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java old mode 100644 new mode 100755 index 7b96a01eb..0399aea2b --- a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java @@ -1,77 +1,77 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Response object returned when an order is canceled. - * - * @see CancelOrderRequest for the request - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class CancelOrderResponse { - - private String symbol; - - private String origClientOrderId; - - private String orderId; - - private String clientOrderId; - - private String status; - private String executedQty; - - public String getSymbol() { - return symbol; - } - - public CancelOrderResponse setSymbol(String symbol) { - this.symbol = symbol; - return this; - } - - public String getOrigClientOrderId() { - return origClientOrderId; - } - - public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { - this.origClientOrderId = origClientOrderId; - return this; - } - - public String getStatus() { - return status; - } - public String getExecutedQty() { - return executedQty; - } - - public String getOrderId() { - return orderId; - } - public CancelOrderResponse setOrderId(String orderId) { - this.orderId = orderId; - return this; - } - - public String getClientOrderId() { - return clientOrderId; - } - - public CancelOrderResponse setClientOrderId(String clientOrderId) { - this.clientOrderId = clientOrderId; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("origClientOrderId", origClientOrderId) - .append("orderId", orderId) - .append("clientOrderId", clientOrderId) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Response object returned when an order is canceled. + * + * @see CancelOrderRequest for the request + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class CancelOrderResponse { + + private String symbol; + + private String origClientOrderId; + + private String orderId; + + private String clientOrderId; + + private String status; + private String executedQty; + + public String getSymbol() { + return symbol; + } + + public CancelOrderResponse setSymbol(String symbol) { + this.symbol = symbol; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + public String getStatus() { + return status; + } + public String getExecutedQty() { + return executedQty; + } + + public String getOrderId() { + return orderId; + } + public CancelOrderResponse setOrderId(String orderId) { + this.orderId = orderId; + return this; + } + + public String getClientOrderId() { + return clientOrderId; + } + + public CancelOrderResponse setClientOrderId(String clientOrderId) { + this.clientOrderId = clientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("origClientOrderId", origClientOrderId) + .append("orderId", orderId) + .append("clientOrderId", clientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java b/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java old mode 100644 new mode 100755 index c890a01d9..cad6033e3 --- a/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/OrderRequest.java @@ -1,55 +1,55 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Base request parameters for order-related methods. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderRequest { - - private final String symbol; - - private Long recvWindow; - - private Long timestamp; - - public OrderRequest(String symbol) { - this.symbol = symbol; - this.timestamp = System.currentTimeMillis(); - this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; - } - - public String getSymbol() { - return symbol; - } - - public Long getRecvWindow() { - return recvWindow; - } - - public OrderRequest recvWindow(Long recvWindow) { - this.recvWindow = recvWindow; - return this; - } - - public Long getTimestamp() { - return timestamp; - } - - public OrderRequest timestamp(Long timestamp) { - this.timestamp = timestamp; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("recvWindow", recvWindow) - .append("timestamp", timestamp) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Base request parameters for order-related methods. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderRequest { + + private final String symbol; + + private Long recvWindow; + + private Long timestamp; + + public OrderRequest(String symbol) { + this.symbol = symbol; + this.timestamp = System.currentTimeMillis(); + this.recvWindow = BinanceApiConstants.DEFAULT_RECEIVING_WINDOW; + } + + public String getSymbol() { + return symbol; + } + + public Long getRecvWindow() { + return recvWindow; + } + + public OrderRequest recvWindow(Long recvWindow) { + this.recvWindow = recvWindow; + return this; + } + + public Long getTimestamp() { + return timestamp; + } + + public OrderRequest timestamp(Long timestamp) { + this.timestamp = timestamp; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("recvWindow", recvWindow) + .append("timestamp", timestamp) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java b/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java old mode 100644 new mode 100755 index 497eed1b2..bde5326d2 --- a/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java +++ b/src/main/java/com/binance/api/client/domain/account/request/OrderStatusRequest.java @@ -1,50 +1,50 @@ -package com.binance.api.client.domain.account.request; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * A specialized order request with additional filters. - */ -public class OrderStatusRequest extends OrderRequest { - - private Long orderId; - - private String origClientOrderId; - - public OrderStatusRequest(String symbol, Long orderId) { - super(symbol); - this.orderId = orderId; - } - - public OrderStatusRequest(String symbol, String origClientOrderId) { - super(symbol); - this.origClientOrderId = origClientOrderId; - } - - public Long getOrderId() { - return orderId; - } - - public OrderStatusRequest orderId(Long orderId) { - this.orderId = orderId; - return this; - } - - public String getOrigClientOrderId() { - return origClientOrderId; - } - - public OrderStatusRequest origClientOrderId(String origClientOrderId) { - this.origClientOrderId = origClientOrderId; - return this; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("orderId", orderId) - .append("origClientOrderId", origClientOrderId) - .toString(); - } -} +package com.binance.api.client.domain.account.request; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A specialized order request with additional filters. + */ +public class OrderStatusRequest extends OrderRequest { + + private Long orderId; + + private String origClientOrderId; + + public OrderStatusRequest(String symbol, Long orderId) { + super(symbol); + this.orderId = orderId; + } + + public OrderStatusRequest(String symbol, String origClientOrderId) { + super(symbol); + this.origClientOrderId = origClientOrderId; + } + + public Long getOrderId() { + return orderId; + } + + public OrderStatusRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + + public String getOrigClientOrderId() { + return origClientOrderId; + } + + public OrderStatusRequest origClientOrderId(String origClientOrderId) { + this.origClientOrderId = origClientOrderId; + return this; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("orderId", orderId) + .append("origClientOrderId", origClientOrderId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java old mode 100644 new mode 100755 index 4deefdbad..e5a28c6e8 --- a/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AccountUpdateEvent.java @@ -1,64 +1,64 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.AssetBalance; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Account update event which will reflect the current position/balances of the account. - * - * This event is embedded as part of a user data update event. - * - * @see UserDataUpdateEvent - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AccountUpdateEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("B") - @JsonDeserialize(contentUsing = AssetBalanceDeserializer.class) - private List balances; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public List getBalances() { - return balances; - } - - public void setBalances(List balances) { - this.balances = balances; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("balances", balances) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.account.AssetBalance; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Account update event which will reflect the current position/balances of the account. + * + * This event is embedded as part of a user data update event. + * + * @see UserDataUpdateEvent + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AccountUpdateEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("B") + @JsonDeserialize(contentUsing = AssetBalanceDeserializer.class) + private List balances; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public List getBalances() { + return balances; + } + + public void setBalances(List balances) { + this.balances = balances; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("balances", balances) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java b/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java old mode 100644 new mode 100755 index 5f608a415..87089cb75 --- a/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AggTradeEvent.java @@ -1,57 +1,57 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.market.AggTrade; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An aggregated trade event for a symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AggTradeEvent extends AggTrade { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("s") - private String symbol; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("aggTrade", super.toString()) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.market.AggTrade; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An aggregated trade event for a symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AggTradeEvent extends AggTrade { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("s") + private String symbol; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("aggTrade", super.toString()) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java b/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java old mode 100644 new mode 100755 index 85a14db29..459157a8b --- a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java @@ -1,294 +1,294 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import org.apache.commons.lang3.builder.ToStringBuilder; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AllMarketTickersEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("s") - private String symbol; - - @JsonProperty("p") - private String priceChange; - - @JsonProperty("P") - private String priceChangePercent; - - @JsonProperty("w") - private String weightedAveragePrice; - - @JsonProperty("x") - private String previousDaysClosePrice; - - @JsonProperty("c") - private String currentDaysClosePrice; - - @JsonProperty("Q") - private String closeTradesQuantity; - - @JsonProperty("b") - private String bestBidPrice; - - @JsonProperty("B") - private String bestBidQuantity; - - @JsonProperty("a") - private String bestAskPrice; - - @JsonProperty("A") - private String bestAskQuantity; - - @JsonProperty("o") - private String openPrice; - - @JsonProperty("h") - private String highPrice; - - @JsonProperty("l") - private String lowPrice; - - @JsonProperty("v") - private String totalTradedBaseAssetVolume; - - @JsonProperty("q") - private String totalTradedQuoteAssetVolume; - - @JsonProperty("O") - private long statisticesOpenTime; - - @JsonProperty("C") - private long statisticesCloseTime; - - @JsonProperty("F") - private long firstTradeId; - - @JsonProperty("L") - private long lastTradeId; - - @JsonProperty("n") - private long totalNumberOfTrades; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getPriceChange() { - return priceChange; - } - - public void setPriceChange(String priceChange) { - this.priceChange = priceChange; - } - - public String getPriceChangePercent() { - return priceChangePercent; - } - - public void setPriceChangePercent(String priceChangePercent) { - this.priceChangePercent = priceChangePercent; - } - - public String getWeightedAveragePrice() { - return weightedAveragePrice; - } - - public void setWeightedAveragePrice(String weightedAveragePrice) { - this.weightedAveragePrice = weightedAveragePrice; - } - - public String getPreviousDaysClosePrice() { - return previousDaysClosePrice; - } - - public void setPreviousDaysClosePrice(String previousDaysClosePrice) { - this.previousDaysClosePrice = previousDaysClosePrice; - } - - public String getCurrentDaysClosePrice() { - return currentDaysClosePrice; - } - - public void setCurrentDaysClosePrice(String currentDaysClosePrice) { - this.currentDaysClosePrice = currentDaysClosePrice; - } - - public String getCloseTradesQuantity() { - return closeTradesQuantity; - } - - public void setCloseTradesQuantity(String closeTradesQuantity) { - this.closeTradesQuantity = closeTradesQuantity; - } - - public String getBestBidPrice() { - return bestBidPrice; - } - - public void setBestBidPrice(String bestBidPrice) { - this.bestBidPrice = bestBidPrice; - } - - public String getBestBidQuantity() { - return bestBidQuantity; - } - - public void setBestBidQuantity(String bestBidQuantity) { - this.bestBidQuantity = bestBidQuantity; - } - - public String getBestAskPrice() { - return bestAskPrice; - } - - public void setBestAskPrice(String bestAskPrice) { - this.bestAskPrice = bestAskPrice; - } - - public String getBestAskQuantity() { - return bestAskQuantity; - } - - public void setBestAskQuantity(String bestAskQuantity) { - this.bestAskQuantity = bestAskQuantity; - } - - public String getOpenPrice() { - return openPrice; - } - - public void setOpenPrice(String openPrice) { - this.openPrice = openPrice; - } - - public String getHighPrice() { - return highPrice; - } - - public void setHighPrice(String highPrice) { - this.highPrice = highPrice; - } - - public String getLowPrice() { - return lowPrice; - } - - public void setLowPrice(String lowPrice) { - this.lowPrice = lowPrice; - } - - public String getTotalTradedBaseAssetVolume() { - return totalTradedBaseAssetVolume; - } - - public void setTotalTradedBaseAssetVolume(String totalTradedBaseAssetVolume) { - this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; - } - - public String getTotalTradedQuoteAssetVolume() { - return totalTradedQuoteAssetVolume; - } - - public void setTotalTradedQuoteAssetVolume(String totalTradedQuoteAssetVolume) { - this.totalTradedQuoteAssetVolume = totalTradedQuoteAssetVolume; - } - - public long getStatisticesOpenTime() { - return statisticesOpenTime; - } - - public void setStatisticesOpenTime(long statisticesOpenTime) { - this.statisticesOpenTime = statisticesOpenTime; - } - - public long getStatisticesCloseTime() { - return statisticesCloseTime; - } - - public void setStatisticesCloseTime(long statisticesCloseTime) { - this.statisticesCloseTime = statisticesCloseTime; - } - - public long getFirstTradeId() { - return firstTradeId; - } - - public void setFirstTradeId(long firstTradeId) { - this.firstTradeId = firstTradeId; - } - - public long getLastTradeId() { - return lastTradeId; - } - - public void setLastTradeId(long lastTradeId) { - this.lastTradeId = lastTradeId; - } - - public long getTotalNumberOfTrades() { - return totalNumberOfTrades; - } - - public void setTotalNumberOfTrades(long totalNumberOfTrades) { - this.totalNumberOfTrades = totalNumberOfTrades; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("priceChange", priceChange) - .append("priceChangePercent", priceChangePercent) - .append("weightedAveragePrice", weightedAveragePrice) - .append("previousDaysClosePrice", previousDaysClosePrice) - .append("currentDaysClosePrice", currentDaysClosePrice) - .append("closeTradesQuantity", closeTradesQuantity) - .append("bestBidPrice", bestBidPrice) - .append("bestBidQuantity", bestBidQuantity) - .append("bestAskPrice", bestAskPrice) - .append("bestAskQuantity", bestAskQuantity) - .append("openPrice", openPrice) - .append("highPrice", highPrice) - .append("lowPrice", lowPrice) - .append("totalTradedBaseAssetVolume", totalTradedBaseAssetVolume) - .append("totalTradedQuoteAssetVolume", totalTradedQuoteAssetVolume) - .append("statisticesOpenTime", statisticesOpenTime) - .append("statisticesCloseTime", statisticesCloseTime) - .append("firstTradeId", firstTradeId) - .append("lastTradeId", lastTradeId) - .append("totalNumberOfTrades", totalNumberOfTrades) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AllMarketTickersEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("p") + private String priceChange; + + @JsonProperty("P") + private String priceChangePercent; + + @JsonProperty("w") + private String weightedAveragePrice; + + @JsonProperty("x") + private String previousDaysClosePrice; + + @JsonProperty("c") + private String currentDaysClosePrice; + + @JsonProperty("Q") + private String closeTradesQuantity; + + @JsonProperty("b") + private String bestBidPrice; + + @JsonProperty("B") + private String bestBidQuantity; + + @JsonProperty("a") + private String bestAskPrice; + + @JsonProperty("A") + private String bestAskQuantity; + + @JsonProperty("o") + private String openPrice; + + @JsonProperty("h") + private String highPrice; + + @JsonProperty("l") + private String lowPrice; + + @JsonProperty("v") + private String totalTradedBaseAssetVolume; + + @JsonProperty("q") + private String totalTradedQuoteAssetVolume; + + @JsonProperty("O") + private long statisticesOpenTime; + + @JsonProperty("C") + private long statisticesCloseTime; + + @JsonProperty("F") + private long firstTradeId; + + @JsonProperty("L") + private long lastTradeId; + + @JsonProperty("n") + private long totalNumberOfTrades; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getPriceChange() { + return priceChange; + } + + public void setPriceChange(String priceChange) { + this.priceChange = priceChange; + } + + public String getPriceChangePercent() { + return priceChangePercent; + } + + public void setPriceChangePercent(String priceChangePercent) { + this.priceChangePercent = priceChangePercent; + } + + public String getWeightedAveragePrice() { + return weightedAveragePrice; + } + + public void setWeightedAveragePrice(String weightedAveragePrice) { + this.weightedAveragePrice = weightedAveragePrice; + } + + public String getPreviousDaysClosePrice() { + return previousDaysClosePrice; + } + + public void setPreviousDaysClosePrice(String previousDaysClosePrice) { + this.previousDaysClosePrice = previousDaysClosePrice; + } + + public String getCurrentDaysClosePrice() { + return currentDaysClosePrice; + } + + public void setCurrentDaysClosePrice(String currentDaysClosePrice) { + this.currentDaysClosePrice = currentDaysClosePrice; + } + + public String getCloseTradesQuantity() { + return closeTradesQuantity; + } + + public void setCloseTradesQuantity(String closeTradesQuantity) { + this.closeTradesQuantity = closeTradesQuantity; + } + + public String getBestBidPrice() { + return bestBidPrice; + } + + public void setBestBidPrice(String bestBidPrice) { + this.bestBidPrice = bestBidPrice; + } + + public String getBestBidQuantity() { + return bestBidQuantity; + } + + public void setBestBidQuantity(String bestBidQuantity) { + this.bestBidQuantity = bestBidQuantity; + } + + public String getBestAskPrice() { + return bestAskPrice; + } + + public void setBestAskPrice(String bestAskPrice) { + this.bestAskPrice = bestAskPrice; + } + + public String getBestAskQuantity() { + return bestAskQuantity; + } + + public void setBestAskQuantity(String bestAskQuantity) { + this.bestAskQuantity = bestAskQuantity; + } + + public String getOpenPrice() { + return openPrice; + } + + public void setOpenPrice(String openPrice) { + this.openPrice = openPrice; + } + + public String getHighPrice() { + return highPrice; + } + + public void setHighPrice(String highPrice) { + this.highPrice = highPrice; + } + + public String getLowPrice() { + return lowPrice; + } + + public void setLowPrice(String lowPrice) { + this.lowPrice = lowPrice; + } + + public String getTotalTradedBaseAssetVolume() { + return totalTradedBaseAssetVolume; + } + + public void setTotalTradedBaseAssetVolume(String totalTradedBaseAssetVolume) { + this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; + } + + public String getTotalTradedQuoteAssetVolume() { + return totalTradedQuoteAssetVolume; + } + + public void setTotalTradedQuoteAssetVolume(String totalTradedQuoteAssetVolume) { + this.totalTradedQuoteAssetVolume = totalTradedQuoteAssetVolume; + } + + public long getStatisticesOpenTime() { + return statisticesOpenTime; + } + + public void setStatisticesOpenTime(long statisticesOpenTime) { + this.statisticesOpenTime = statisticesOpenTime; + } + + public long getStatisticesCloseTime() { + return statisticesCloseTime; + } + + public void setStatisticesCloseTime(long statisticesCloseTime) { + this.statisticesCloseTime = statisticesCloseTime; + } + + public long getFirstTradeId() { + return firstTradeId; + } + + public void setFirstTradeId(long firstTradeId) { + this.firstTradeId = firstTradeId; + } + + public long getLastTradeId() { + return lastTradeId; + } + + public void setLastTradeId(long lastTradeId) { + this.lastTradeId = lastTradeId; + } + + public long getTotalNumberOfTrades() { + return totalNumberOfTrades; + } + + public void setTotalNumberOfTrades(long totalNumberOfTrades) { + this.totalNumberOfTrades = totalNumberOfTrades; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("priceChange", priceChange) + .append("priceChangePercent", priceChangePercent) + .append("weightedAveragePrice", weightedAveragePrice) + .append("previousDaysClosePrice", previousDaysClosePrice) + .append("currentDaysClosePrice", currentDaysClosePrice) + .append("closeTradesQuantity", closeTradesQuantity) + .append("bestBidPrice", bestBidPrice) + .append("bestBidQuantity", bestBidQuantity) + .append("bestAskPrice", bestAskPrice) + .append("bestAskQuantity", bestAskQuantity) + .append("openPrice", openPrice) + .append("highPrice", highPrice) + .append("lowPrice", lowPrice) + .append("totalTradedBaseAssetVolume", totalTradedBaseAssetVolume) + .append("totalTradedQuoteAssetVolume", totalTradedQuoteAssetVolume) + .append("statisticesOpenTime", statisticesOpenTime) + .append("statisticesCloseTime", statisticesCloseTime) + .append("firstTradeId", firstTradeId) + .append("lastTradeId", lastTradeId) + .append("totalNumberOfTrades", totalNumberOfTrades) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java b/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java old mode 100644 new mode 100755 index d54703f71..f8953a4c6 --- a/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/AssetBalanceDeserializer.java @@ -1,32 +1,32 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.domain.account.AssetBalance; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; - -/** - * Custom deserializer for an AssetBalance, since the streaming API returns an object in the format {"a":"symbol","f":"free","l":"locked"}, - * which is different than the format used in the REST API. - */ -public class AssetBalanceDeserializer extends JsonDeserializer { - - @Override - public AssetBalance deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - final String asset = node.get("a").asText(); - final String free = node.get("f").asText(); - final String locked = node.get("l").asText(); - - AssetBalance assetBalance = new AssetBalance(); - assetBalance.setAsset(asset); - assetBalance.setFree(free); - assetBalance.setLocked(locked); - return assetBalance; - } +package com.binance.api.client.domain.event; + +import com.binance.api.client.domain.account.AssetBalance; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; + +/** + * Custom deserializer for an AssetBalance, since the streaming API returns an object in the format {"a":"symbol","f":"free","l":"locked"}, + * which is different than the format used in the REST API. + */ +public class AssetBalanceDeserializer extends JsonDeserializer { + + @Override + public AssetBalance deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + final String asset = node.get("a").asText(); + final String free = node.get("f").asText(); + final String locked = node.get("l").asText(); + + AssetBalance assetBalance = new AssetBalance(); + assetBalance.setAsset(asset); + assetBalance.setFree(free); + assetBalance.setLocked(locked); + return assetBalance; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java b/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java old mode 100644 new mode 100755 index 1019eb6f3..f7c04b3df --- a/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/CandlestickEvent.java @@ -1,221 +1,221 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An interval candlestick for a symbol providing informations on price that can be used to produce candlestick charts. - */ -@JsonDeserialize(using = CandlestickEventDeserializer.class) -@JsonSerialize(using = CandlestickEventSerializer.class) -@JsonIgnoreProperties(ignoreUnknown = true) -public class CandlestickEvent { - - private String eventType; - - private long eventTime; - - private String symbol; - - private Long openTime; - - private String open; - - private String high; - - private String low; - - private String close; - - private String volume; - - private Long closeTime; - - private String intervalId; - - private Long firstTradeId; - - private Long lastTradeId; - - private String quoteAssetVolume; - - private Long numberOfTrades; - - private String takerBuyBaseAssetVolume; - - private String takerBuyQuoteAssetVolume; - - private Boolean isBarFinal; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public Long getOpenTime() { - return openTime; - } - - public void setOpenTime(Long openTime) { - this.openTime = openTime; - } - - public String getOpen() { - return open; - } - - public void setOpen(String open) { - this.open = open; - } - - public String getHigh() { - return high; - } - - public void setHigh(String high) { - this.high = high; - } - - public String getLow() { - return low; - } - - public void setLow(String low) { - this.low = low; - } - - public String getClose() { - return close; - } - - public void setClose(String close) { - this.close = close; - } - - public String getVolume() { - return volume; - } - - public void setVolume(String volume) { - this.volume = volume; - } - - public Long getCloseTime() { - return closeTime; - } - - public void setCloseTime(Long closeTime) { - this.closeTime = closeTime; - } - - public String getIntervalId() { - return intervalId; - } - - public void setIntervalId(String intervalId) { - this.intervalId = intervalId; - } - - public Long getFirstTradeId() { - return firstTradeId; - } - - public void setFirstTradeId(Long firstTradeId) { - this.firstTradeId = firstTradeId; - } - - public Long getLastTradeId() { - return lastTradeId; - } - - public void setLastTradeId(Long lastTradeId) { - this.lastTradeId = lastTradeId; - } - - public String getQuoteAssetVolume() { - return quoteAssetVolume; - } - - public void setQuoteAssetVolume(String quoteAssetVolume) { - this.quoteAssetVolume = quoteAssetVolume; - } - - public Long getNumberOfTrades() { - return numberOfTrades; - } - - public void setNumberOfTrades(Long numberOfTrades) { - this.numberOfTrades = numberOfTrades; - } - - public String getTakerBuyBaseAssetVolume() { - return takerBuyBaseAssetVolume; - } - - public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { - this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; - } - - public String getTakerBuyQuoteAssetVolume() { - return takerBuyQuoteAssetVolume; - } - - public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { - this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; - } - - public Boolean getBarFinal() { - return isBarFinal; - } - - public void setBarFinal(Boolean barFinal) { - isBarFinal = barFinal; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("openTime", openTime) - .append("open", open) - .append("high", high) - .append("low", low) - .append("close", close) - .append("volume", volume) - .append("closeTime", closeTime) - .append("intervalId", intervalId) - .append("firstTradeId", firstTradeId) - .append("lastTradeId", lastTradeId) - .append("quoteAssetVolume", quoteAssetVolume) - .append("numberOfTrades", numberOfTrades) - .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) - .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) - .append("isBarFinal", isBarFinal) - .toString(); - } +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An interval candlestick for a symbol providing informations on price that can be used to produce candlestick charts. + */ +@JsonDeserialize(using = CandlestickEventDeserializer.class) +@JsonSerialize(using = CandlestickEventSerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public class CandlestickEvent { + + private String eventType; + + private long eventTime; + + private String symbol; + + private Long openTime; + + private String open; + + private String high; + + private String low; + + private String close; + + private String volume; + + private Long closeTime; + + private String intervalId; + + private Long firstTradeId; + + private Long lastTradeId; + + private String quoteAssetVolume; + + private Long numberOfTrades; + + private String takerBuyBaseAssetVolume; + + private String takerBuyQuoteAssetVolume; + + private Boolean isBarFinal; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public Long getOpenTime() { + return openTime; + } + + public void setOpenTime(Long openTime) { + this.openTime = openTime; + } + + public String getOpen() { + return open; + } + + public void setOpen(String open) { + this.open = open; + } + + public String getHigh() { + return high; + } + + public void setHigh(String high) { + this.high = high; + } + + public String getLow() { + return low; + } + + public void setLow(String low) { + this.low = low; + } + + public String getClose() { + return close; + } + + public void setClose(String close) { + this.close = close; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public Long getCloseTime() { + return closeTime; + } + + public void setCloseTime(Long closeTime) { + this.closeTime = closeTime; + } + + public String getIntervalId() { + return intervalId; + } + + public void setIntervalId(String intervalId) { + this.intervalId = intervalId; + } + + public Long getFirstTradeId() { + return firstTradeId; + } + + public void setFirstTradeId(Long firstTradeId) { + this.firstTradeId = firstTradeId; + } + + public Long getLastTradeId() { + return lastTradeId; + } + + public void setLastTradeId(Long lastTradeId) { + this.lastTradeId = lastTradeId; + } + + public String getQuoteAssetVolume() { + return quoteAssetVolume; + } + + public void setQuoteAssetVolume(String quoteAssetVolume) { + this.quoteAssetVolume = quoteAssetVolume; + } + + public Long getNumberOfTrades() { + return numberOfTrades; + } + + public void setNumberOfTrades(Long numberOfTrades) { + this.numberOfTrades = numberOfTrades; + } + + public String getTakerBuyBaseAssetVolume() { + return takerBuyBaseAssetVolume; + } + + public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { + this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; + } + + public String getTakerBuyQuoteAssetVolume() { + return takerBuyQuoteAssetVolume; + } + + public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { + this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; + } + + public Boolean getBarFinal() { + return isBarFinal; + } + + public void setBarFinal(Boolean barFinal) { + isBarFinal = barFinal; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("openTime", openTime) + .append("open", open) + .append("high", high) + .append("low", low) + .append("close", close) + .append("volume", volume) + .append("closeTime", closeTime) + .append("intervalId", intervalId) + .append("firstTradeId", firstTradeId) + .append("lastTradeId", lastTradeId) + .append("quoteAssetVolume", quoteAssetVolume) + .append("numberOfTrades", numberOfTrades) + .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) + .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) + .append("isBarFinal", isBarFinal) + .toString(); + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java b/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java old mode 100644 new mode 100755 index b8665e448..7792fc73a --- a/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/CandlestickEventDeserializer.java @@ -1,50 +1,50 @@ -package com.binance.api.client.domain.event; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; - -/** - * Custom deserializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. - * - * @see CandlestickEvent - */ -public class CandlestickEventDeserializer extends JsonDeserializer { - - @Override - public CandlestickEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - - CandlestickEvent candlestickEvent = new CandlestickEvent(); - - // Parse header - candlestickEvent.setEventType(node.get("e").asText()); - candlestickEvent.setEventTime(node.get("E").asLong()); - candlestickEvent.setSymbol(node.get("s").asText()); - - // Parse candlestick data - JsonNode candlestickNode = node.get("k"); - candlestickEvent.setOpenTime(candlestickNode.get("t").asLong()); - candlestickEvent.setCloseTime(candlestickNode.get("T").asLong()); - candlestickEvent.setIntervalId(candlestickNode.get("i").asText()); - candlestickEvent.setFirstTradeId(candlestickNode.get("f").asLong()); - candlestickEvent.setLastTradeId(candlestickNode.get("L").asLong()); - candlestickEvent.setOpen(candlestickNode.get("o").asText()); - candlestickEvent.setClose(candlestickNode.get("c").asText()); - candlestickEvent.setHigh(candlestickNode.get("h").asText()); - candlestickEvent.setLow(candlestickNode.get("l").asText()); - candlestickEvent.setVolume(candlestickNode.get("v").asText()); - candlestickEvent.setNumberOfTrades(candlestickNode.get("n").asLong()); - candlestickEvent.setBarFinal(candlestickNode.get("x").asBoolean()); - candlestickEvent.setQuoteAssetVolume(candlestickNode.get("q").asText()); - candlestickEvent.setTakerBuyBaseAssetVolume(candlestickNode.get("V").asText()); - candlestickEvent.setTakerBuyQuoteAssetVolume(candlestickNode.get("Q").asText()); - - return candlestickEvent; - } +package com.binance.api.client.domain.event; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; + +/** + * Custom deserializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. + * + * @see CandlestickEvent + */ +public class CandlestickEventDeserializer extends JsonDeserializer { + + @Override + public CandlestickEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + + CandlestickEvent candlestickEvent = new CandlestickEvent(); + + // Parse header + candlestickEvent.setEventType(node.get("e").asText()); + candlestickEvent.setEventTime(node.get("E").asLong()); + candlestickEvent.setSymbol(node.get("s").asText()); + + // Parse candlestick data + JsonNode candlestickNode = node.get("k"); + candlestickEvent.setOpenTime(candlestickNode.get("t").asLong()); + candlestickEvent.setCloseTime(candlestickNode.get("T").asLong()); + candlestickEvent.setIntervalId(candlestickNode.get("i").asText()); + candlestickEvent.setFirstTradeId(candlestickNode.get("f").asLong()); + candlestickEvent.setLastTradeId(candlestickNode.get("L").asLong()); + candlestickEvent.setOpen(candlestickNode.get("o").asText()); + candlestickEvent.setClose(candlestickNode.get("c").asText()); + candlestickEvent.setHigh(candlestickNode.get("h").asText()); + candlestickEvent.setLow(candlestickNode.get("l").asText()); + candlestickEvent.setVolume(candlestickNode.get("v").asText()); + candlestickEvent.setNumberOfTrades(candlestickNode.get("n").asLong()); + candlestickEvent.setBarFinal(candlestickNode.get("x").asBoolean()); + candlestickEvent.setQuoteAssetVolume(candlestickNode.get("q").asText()); + candlestickEvent.setTakerBuyBaseAssetVolume(candlestickNode.get("V").asText()); + candlestickEvent.setTakerBuyQuoteAssetVolume(candlestickNode.get("Q").asText()); + + return candlestickEvent; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java b/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java old mode 100644 new mode 100755 index 34f03370e..2ceb99956 --- a/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java +++ b/src/main/java/com/binance/api/client/domain/event/CandlestickEventSerializer.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.event; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.JsonSerializer; - -import java.io.IOException; - -/** - * Custom serializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. - * - * @see CandlestickEvent - */ -public class CandlestickEventSerializer extends JsonSerializer { - - @Override - public void serialize(CandlestickEvent candlestickEvent, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - - // Write header - gen.writeStringField("e", candlestickEvent.getEventType()); - gen.writeNumberField("E", candlestickEvent.getEventTime()); - gen.writeStringField("s", candlestickEvent.getSymbol()); - - // Write candlestick data - gen.writeObjectFieldStart("k"); - gen.writeNumberField("t", candlestickEvent.getOpenTime()); - gen.writeNumberField("T", candlestickEvent.getCloseTime()); - gen.writeStringField("i", candlestickEvent.getIntervalId()); - gen.writeNumberField("f", candlestickEvent.getFirstTradeId()); - gen.writeNumberField("L", candlestickEvent.getLastTradeId()); - gen.writeStringField("o", candlestickEvent.getOpen()); - gen.writeStringField("c", candlestickEvent.getClose()); - gen.writeStringField("h", candlestickEvent.getHigh()); - gen.writeStringField("l", candlestickEvent.getLow()); - gen.writeStringField("v", candlestickEvent.getVolume()); - gen.writeNumberField("n", candlestickEvent.getNumberOfTrades()); - gen.writeBooleanField("x", candlestickEvent.getBarFinal()); - gen.writeStringField("q", candlestickEvent.getQuoteAssetVolume()); - gen.writeStringField("V", candlestickEvent.getTakerBuyBaseAssetVolume()); - gen.writeStringField("Q", candlestickEvent.getTakerBuyQuoteAssetVolume()); - gen.writeEndObject(); - } -} +package com.binance.api.client.domain.event; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.JsonSerializer; + +import java.io.IOException; + +/** + * Custom serializer for a candlestick stream event, since the structure of the candlestick json differ from the one in the REST API. + * + * @see CandlestickEvent + */ +public class CandlestickEventSerializer extends JsonSerializer { + + @Override + public void serialize(CandlestickEvent candlestickEvent, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartObject(); + + // Write header + gen.writeStringField("e", candlestickEvent.getEventType()); + gen.writeNumberField("E", candlestickEvent.getEventTime()); + gen.writeStringField("s", candlestickEvent.getSymbol()); + + // Write candlestick data + gen.writeObjectFieldStart("k"); + gen.writeNumberField("t", candlestickEvent.getOpenTime()); + gen.writeNumberField("T", candlestickEvent.getCloseTime()); + gen.writeStringField("i", candlestickEvent.getIntervalId()); + gen.writeNumberField("f", candlestickEvent.getFirstTradeId()); + gen.writeNumberField("L", candlestickEvent.getLastTradeId()); + gen.writeStringField("o", candlestickEvent.getOpen()); + gen.writeStringField("c", candlestickEvent.getClose()); + gen.writeStringField("h", candlestickEvent.getHigh()); + gen.writeStringField("l", candlestickEvent.getLow()); + gen.writeStringField("v", candlestickEvent.getVolume()); + gen.writeNumberField("n", candlestickEvent.getNumberOfTrades()); + gen.writeBooleanField("x", candlestickEvent.getBarFinal()); + gen.writeStringField("q", candlestickEvent.getQuoteAssetVolume()); + gen.writeStringField("V", candlestickEvent.getTakerBuyBaseAssetVolume()); + gen.writeStringField("Q", candlestickEvent.getTakerBuyQuoteAssetVolume()); + gen.writeEndObject(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/DepthEvent.java b/src/main/java/com/binance/api/client/domain/event/DepthEvent.java old mode 100644 new mode 100755 index 4dfe6a77a..0d24ffcf7 --- a/src/main/java/com/binance/api/client/domain/event/DepthEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/DepthEvent.java @@ -1,131 +1,131 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.market.OrderBookEntry; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Depth delta event for a symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class DepthEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private long eventTime; - - @JsonProperty("s") - private String symbol; - - @JsonProperty("U") - private long firstUpdateId; - - /** - * updateId to sync up with updateid in /api/v1/depth - */ - @JsonProperty("u") - private long finalUpdateId; - - /** - * Bid depth delta. - */ - @JsonProperty("b") - private List bids; - - /** - * Ask depth delta. - */ - @JsonProperty("a") - private List asks; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public long getFirstUpdateId() { - return firstUpdateId; - } - - public void setFirstUpdateId(final long firstUpdateId) { - this.firstUpdateId = firstUpdateId; - } - - public long getFinalUpdateId() { - return finalUpdateId; - } - - public void setFinalUpdateId(long finalUpdateId) { - this.finalUpdateId = finalUpdateId; - } - - /** - * @deprecated Use {@link #getFinalUpdateId} - */ - @Deprecated - public long getUpdateId() { - return finalUpdateId; - } - - /** - * @deprecated Use {@link #setFinalUpdateId} - */ - @Deprecated - public void setUpdateId(long updateId) { - this.finalUpdateId = updateId; - } - - public List getBids() { - return bids; - } - - public void setBids(List bids) { - this.bids = bids; - } - - public List getAsks() { - return asks; - } - - public void setAsks(List asks) { - this.asks = asks; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("firstUpdateId", firstUpdateId) - .append("finalUpdateId", finalUpdateId) - .append("bids", bids) - .append("asks", asks) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.market.OrderBookEntry; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Depth delta event for a symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class DepthEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private long eventTime; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("U") + private long firstUpdateId; + + /** + * updateId to sync up with updateid in /api/v1/depth + */ + @JsonProperty("u") + private long finalUpdateId; + + /** + * Bid depth delta. + */ + @JsonProperty("b") + private List bids; + + /** + * Ask depth delta. + */ + @JsonProperty("a") + private List asks; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public long getFirstUpdateId() { + return firstUpdateId; + } + + public void setFirstUpdateId(final long firstUpdateId) { + this.firstUpdateId = firstUpdateId; + } + + public long getFinalUpdateId() { + return finalUpdateId; + } + + public void setFinalUpdateId(long finalUpdateId) { + this.finalUpdateId = finalUpdateId; + } + + /** + * @deprecated Use {@link #getFinalUpdateId} + */ + @Deprecated + public long getUpdateId() { + return finalUpdateId; + } + + /** + * @deprecated Use {@link #setFinalUpdateId} + */ + @Deprecated + public void setUpdateId(long updateId) { + this.finalUpdateId = updateId; + } + + public List getBids() { + return bids; + } + + public void setBids(List bids) { + this.bids = bids; + } + + public List getAsks() { + return asks; + } + + public void setAsks(List asks) { + this.asks = asks; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("firstUpdateId", firstUpdateId) + .append("finalUpdateId", finalUpdateId) + .append("bids", bids) + .append("asks", asks) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/ListenKey.java b/src/main/java/com/binance/api/client/domain/event/ListenKey.java old mode 100644 new mode 100755 index cfce64396..a5ab73977 --- a/src/main/java/com/binance/api/client/domain/event/ListenKey.java +++ b/src/main/java/com/binance/api/client/domain/event/ListenKey.java @@ -1,25 +1,25 @@ -package com.binance.api.client.domain.event; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Dummy type to wrap a listen key from a server response. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ListenKey { - - private String listenKey; - - public String getListenKey() { - return listenKey; - } - - public void setListenKey(String listenKey) { - this.listenKey = listenKey; - } - - @Override - public String toString() { - return listenKey; - } -} +package com.binance.api.client.domain.event; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Dummy type to wrap a listen key from a server response. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ListenKey { + + private String listenKey; + + public String getListenKey() { + return listenKey; + } + + public void setListenKey(String listenKey) { + this.listenKey = listenKey; + } + + @Override + public String toString() { + return listenKey; + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java old mode 100644 new mode 100755 index cf7ab86e3..4b6c4319e --- a/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/OrderTradeUpdateEvent.java @@ -1,318 +1,318 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.ExecutionType; -import com.binance.api.client.domain.OrderRejectReason; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Order or trade report update event. - * - * This event is embedded as part of a user data update event. - * - * @see UserDataUpdateEvent - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderTradeUpdateEvent { - - @JsonProperty("e") - private String eventType; - - @JsonProperty("E") - private Long eventTime; - - @JsonProperty("s") - private String symbol; - - @JsonProperty("c") - private String newClientOrderId; - - /** - * Buy/Sell order side. - */ - @JsonProperty("S") - private OrderSide side; - - /** - * Type of order. - */ - @JsonProperty("o") - private OrderType type; - - /** - * Time in force to indicate how long will the order remain active. - */ - @JsonProperty("f") - private TimeInForce timeInForce; - - /** - * Original quantity in the order. - */ - @JsonProperty("q") - private String originalQuantity; - - /** - * Price. - */ - @JsonProperty("p") - private String price; - - /** - * Type of execution. - */ - @JsonProperty("x") - private ExecutionType executionType; - - /** - * Status of the order. - */ - @JsonProperty("X") - private OrderStatus orderStatus; - - /** - * Reason why the order was rejected. - */ - @JsonProperty("r") - private OrderRejectReason orderRejectReason; - - /** - * Order id. - */ - @JsonProperty("i") - private Long orderId; - - /** - * Quantity of the last filled trade. - */ - @JsonProperty("l") - private String quantityLastFilledTrade; - - /** - * Accumulated quantity of filled trades on this order. - */ - @JsonProperty("z") - private String accumulatedQuantity; - - /** - * Price of last filled trade. - */ - @JsonProperty("L") - private String priceOfLastFilledTrade; - - /** - * Commission. - */ - @JsonProperty("n") - private String commission; - - /** - * Asset on which commission is taken - */ - @JsonProperty("N") - private String commissionAsset; - - /** - * Order/trade time. - */ - @JsonProperty("T") - private Long orderTradeTime; - - /** - * Trade id. - */ - @JsonProperty("t") - private Long tradeId; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public Long getEventTime() { - return eventTime; - } - - public void setEventTime(Long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getNewClientOrderId() { - return newClientOrderId; - } - - public void setNewClientOrderId(String newClientOrderId) { - this.newClientOrderId = newClientOrderId; - } - - public OrderSide getSide() { - return side; - } - - public void setSide(OrderSide side) { - this.side = side; - } - - public OrderType getType() { - return type; - } - - public void setType(OrderType type) { - this.type = type; - } - - public TimeInForce getTimeInForce() { - return timeInForce; - } - - public void setTimeInForce(TimeInForce timeInForce) { - this.timeInForce = timeInForce; - } - - public String getOriginalQuantity() { - return originalQuantity; - } - - public void setOriginalQuantity(String originalQuantity) { - this.originalQuantity = originalQuantity; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public ExecutionType getExecutionType() { - return executionType; - } - - public void setExecutionType(ExecutionType executionType) { - this.executionType = executionType; - } - - public OrderStatus getOrderStatus() { - return orderStatus; - } - - public void setOrderStatus(OrderStatus orderStatus) { - this.orderStatus = orderStatus; - } - - public OrderRejectReason getOrderRejectReason() { - return orderRejectReason; - } - - public void setOrderRejectReason(OrderRejectReason orderRejectReason) { - this.orderRejectReason = orderRejectReason; - } - - public Long getOrderId() { - return orderId; - } - - public void setOrderId(Long orderId) { - this.orderId = orderId; - } - - public String getQuantityLastFilledTrade() { - return quantityLastFilledTrade; - } - - public void setQuantityLastFilledTrade(String quantityLastFilledTrade) { - this.quantityLastFilledTrade = quantityLastFilledTrade; - } - - public String getAccumulatedQuantity() { - return accumulatedQuantity; - } - - public void setAccumulatedQuantity(String accumulatedQuantity) { - this.accumulatedQuantity = accumulatedQuantity; - } - - public String getPriceOfLastFilledTrade() { - return priceOfLastFilledTrade; - } - - public void setPriceOfLastFilledTrade(String priceOfLastFilledTrade) { - this.priceOfLastFilledTrade = priceOfLastFilledTrade; - } - - public String getCommission() { - return commission; - } - - public void setCommission(String commission) { - this.commission = commission; - } - - public String getCommissionAsset() { - return commissionAsset; - } - - public void setCommissionAsset(String commissionAsset) { - this.commissionAsset = commissionAsset; - } - - public Long getOrderTradeTime() { - return orderTradeTime; - } - - public void setOrderTradeTime(Long orderTradeTime) { - this.orderTradeTime = orderTradeTime; - } - - public Long getTradeId() { - return tradeId; - } - - public void setTradeId(Long tradeId) { - this.tradeId = tradeId; - } - - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("newClientOrderId", newClientOrderId) - .append("side", side) - .append("type", type) - .append("timeInForce", timeInForce) - .append("originalQuantity", originalQuantity) - .append("price", price) - .append("executionType", executionType) - .append("orderStatus", orderStatus) - .append("orderRejectReason", orderRejectReason) - .append("orderId", orderId) - .append("quantityLastFilledTrade", quantityLastFilledTrade) - .append("accumulatedQuantity", accumulatedQuantity) - .append("priceOfLastFilledTrade", priceOfLastFilledTrade) - .append("commission", commission) - .append("commissionAsset", commissionAsset) - .append("orderTradeTime", orderTradeTime) - .append("tradeId", tradeId) - .toString(); - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.ExecutionType; +import com.binance.api.client.domain.OrderRejectReason; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Order or trade report update event. + * + * This event is embedded as part of a user data update event. + * + * @see UserDataUpdateEvent + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderTradeUpdateEvent { + + @JsonProperty("e") + private String eventType; + + @JsonProperty("E") + private Long eventTime; + + @JsonProperty("s") + private String symbol; + + @JsonProperty("c") + private String newClientOrderId; + + /** + * Buy/Sell order side. + */ + @JsonProperty("S") + private OrderSide side; + + /** + * Type of order. + */ + @JsonProperty("o") + private OrderType type; + + /** + * Time in force to indicate how long will the order remain active. + */ + @JsonProperty("f") + private TimeInForce timeInForce; + + /** + * Original quantity in the order. + */ + @JsonProperty("q") + private String originalQuantity; + + /** + * Price. + */ + @JsonProperty("p") + private String price; + + /** + * Type of execution. + */ + @JsonProperty("x") + private ExecutionType executionType; + + /** + * Status of the order. + */ + @JsonProperty("X") + private OrderStatus orderStatus; + + /** + * Reason why the order was rejected. + */ + @JsonProperty("r") + private OrderRejectReason orderRejectReason; + + /** + * Order id. + */ + @JsonProperty("i") + private Long orderId; + + /** + * Quantity of the last filled trade. + */ + @JsonProperty("l") + private String quantityLastFilledTrade; + + /** + * Accumulated quantity of filled trades on this order. + */ + @JsonProperty("z") + private String accumulatedQuantity; + + /** + * Price of last filled trade. + */ + @JsonProperty("L") + private String priceOfLastFilledTrade; + + /** + * Commission. + */ + @JsonProperty("n") + private String commission; + + /** + * Asset on which commission is taken + */ + @JsonProperty("N") + private String commissionAsset; + + /** + * Order/trade time. + */ + @JsonProperty("T") + private Long orderTradeTime; + + /** + * Trade id. + */ + @JsonProperty("t") + private Long tradeId; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public Long getEventTime() { + return eventTime; + } + + public void setEventTime(Long eventTime) { + this.eventTime = eventTime; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getNewClientOrderId() { + return newClientOrderId; + } + + public void setNewClientOrderId(String newClientOrderId) { + this.newClientOrderId = newClientOrderId; + } + + public OrderSide getSide() { + return side; + } + + public void setSide(OrderSide side) { + this.side = side; + } + + public OrderType getType() { + return type; + } + + public void setType(OrderType type) { + this.type = type; + } + + public TimeInForce getTimeInForce() { + return timeInForce; + } + + public void setTimeInForce(TimeInForce timeInForce) { + this.timeInForce = timeInForce; + } + + public String getOriginalQuantity() { + return originalQuantity; + } + + public void setOriginalQuantity(String originalQuantity) { + this.originalQuantity = originalQuantity; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public ExecutionType getExecutionType() { + return executionType; + } + + public void setExecutionType(ExecutionType executionType) { + this.executionType = executionType; + } + + public OrderStatus getOrderStatus() { + return orderStatus; + } + + public void setOrderStatus(OrderStatus orderStatus) { + this.orderStatus = orderStatus; + } + + public OrderRejectReason getOrderRejectReason() { + return orderRejectReason; + } + + public void setOrderRejectReason(OrderRejectReason orderRejectReason) { + this.orderRejectReason = orderRejectReason; + } + + public Long getOrderId() { + return orderId; + } + + public void setOrderId(Long orderId) { + this.orderId = orderId; + } + + public String getQuantityLastFilledTrade() { + return quantityLastFilledTrade; + } + + public void setQuantityLastFilledTrade(String quantityLastFilledTrade) { + this.quantityLastFilledTrade = quantityLastFilledTrade; + } + + public String getAccumulatedQuantity() { + return accumulatedQuantity; + } + + public void setAccumulatedQuantity(String accumulatedQuantity) { + this.accumulatedQuantity = accumulatedQuantity; + } + + public String getPriceOfLastFilledTrade() { + return priceOfLastFilledTrade; + } + + public void setPriceOfLastFilledTrade(String priceOfLastFilledTrade) { + this.priceOfLastFilledTrade = priceOfLastFilledTrade; + } + + public String getCommission() { + return commission; + } + + public void setCommission(String commission) { + this.commission = commission; + } + + public String getCommissionAsset() { + return commissionAsset; + } + + public void setCommissionAsset(String commissionAsset) { + this.commissionAsset = commissionAsset; + } + + public Long getOrderTradeTime() { + return orderTradeTime; + } + + public void setOrderTradeTime(Long orderTradeTime) { + this.orderTradeTime = orderTradeTime; + } + + public Long getTradeId() { + return tradeId; + } + + public void setTradeId(Long tradeId) { + this.tradeId = tradeId; + } + + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime) + .append("symbol", symbol) + .append("newClientOrderId", newClientOrderId) + .append("side", side) + .append("type", type) + .append("timeInForce", timeInForce) + .append("originalQuantity", originalQuantity) + .append("price", price) + .append("executionType", executionType) + .append("orderStatus", orderStatus) + .append("orderRejectReason", orderRejectReason) + .append("orderId", orderId) + .append("quantityLastFilledTrade", quantityLastFilledTrade) + .append("accumulatedQuantity", accumulatedQuantity) + .append("priceOfLastFilledTrade", priceOfLastFilledTrade) + .append("commission", commission) + .append("commissionAsset", commissionAsset) + .append("orderTradeTime", orderTradeTime) + .append("tradeId", tradeId) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java old mode 100644 new mode 100755 index e0cd92bf2..f9d3f7bf9 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java @@ -1,100 +1,100 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * User data update event which can be of two types: - * - * 1) outboundAccountInfo, whenever there is a change in the account (e.g. balance of an asset) - * 2) outboundAccountPosition, the change in account balances caused by an event. - * 3) executionReport, whenever there is a trade or an order - */ -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonDeserialize(using = UserDataUpdateEventDeserializer.class) -public class UserDataUpdateEvent { - - private UserDataUpdateEventType eventType; - - private long eventTime; - - private AccountUpdateEvent accountUpdateEvent; - - private OrderTradeUpdateEvent orderTradeUpdateEvent; - - public UserDataUpdateEventType getEventType() { - return eventType; - } - - public void setEventType(UserDataUpdateEventType eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public AccountUpdateEvent getAccountUpdateEvent() { - return accountUpdateEvent; - } - - public void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { - this.accountUpdateEvent = accountUpdateEvent; - } - - public OrderTradeUpdateEvent getOrderTradeUpdateEvent() { - return orderTradeUpdateEvent; - } - - public void setOrderTradeUpdateEvent(OrderTradeUpdateEvent orderTradeUpdateEvent) { - this.orderTradeUpdateEvent = orderTradeUpdateEvent; - } - - @Override - public String toString() { - ToStringBuilder sb = new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime); - if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { - sb.append("accountUpdateEvent", accountUpdateEvent); - } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { - sb.append("accountPositionUpdateEvent", accountUpdateEvent); - } else { - sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); - } - return sb.toString(); - } - - public enum UserDataUpdateEventType { - ACCOUNT_UPDATE("outboundAccountInfo"), - ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), - ORDER_TRADE_UPDATE("executionReport"); - - private final String eventTypeId; - - UserDataUpdateEventType(String eventTypeId) { - this.eventTypeId = eventTypeId; - } - - public String getEventTypeId() { - return eventTypeId; - } - - public static UserDataUpdateEventType fromEventTypeId(String eventTypeId) { - if (ACCOUNT_UPDATE.eventTypeId.equals(eventTypeId)) { - return ACCOUNT_UPDATE; - } else if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { - return ORDER_TRADE_UPDATE; - } else if (ACCOUNT_POSITION_UPDATE.eventTypeId.equals(eventTypeId)) { - return ACCOUNT_POSITION_UPDATE; - } - throw new IllegalArgumentException("Unrecognized user data update event type id: " + eventTypeId); - } - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * User data update event which can be of two types: + * + * 1) outboundAccountInfo, whenever there is a change in the account (e.g. balance of an asset) + * 2) outboundAccountPosition, the change in account balances caused by an event. + * 3) executionReport, whenever there is a trade or an order + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonDeserialize(using = UserDataUpdateEventDeserializer.class) +public class UserDataUpdateEvent { + + private UserDataUpdateEventType eventType; + + private long eventTime; + + private AccountUpdateEvent accountUpdateEvent; + + private OrderTradeUpdateEvent orderTradeUpdateEvent; + + public UserDataUpdateEventType getEventType() { + return eventType; + } + + public void setEventType(UserDataUpdateEventType eventType) { + this.eventType = eventType; + } + + public long getEventTime() { + return eventTime; + } + + public void setEventTime(long eventTime) { + this.eventTime = eventTime; + } + + public AccountUpdateEvent getAccountUpdateEvent() { + return accountUpdateEvent; + } + + public void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { + this.accountUpdateEvent = accountUpdateEvent; + } + + public OrderTradeUpdateEvent getOrderTradeUpdateEvent() { + return orderTradeUpdateEvent; + } + + public void setOrderTradeUpdateEvent(OrderTradeUpdateEvent orderTradeUpdateEvent) { + this.orderTradeUpdateEvent = orderTradeUpdateEvent; + } + + @Override + public String toString() { + ToStringBuilder sb = new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("eventType", eventType) + .append("eventTime", eventTime); + if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { + sb.append("accountUpdateEvent", accountUpdateEvent); + } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + sb.append("accountPositionUpdateEvent", accountUpdateEvent); + } else { + sb.append("orderTradeUpdateEvent", orderTradeUpdateEvent); + } + return sb.toString(); + } + + public enum UserDataUpdateEventType { + ACCOUNT_UPDATE("outboundAccountInfo"), + ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), + ORDER_TRADE_UPDATE("executionReport"); + + private final String eventTypeId; + + UserDataUpdateEventType(String eventTypeId) { + this.eventTypeId = eventTypeId; + } + + public String getEventTypeId() { + return eventTypeId; + } + + public static UserDataUpdateEventType fromEventTypeId(String eventTypeId) { + if (ACCOUNT_UPDATE.eventTypeId.equals(eventTypeId)) { + return ACCOUNT_UPDATE; + } else if (ORDER_TRADE_UPDATE.eventTypeId.equals(eventTypeId)) { + return ORDER_TRADE_UPDATE; + } else if (ACCOUNT_POSITION_UPDATE.eventTypeId.equals(eventTypeId)) { + return ACCOUNT_POSITION_UPDATE; + } + throw new IllegalArgumentException("Unrecognized user data update event type id: " + eventTypeId); + } + } +} diff --git a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java old mode 100644 new mode 100755 index 8ef548e39..45d4829df --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java @@ -1,60 +1,60 @@ -package com.binance.api.client.domain.event; - -import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; -import com.binance.api.client.exception.BinanceApiException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; - -/** - * Custom deserializer for a User Data stream event, since the API can return two different responses in this stream. - * @see UserDataUpdateEvent - */ -public class UserDataUpdateEventDeserializer extends JsonDeserializer { - - private ObjectMapper mapper; - - @Override - public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - - if (mapper == null){ - mapper = new ObjectMapper(); - } - - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - String json = node.toString(); - - final String eventTypeId = node.get("e").asText(); - final Long eventTime = node.get("E").asLong(); - UserDataUpdateEventType userDataUpdateEventType = UserDataUpdateEventType.fromEventTypeId(eventTypeId); - - UserDataUpdateEvent userDataUpdateEvent = new UserDataUpdateEvent(); - userDataUpdateEvent.setEventType(userDataUpdateEventType); - userDataUpdateEvent.setEventTime(eventTime); - - if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE || - userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { - AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); - userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); - } else { // userDataUpdateEventType == UserDataUpdateEventType.ORDER_TRADE_UPDATE - OrderTradeUpdateEvent orderTradeUpdateEvent = getUserDataUpdateEventDetail(json, OrderTradeUpdateEvent.class, mapper); - userDataUpdateEvent.setOrderTradeUpdateEvent(orderTradeUpdateEvent); - } - - return userDataUpdateEvent; - } - - public T getUserDataUpdateEventDetail(String json, Class clazz, ObjectMapper mapper) { - try { - return mapper.readValue(json, clazz); - } catch (IOException e) { - throw new BinanceApiException(e); - } - } -} +package com.binance.api.client.domain.event; + +import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; +import com.binance.api.client.exception.BinanceApiException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; + +/** + * Custom deserializer for a User Data stream event, since the API can return two different responses in this stream. + * @see UserDataUpdateEvent + */ +public class UserDataUpdateEventDeserializer extends JsonDeserializer { + + private ObjectMapper mapper; + + @Override + public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + + if (mapper == null){ + mapper = new ObjectMapper(); + } + + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + String json = node.toString(); + + final String eventTypeId = node.get("e").asText(); + final Long eventTime = node.get("E").asLong(); + UserDataUpdateEventType userDataUpdateEventType = UserDataUpdateEventType.fromEventTypeId(eventTypeId); + + UserDataUpdateEvent userDataUpdateEvent = new UserDataUpdateEvent(); + userDataUpdateEvent.setEventType(userDataUpdateEventType); + userDataUpdateEvent.setEventTime(eventTime); + + if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE || + userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); + userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); + } else { // userDataUpdateEventType == UserDataUpdateEventType.ORDER_TRADE_UPDATE + OrderTradeUpdateEvent orderTradeUpdateEvent = getUserDataUpdateEventDetail(json, OrderTradeUpdateEvent.class, mapper); + userDataUpdateEvent.setOrderTradeUpdateEvent(orderTradeUpdateEvent); + } + + return userDataUpdateEvent; + } + + public T getUserDataUpdateEventDetail(String json, Class clazz, ObjectMapper mapper) { + try { + return mapper.readValue(json, clazz); + } catch (IOException e) { + throw new BinanceApiException(e); + } + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/Asset.java b/src/main/java/com/binance/api/client/domain/general/Asset.java old mode 100644 new mode 100755 index 4a286acc6..715190f31 --- a/src/main/java/com/binance/api/client/domain/general/Asset.java +++ b/src/main/java/com/binance/api/client/domain/general/Asset.java @@ -1,123 +1,123 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An asset Binance supports. - */ - @JsonIgnoreProperties(ignoreUnknown = true) - public class Asset { - - @JsonProperty("id") - private String id; - - @JsonProperty("assetCode") - private String assetCode; - - @JsonProperty("assetName") - private String assetName; - - @JsonProperty("unit") - private String unit; - - @JsonProperty("transactionFee") - private String transactionFee; - - @JsonProperty("commissionRate") - private String commissionRate; - - @JsonProperty("freeAuditWithdrawAmt") - private String freeAuditWithdrawAmount; - - @JsonProperty("freeUserChargeAmount") - private String freeUserChargeAmount; - - @JsonProperty("minProductWithdraw") - private String minProductWithdraw; - - @JsonProperty("withdrawIntegerMultiple") - private String withdrawIntegerMultiple; - - @JsonProperty("confirmTimes") - private long confirmTimes; - - @JsonProperty("enableWithdraw") - private boolean enableWithdraw; - - @JsonProperty("isLegalMoney") - private boolean isLegalMoney; - - public String getId() { - return id; - } - - public String getAssetCode() { - return assetCode; - } - - public String getAssetName() { - return assetName; - } - - public String getUnit() { - return unit; - } - - public String getTransactionFee() { - return transactionFee; - } - - public String getCommissionRate() { - return commissionRate; - } - - public String getFreeAuditWithdrawAmount() { - return freeAuditWithdrawAmount; - } - - public String getFreeUserChargeAmount() { - return freeUserChargeAmount; - } - - public String minProductWithdraw() { - return minProductWithdraw; - } - - public String getWithdrawIntegerMultiple() { - return withdrawIntegerMultiple; - } - - public long getConfirmTimes() { - return confirmTimes; - } - - public boolean canWithraw() { - return enableWithdraw; - } - - public boolean isLegalMoney() { - return isLegalMoney; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("id", id) - .append("assetCode", assetCode) - .append("assetName", assetName) - .append("unit", unit) - .append("transactionFee", transactionFee) - .append("commissionRate", commissionRate) - .append("freeAuditWithdrawAmount", freeAuditWithdrawAmount) - .append("freeUserChargeAmount", freeUserChargeAmount) - .append("minProductWithdraw", minProductWithdraw) - .append("withdrawIntegerMultiple", withdrawIntegerMultiple) - .append("confirmTimes", confirmTimes) - .append("enableWithdraw", enableWithdraw) - .append("isLegalMoney", isLegalMoney) - .toString(); - } - } +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An asset Binance supports. + */ + @JsonIgnoreProperties(ignoreUnknown = true) + public class Asset { + + @JsonProperty("id") + private String id; + + @JsonProperty("assetCode") + private String assetCode; + + @JsonProperty("assetName") + private String assetName; + + @JsonProperty("unit") + private String unit; + + @JsonProperty("transactionFee") + private String transactionFee; + + @JsonProperty("commissionRate") + private String commissionRate; + + @JsonProperty("freeAuditWithdrawAmt") + private String freeAuditWithdrawAmount; + + @JsonProperty("freeUserChargeAmount") + private String freeUserChargeAmount; + + @JsonProperty("minProductWithdraw") + private String minProductWithdraw; + + @JsonProperty("withdrawIntegerMultiple") + private String withdrawIntegerMultiple; + + @JsonProperty("confirmTimes") + private long confirmTimes; + + @JsonProperty("enableWithdraw") + private boolean enableWithdraw; + + @JsonProperty("isLegalMoney") + private boolean isLegalMoney; + + public String getId() { + return id; + } + + public String getAssetCode() { + return assetCode; + } + + public String getAssetName() { + return assetName; + } + + public String getUnit() { + return unit; + } + + public String getTransactionFee() { + return transactionFee; + } + + public String getCommissionRate() { + return commissionRate; + } + + public String getFreeAuditWithdrawAmount() { + return freeAuditWithdrawAmount; + } + + public String getFreeUserChargeAmount() { + return freeUserChargeAmount; + } + + public String minProductWithdraw() { + return minProductWithdraw; + } + + public String getWithdrawIntegerMultiple() { + return withdrawIntegerMultiple; + } + + public long getConfirmTimes() { + return confirmTimes; + } + + public boolean canWithraw() { + return enableWithdraw; + } + + public boolean isLegalMoney() { + return isLegalMoney; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("id", id) + .append("assetCode", assetCode) + .append("assetName", assetName) + .append("unit", unit) + .append("transactionFee", transactionFee) + .append("commissionRate", commissionRate) + .append("freeAuditWithdrawAmount", freeAuditWithdrawAmount) + .append("freeUserChargeAmount", freeUserChargeAmount) + .append("minProductWithdraw", minProductWithdraw) + .append("withdrawIntegerMultiple", withdrawIntegerMultiple) + .append("confirmTimes", confirmTimes) + .append("enableWithdraw", enableWithdraw) + .append("isLegalMoney", isLegalMoney) + .toString(); + } + } diff --git a/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java b/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java old mode 100644 new mode 100755 index e492111a8..e367deaef --- a/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java +++ b/src/main/java/com/binance/api/client/domain/general/ExchangeFilter.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Exchange Filters define trading rules an exchange. - * - * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on the exchange. Note that both "algo" orders and normal orders are counted for this filter. - * - * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on the exchange. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ExchangeFilter { - - private FilterType filterType; - - private Integer limit; - - public FilterType getFilterType() { - return filterType; - } - - public void setFilterType(FilterType filterType) { - this.filterType = filterType; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("filterType", filterType) - .append("limit", limit) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Exchange Filters define trading rules an exchange. + * + * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on the exchange. Note that both "algo" orders and normal orders are counted for this filter. + * + * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on the exchange. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ExchangeFilter { + + private FilterType filterType; + + private Integer limit; + + public FilterType getFilterType() { + return filterType; + } + + public void setFilterType(FilterType filterType) { + this.filterType = filterType; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("filterType", filterType) + .append("limit", limit) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java b/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java old mode 100644 new mode 100755 index ab88f3c5c..b12c1d20c --- a/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java +++ b/src/main/java/com/binance/api/client/domain/general/ExchangeInfo.java @@ -1,78 +1,78 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.exception.BinanceApiException; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Current exchange trading rules and symbol information. - * https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ExchangeInfo { - - private String timezone; - - private Long serverTime; - - private List rateLimits; - - // private List exchangeFilters; - - private List symbols; - - public String getTimezone() { - return timezone; - } - - public void setTimezone(String timezone) { - this.timezone = timezone; - } - - public Long getServerTime() { - return serverTime; - } - - public void setServerTime(Long serverTime) { - this.serverTime = serverTime; - } - - public List getRateLimits() { - return rateLimits; - } - - public void setRateLimits(List rateLimits) { - this.rateLimits = rateLimits; - } - - public List getSymbols() { - return symbols; - } - - public void setSymbols(List symbols) { - this.symbols = symbols; - } - - /** - * @param symbol the symbol to obtain information for (e.g. ETHBTC) - * @return symbol exchange information - */ - public SymbolInfo getSymbolInfo(String symbol) { - return symbols.stream().filter(symbolInfo -> symbolInfo.getSymbol().equals(symbol)) - .findFirst() - .orElseThrow(() -> new BinanceApiException("Unable to obtain information for symbol " + symbol)); - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("timezone", timezone) - .append("serverTime", serverTime) - .append("rateLimits", rateLimits) - .append("symbols", symbols) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.exception.BinanceApiException; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Current exchange trading rules and symbol information. + * https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ExchangeInfo { + + private String timezone; + + private Long serverTime; + + private List rateLimits; + + // private List exchangeFilters; + + private List symbols; + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public Long getServerTime() { + return serverTime; + } + + public void setServerTime(Long serverTime) { + this.serverTime = serverTime; + } + + public List getRateLimits() { + return rateLimits; + } + + public void setRateLimits(List rateLimits) { + this.rateLimits = rateLimits; + } + + public List getSymbols() { + return symbols; + } + + public void setSymbols(List symbols) { + this.symbols = symbols; + } + + /** + * @param symbol the symbol to obtain information for (e.g. ETHBTC) + * @return symbol exchange information + */ + public SymbolInfo getSymbolInfo(String symbol) { + return symbols.stream().filter(symbolInfo -> symbolInfo.getSymbol().equals(symbol)) + .findFirst() + .orElseThrow(() -> new BinanceApiException("Unable to obtain information for symbol " + symbol)); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("timezone", timezone) + .append("serverTime", serverTime) + .append("rateLimits", rateLimits) + .append("symbols", symbols) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java old mode 100644 new mode 100755 index 1959f8ec5..8dd26c46a --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -1,25 +1,25 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum FilterType { - // Symbol - PRICE_FILTER, - LOT_SIZE, - MIN_NOTIONAL, - MAX_NUM_ORDERS, - MAX_ALGO_ORDERS, - MAX_NUM_ALGO_ORDERS, - ICEBERG_PARTS, - PERCENT_PRICE, - MARKET_LOT_SIZE, - MAX_NUM_ICEBERG_ORDERS, - - // Exchange - EXCHANGE_MAX_NUM_ORDERS, - EXCHANGE_MAX_ALGO_ORDERS -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum FilterType { + // Symbol + PRICE_FILTER, + LOT_SIZE, + MIN_NOTIONAL, + MAX_NUM_ORDERS, + MAX_ALGO_ORDERS, + MAX_NUM_ALGO_ORDERS, + ICEBERG_PARTS, + PERCENT_PRICE, + MARKET_LOT_SIZE, + MAX_NUM_ICEBERG_ORDERS, + + // Exchange + EXCHANGE_MAX_NUM_ORDERS, + EXCHANGE_MAX_ALGO_ORDERS +} diff --git a/src/main/java/com/binance/api/client/domain/general/RateLimit.java b/src/main/java/com/binance/api/client/domain/general/RateLimit.java old mode 100644 new mode 100755 index e8d963c33..253f4e36a --- a/src/main/java/com/binance/api/client/domain/general/RateLimit.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimit.java @@ -1,51 +1,51 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Rate limits. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class RateLimit { - - private RateLimitType rateLimitType; - - private RateLimitInterval interval; - - private Integer limit; - - public RateLimitType getRateLimitType() { - return rateLimitType; - } - - public void setRateLimitType(RateLimitType rateLimitType) { - this.rateLimitType = rateLimitType; - } - - public RateLimitInterval getInterval() { - return interval; - } - - public void setInterval(RateLimitInterval interval) { - this.interval = interval; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("rateLimitType", rateLimitType) - .append("interval", interval) - .append("limit", limit) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Rate limits. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class RateLimit { + + private RateLimitType rateLimitType; + + private RateLimitInterval interval; + + private Integer limit; + + public RateLimitType getRateLimitType() { + return rateLimitType; + } + + public void setRateLimitType(RateLimitType rateLimitType) { + this.rateLimitType = rateLimitType; + } + + public RateLimitInterval getInterval() { + return interval; + } + + public void setInterval(RateLimitInterval interval) { + this.interval = interval; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("rateLimitType", rateLimitType) + .append("interval", interval) + .append("limit", limit) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java b/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java old mode 100644 new mode 100755 index 0c8f65fca..30edd34a4 --- a/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimitInterval.java @@ -1,13 +1,13 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Rate limit intervals. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum RateLimitInterval { - SECOND, - MINUTE, - DAY +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Rate limit intervals. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum RateLimitInterval { + SECOND, + MINUTE, + DAY } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/general/RateLimitType.java b/src/main/java/com/binance/api/client/domain/general/RateLimitType.java old mode 100644 new mode 100755 index db43d5d39..25775dab5 --- a/src/main/java/com/binance/api/client/domain/general/RateLimitType.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimitType.java @@ -1,12 +1,12 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Rate limiters. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum RateLimitType { - REQUEST_WEIGHT, - ORDERS -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Rate limiters. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum RateLimitType { + REQUEST_WEIGHT, + ORDERS +} diff --git a/src/main/java/com/binance/api/client/domain/general/ServerTime.java b/src/main/java/com/binance/api/client/domain/general/ServerTime.java old mode 100644 new mode 100755 index ec4880313..828ea342b --- a/src/main/java/com/binance/api/client/domain/general/ServerTime.java +++ b/src/main/java/com/binance/api/client/domain/general/ServerTime.java @@ -1,24 +1,24 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Time of the server running Binance's REST API. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ServerTime { - private Long serverTime; - - public Long getServerTime() { - return serverTime; - } - - public void setServerTime(Long serverTime) { - this.serverTime = serverTime; - } - - @Override - public String toString() { - return String.valueOf(serverTime); - } -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Time of the server running Binance's REST API. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServerTime { + private Long serverTime; + + public Long getServerTime() { + return serverTime; + } + + public void setServerTime(Long serverTime) { + this.serverTime = serverTime; + } + + @Override + public String toString() { + return String.valueOf(serverTime); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java b/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java old mode 100644 new mode 100755 index 068e0ba28..e6a8b98c8 --- a/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolFilter.java @@ -1,160 +1,160 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. - * - * The PRICE_FILTER defines the price rules for a symbol. - * - * The LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for a symbol. - * - * The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. - * - * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. - * - * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class SymbolFilter { - - // PRICE_FILTER - - private FilterType filterType; - - /** - * Defines the minimum price/stopPrice allowed. - */ - private String minPrice; - - /** - * Defines the maximum price/stopPrice allowed. - */ - private String maxPrice; - - /** - * Defines the intervals that a price/stopPrice can be increased/decreased by. - */ - private String tickSize; - - - // LOT_SIZE - - /** - * Defines the minimum quantity/icebergQty allowed. - */ - private String minQty; - - /** - * Defines the maximum quantity/icebergQty allowed. - */ - private String maxQty; - - /** - * Defines the intervals that a quantity/icebergQty can be increased/decreased by. - */ - private String stepSize; - - // MIN_NOTIONAL - - /** - * Defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. - */ - private String minNotional; - - - // MAX_NUM_ALGO_ORDERS - - /** - * Defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - */ - private String maxNumAlgoOrders; - - /** - * MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. - * MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. - * ICEBERG_PARTS filter defines the maximum parts an iceberg order can have. The number of ICEBERG_PARTS is defined as CEIL(qty / icebergQty). - */ - private String limit; - - public FilterType getFilterType() { - return filterType; - } - - public void setFilterType(FilterType filterType) { - this.filterType = filterType; - } - - public String getMinPrice() { - return minPrice; - } - - public void setMinPrice(String minPrice) { - this.minPrice = minPrice; - } - - public String getMaxPrice() { - return maxPrice; - } - - public void setMaxPrice(String maxPrice) { - this.maxPrice = maxPrice; - } - - public String getTickSize() { - return tickSize; - } - - public void setTickSize(String tickSize) { - this.tickSize = tickSize; - } - - public String getMinQty() { - return minQty; - } - - public void setMinQty(String minQty) { - this.minQty = minQty; - } - - public String getMaxQty() { - return maxQty; - } - - public void setMaxQty(String maxQty) { - this.maxQty = maxQty; - } - - public String getStepSize() { - return stepSize; - } - - public void setStepSize(String stepSize) { - this.stepSize = stepSize; - } - - public String getMinNotional() { - return minNotional; - } - - public void setMinNotional(String minNotional) { - this.minNotional = minNotional; - } - - public String getMaxNumAlgoOrders() { - return maxNumAlgoOrders; - } - - public SymbolFilter setMaxNumAlgoOrders(String maxNumAlgoOrders) { - this.maxNumAlgoOrders = maxNumAlgoOrders; - return this; - } - - public String getLimit() { - return limit; - } - - public void setLimit(String limit) { - this.limit = limit; - } -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Filters define trading rules on a symbol or an exchange. Filters come in two forms: symbol filters and exchange filters. + * + * The PRICE_FILTER defines the price rules for a symbol. + * + * The LOT_SIZE filter defines the quantity (aka "lots" in auction terms) rules for a symbol. + * + * The MIN_NOTIONAL filter defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. + * + * The MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. + * + * The MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class SymbolFilter { + + // PRICE_FILTER + + private FilterType filterType; + + /** + * Defines the minimum price/stopPrice allowed. + */ + private String minPrice; + + /** + * Defines the maximum price/stopPrice allowed. + */ + private String maxPrice; + + /** + * Defines the intervals that a price/stopPrice can be increased/decreased by. + */ + private String tickSize; + + + // LOT_SIZE + + /** + * Defines the minimum quantity/icebergQty allowed. + */ + private String minQty; + + /** + * Defines the maximum quantity/icebergQty allowed. + */ + private String maxQty; + + /** + * Defines the intervals that a quantity/icebergQty can be increased/decreased by. + */ + private String stepSize; + + // MIN_NOTIONAL + + /** + * Defines the minimum notional value allowed for an order on a symbol. An order's notional value is the price * quantity. + */ + private String minNotional; + + + // MAX_NUM_ALGO_ORDERS + + /** + * Defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + */ + private String maxNumAlgoOrders; + + /** + * MAX_NUM_ORDERS filter defines the maximum number of orders an account is allowed to have open on a symbol. Note that both "algo" orders and normal orders are counted for this filter. + * MAX_ALGO_ORDERS filter defines the maximum number of "algo" orders an account is allowed to have open on a symbol. "Algo" orders are STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders. + * ICEBERG_PARTS filter defines the maximum parts an iceberg order can have. The number of ICEBERG_PARTS is defined as CEIL(qty / icebergQty). + */ + private String limit; + + public FilterType getFilterType() { + return filterType; + } + + public void setFilterType(FilterType filterType) { + this.filterType = filterType; + } + + public String getMinPrice() { + return minPrice; + } + + public void setMinPrice(String minPrice) { + this.minPrice = minPrice; + } + + public String getMaxPrice() { + return maxPrice; + } + + public void setMaxPrice(String maxPrice) { + this.maxPrice = maxPrice; + } + + public String getTickSize() { + return tickSize; + } + + public void setTickSize(String tickSize) { + this.tickSize = tickSize; + } + + public String getMinQty() { + return minQty; + } + + public void setMinQty(String minQty) { + this.minQty = minQty; + } + + public String getMaxQty() { + return maxQty; + } + + public void setMaxQty(String maxQty) { + this.maxQty = maxQty; + } + + public String getStepSize() { + return stepSize; + } + + public void setStepSize(String stepSize) { + this.stepSize = stepSize; + } + + public String getMinNotional() { + return minNotional; + } + + public void setMinNotional(String minNotional) { + this.minNotional = minNotional; + } + + public String getMaxNumAlgoOrders() { + return maxNumAlgoOrders; + } + + public SymbolFilter setMaxNumAlgoOrders(String maxNumAlgoOrders) { + this.maxNumAlgoOrders = maxNumAlgoOrders; + return this; + } + + public String getLimit() { + return limit; + } + + public void setLimit(String limit) { + this.limit = limit; + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java b/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java old mode 100644 new mode 100755 index 7eed2e97c..72bca07e3 --- a/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java @@ -1,131 +1,131 @@ -package com.binance.api.client.domain.general; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderType; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Symbol information (base/quote). - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class SymbolInfo { - - private String symbol; - - private SymbolStatus status; - - private String baseAsset; - - private Integer baseAssetPrecision; - - private String quoteAsset; - - private Integer quotePrecision; - - private List orderTypes; - - private boolean icebergAllowed; - - private List filters; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public SymbolStatus getStatus() { - return status; - } - - public void setStatus(SymbolStatus status) { - this.status = status; - } - - public String getBaseAsset() { - return baseAsset; - } - - public void setBaseAsset(String baseAsset) { - this.baseAsset = baseAsset; - } - - public Integer getBaseAssetPrecision() { - return baseAssetPrecision; - } - - public void setBaseAssetPrecision(Integer baseAssetPrecision) { - this.baseAssetPrecision = baseAssetPrecision; - } - - public String getQuoteAsset() { - return quoteAsset; - } - - public void setQuoteAsset(String quoteAsset) { - this.quoteAsset = quoteAsset; - } - - public Integer getQuotePrecision() { - return quotePrecision; - } - - public void setQuotePrecision(Integer quotePrecision) { - this.quotePrecision = quotePrecision; - } - - public List getOrderTypes() { - return orderTypes; - } - - public void setOrderTypes(List orderTypes) { - this.orderTypes = orderTypes; - } - - public boolean isIcebergAllowed() { - return icebergAllowed; - } - - public void setIcebergAllowed(boolean icebergAllowed) { - this.icebergAllowed = icebergAllowed; - } - - public List getFilters() { - return filters; - } - - public void setFilters(List filters) { - this.filters = filters; - } - - /** - * @param filterType filter type to filter for. - * @return symbol filter information for the provided filter type. - */ - public SymbolFilter getSymbolFilter(FilterType filterType) { - return filters.stream() - .filter(symbolFilter -> symbolFilter.getFilterType() == filterType) - .findFirst() - .get(); - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("status", status) - .append("baseAsset", baseAsset) - .append("baseAssetPrecision", baseAssetPrecision) - .append("quoteAsset", quoteAsset) - .append("quotePrecision", quotePrecision) - .append("orderTypes", orderTypes) - .append("icebergAllowed", icebergAllowed) - .append("filters", filters) - .toString(); - } -} +package com.binance.api.client.domain.general; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderType; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Symbol information (base/quote). + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class SymbolInfo { + + private String symbol; + + private SymbolStatus status; + + private String baseAsset; + + private Integer baseAssetPrecision; + + private String quoteAsset; + + private Integer quotePrecision; + + private List orderTypes; + + private boolean icebergAllowed; + + private List filters; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public SymbolStatus getStatus() { + return status; + } + + public void setStatus(SymbolStatus status) { + this.status = status; + } + + public String getBaseAsset() { + return baseAsset; + } + + public void setBaseAsset(String baseAsset) { + this.baseAsset = baseAsset; + } + + public Integer getBaseAssetPrecision() { + return baseAssetPrecision; + } + + public void setBaseAssetPrecision(Integer baseAssetPrecision) { + this.baseAssetPrecision = baseAssetPrecision; + } + + public String getQuoteAsset() { + return quoteAsset; + } + + public void setQuoteAsset(String quoteAsset) { + this.quoteAsset = quoteAsset; + } + + public Integer getQuotePrecision() { + return quotePrecision; + } + + public void setQuotePrecision(Integer quotePrecision) { + this.quotePrecision = quotePrecision; + } + + public List getOrderTypes() { + return orderTypes; + } + + public void setOrderTypes(List orderTypes) { + this.orderTypes = orderTypes; + } + + public boolean isIcebergAllowed() { + return icebergAllowed; + } + + public void setIcebergAllowed(boolean icebergAllowed) { + this.icebergAllowed = icebergAllowed; + } + + public List getFilters() { + return filters; + } + + public void setFilters(List filters) { + this.filters = filters; + } + + /** + * @param filterType filter type to filter for. + * @return symbol filter information for the provided filter type. + */ + public SymbolFilter getSymbolFilter(FilterType filterType) { + return filters.stream() + .filter(symbolFilter -> symbolFilter.getFilterType() == filterType) + .findFirst() + .get(); + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("status", status) + .append("baseAsset", baseAsset) + .append("baseAssetPrecision", baseAssetPrecision) + .append("quoteAsset", quoteAsset) + .append("quotePrecision", quotePrecision) + .append("orderTypes", orderTypes) + .append("icebergAllowed", icebergAllowed) + .append("filters", filters) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java b/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java old mode 100644 new mode 100755 index c12647540..77291ee77 --- a/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolStatus.java @@ -1,17 +1,17 @@ -package com.binance.api.client.domain.general; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Status of a symbol on the exchange. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum SymbolStatus { - PRE_TRADING, - TRADING, - POST_TRADING, - END_OF_DAY, - HALT, - AUCTION_MATCH, - BREAK; -} +package com.binance.api.client.domain.general; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Status of a symbol on the exchange. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SymbolStatus { + PRE_TRADING, + TRADING, + POST_TRADING, + END_OF_DAY, + HALT, + AUCTION_MATCH, + BREAK; +} diff --git a/src/main/java/com/binance/api/client/domain/market/AggTrade.java b/src/main/java/com/binance/api/client/domain/market/AggTrade.java old mode 100644 new mode 100755 index 75d8c0d23..65d135af6 --- a/src/main/java/com/binance/api/client/domain/market/AggTrade.java +++ b/src/main/java/com/binance/api/client/domain/market/AggTrade.java @@ -1,103 +1,103 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An aggregated trade event for a symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class AggTrade { - - @JsonProperty("a") - private long aggregatedTradeId; - - @JsonProperty("p") - private String price; - - @JsonProperty("q") - private String quantity; - - @JsonProperty("f") - private long firstBreakdownTradeId; - - @JsonProperty("l") - private long lastBreakdownTradeId; - - @JsonProperty("T") - private long tradeTime; - - @JsonProperty("m") - private boolean isBuyerMaker; - - public long getAggregatedTradeId() { - return aggregatedTradeId; - } - - public void setAggregatedTradeId(long aggregatedTradeId) { - this.aggregatedTradeId = aggregatedTradeId; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQuantity() { - return quantity; - } - - public void setQuantity(String quantity) { - this.quantity = quantity; - } - - public long getFirstBreakdownTradeId() { - return firstBreakdownTradeId; - } - - public void setFirstBreakdownTradeId(long firstBreakdownTradeId) { - this.firstBreakdownTradeId = firstBreakdownTradeId; - } - - public long getLastBreakdownTradeId() { - return lastBreakdownTradeId; - } - - public void setLastBreakdownTradeId(long lastBreakdownTradeId) { - this.lastBreakdownTradeId = lastBreakdownTradeId; - } - - public long getTradeTime() { - return tradeTime; - } - - public void setTradeTime(long tradeTime) { - this.tradeTime = tradeTime; - } - - public boolean isBuyerMaker() { - return isBuyerMaker; - } - - public void setBuyerMaker(boolean buyerMaker) { - isBuyerMaker = buyerMaker; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("aggregatedTradeId", aggregatedTradeId) - .append("price", price) - .append("quantity", quantity) - .append("firstBreakdownTradeId", firstBreakdownTradeId) - .append("lastBreakdownTradeId", lastBreakdownTradeId) - .append("tradeTime", tradeTime) - .append("isBuyerMaker", isBuyerMaker) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An aggregated trade event for a symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class AggTrade { + + @JsonProperty("a") + private long aggregatedTradeId; + + @JsonProperty("p") + private String price; + + @JsonProperty("q") + private String quantity; + + @JsonProperty("f") + private long firstBreakdownTradeId; + + @JsonProperty("l") + private long lastBreakdownTradeId; + + @JsonProperty("T") + private long tradeTime; + + @JsonProperty("m") + private boolean isBuyerMaker; + + public long getAggregatedTradeId() { + return aggregatedTradeId; + } + + public void setAggregatedTradeId(long aggregatedTradeId) { + this.aggregatedTradeId = aggregatedTradeId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQuantity() { + return quantity; + } + + public void setQuantity(String quantity) { + this.quantity = quantity; + } + + public long getFirstBreakdownTradeId() { + return firstBreakdownTradeId; + } + + public void setFirstBreakdownTradeId(long firstBreakdownTradeId) { + this.firstBreakdownTradeId = firstBreakdownTradeId; + } + + public long getLastBreakdownTradeId() { + return lastBreakdownTradeId; + } + + public void setLastBreakdownTradeId(long lastBreakdownTradeId) { + this.lastBreakdownTradeId = lastBreakdownTradeId; + } + + public long getTradeTime() { + return tradeTime; + } + + public void setTradeTime(long tradeTime) { + this.tradeTime = tradeTime; + } + + public boolean isBuyerMaker() { + return isBuyerMaker; + } + + public void setBuyerMaker(boolean buyerMaker) { + isBuyerMaker = buyerMaker; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("aggregatedTradeId", aggregatedTradeId) + .append("price", price) + .append("quantity", quantity) + .append("firstBreakdownTradeId", firstBreakdownTradeId) + .append("lastBreakdownTradeId", lastBreakdownTradeId) + .append("tradeTime", tradeTime) + .append("isBuyerMaker", isBuyerMaker) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/BookTicker.java b/src/main/java/com/binance/api/client/domain/market/BookTicker.java old mode 100644 new mode 100755 index 67b007ea8..94b5c7989 --- a/src/main/java/com/binance/api/client/domain/market/BookTicker.java +++ b/src/main/java/com/binance/api/client/domain/market/BookTicker.java @@ -1,88 +1,88 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Represents the best price/qty on the order book for a given symbol. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class BookTicker { - - /** - * Ticker symbol. - */ - private String symbol; - - /** - * Bid price. - */ - private String bidPrice; - - /** - * Bid quantity - */ - private String bidQty; - - /** - * Ask price. - */ - private String askPrice; - - /** - * Ask quantity. - */ - private String askQty; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getBidPrice() { - return bidPrice; - } - - public void setBidPrice(String bidPrice) { - this.bidPrice = bidPrice; - } - - public String getBidQty() { - return bidQty; - } - - public void setBidQty(String bidQty) { - this.bidQty = bidQty; - } - - public String getAskPrice() { - return askPrice; - } - - public void setAskPrice(String askPrice) { - this.askPrice = askPrice; - } - - public String getAskQty() { - return askQty; - } - - public void setAskQty(String askQty) { - this.askQty = askQty; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("bidPrice", bidPrice) - .append("bidQty", bidQty) - .append("askPrice", askPrice) - .append("askQty", askQty) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents the best price/qty on the order book for a given symbol. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class BookTicker { + + /** + * Ticker symbol. + */ + private String symbol; + + /** + * Bid price. + */ + private String bidPrice; + + /** + * Bid quantity + */ + private String bidQty; + + /** + * Ask price. + */ + private String askPrice; + + /** + * Ask quantity. + */ + private String askQty; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getBidPrice() { + return bidPrice; + } + + public void setBidPrice(String bidPrice) { + this.bidPrice = bidPrice; + } + + public String getBidQty() { + return bidQty; + } + + public void setBidQty(String bidQty) { + this.bidQty = bidQty; + } + + public String getAskPrice() { + return askPrice; + } + + public void setAskPrice(String askPrice) { + this.askPrice = askPrice; + } + + public String getAskQty() { + return askQty; + } + + public void setAskQty(String askQty) { + this.askQty = askQty; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("bidPrice", bidPrice) + .append("bidQty", bidQty) + .append("askPrice", askPrice) + .append("askQty", askQty) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/Candlestick.java b/src/main/java/com/binance/api/client/domain/market/Candlestick.java old mode 100644 new mode 100755 index 275f7cd37..acd1718d3 --- a/src/main/java/com/binance/api/client/domain/market/Candlestick.java +++ b/src/main/java/com/binance/api/client/domain/market/Candlestick.java @@ -1,143 +1,143 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Kline/Candlestick bars for a symbol. Klines are uniquely identified by their open time. - */ -@JsonFormat(shape = JsonFormat.Shape.ARRAY) -@JsonPropertyOrder() -@JsonIgnoreProperties(ignoreUnknown = true) -public class Candlestick { - - private Long openTime; - - private String open; - - private String high; - - private String low; - - private String close; - - private String volume; - - private Long closeTime; - - private String quoteAssetVolume; - - private Long numberOfTrades; - - private String takerBuyBaseAssetVolume; - - private String takerBuyQuoteAssetVolume; - - public Long getOpenTime() { - return openTime; - } - - public void setOpenTime(Long openTime) { - this.openTime = openTime; - } - - public String getOpen() { - return open; - } - - public void setOpen(String open) { - this.open = open; - } - - public String getHigh() { - return high; - } - - public void setHigh(String high) { - this.high = high; - } - - public String getLow() { - return low; - } - - public void setLow(String low) { - this.low = low; - } - - public String getClose() { - return close; - } - - public void setClose(String close) { - this.close = close; - } - - public String getVolume() { - return volume; - } - - public void setVolume(String volume) { - this.volume = volume; - } - - public Long getCloseTime() { - return closeTime; - } - - public void setCloseTime(Long closeTime) { - this.closeTime = closeTime; - } - - public String getQuoteAssetVolume() { - return quoteAssetVolume; - } - - public void setQuoteAssetVolume(String quoteAssetVolume) { - this.quoteAssetVolume = quoteAssetVolume; - } - - public Long getNumberOfTrades() { - return numberOfTrades; - } - - public void setNumberOfTrades(Long numberOfTrades) { - this.numberOfTrades = numberOfTrades; - } - - public String getTakerBuyBaseAssetVolume() { - return takerBuyBaseAssetVolume; - } - - public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { - this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; - } - - public String getTakerBuyQuoteAssetVolume() { - return takerBuyQuoteAssetVolume; - } - - public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { - this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("openTime", openTime) - .append("open", open) - .append("high", high) - .append("low", low) - .append("close", close) - .append("volume", volume) - .append("closeTime", closeTime) - .append("quoteAssetVolume", quoteAssetVolume) - .append("numberOfTrades", numberOfTrades) - .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) - .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Kline/Candlestick bars for a symbol. Klines are uniquely identified by their open time. + */ +@JsonFormat(shape = JsonFormat.Shape.ARRAY) +@JsonPropertyOrder() +@JsonIgnoreProperties(ignoreUnknown = true) +public class Candlestick { + + private Long openTime; + + private String open; + + private String high; + + private String low; + + private String close; + + private String volume; + + private Long closeTime; + + private String quoteAssetVolume; + + private Long numberOfTrades; + + private String takerBuyBaseAssetVolume; + + private String takerBuyQuoteAssetVolume; + + public Long getOpenTime() { + return openTime; + } + + public void setOpenTime(Long openTime) { + this.openTime = openTime; + } + + public String getOpen() { + return open; + } + + public void setOpen(String open) { + this.open = open; + } + + public String getHigh() { + return high; + } + + public void setHigh(String high) { + this.high = high; + } + + public String getLow() { + return low; + } + + public void setLow(String low) { + this.low = low; + } + + public String getClose() { + return close; + } + + public void setClose(String close) { + this.close = close; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public Long getCloseTime() { + return closeTime; + } + + public void setCloseTime(Long closeTime) { + this.closeTime = closeTime; + } + + public String getQuoteAssetVolume() { + return quoteAssetVolume; + } + + public void setQuoteAssetVolume(String quoteAssetVolume) { + this.quoteAssetVolume = quoteAssetVolume; + } + + public Long getNumberOfTrades() { + return numberOfTrades; + } + + public void setNumberOfTrades(Long numberOfTrades) { + this.numberOfTrades = numberOfTrades; + } + + public String getTakerBuyBaseAssetVolume() { + return takerBuyBaseAssetVolume; + } + + public void setTakerBuyBaseAssetVolume(String takerBuyBaseAssetVolume) { + this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume; + } + + public String getTakerBuyQuoteAssetVolume() { + return takerBuyQuoteAssetVolume; + } + + public void setTakerBuyQuoteAssetVolume(String takerBuyQuoteAssetVolume) { + this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("openTime", openTime) + .append("open", open) + .append("high", high) + .append("low", low) + .append("close", close) + .append("volume", volume) + .append("closeTime", closeTime) + .append("quoteAssetVolume", quoteAssetVolume) + .append("numberOfTrades", numberOfTrades) + .append("takerBuyBaseAssetVolume", takerBuyBaseAssetVolume) + .append("takerBuyQuoteAssetVolume", takerBuyQuoteAssetVolume) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java b/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java old mode 100644 new mode 100755 index b34334977..577287c86 --- a/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java +++ b/src/main/java/com/binance/api/client/domain/market/CandlestickInterval.java @@ -1,36 +1,36 @@ -package com.binance.api.client.domain.market; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Kline/Candlestick intervals. - * m -> minutes; h -> hours; d -> days; w -> weeks; M -> months - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public enum CandlestickInterval { - ONE_MINUTE("1m"), - THREE_MINUTES("3m"), - FIVE_MINUTES("5m"), - FIFTEEN_MINUTES("15m"), - HALF_HOURLY("30m"), - HOURLY("1h"), - TWO_HOURLY("2h"), - FOUR_HOURLY("4h"), - SIX_HOURLY("6h"), - EIGHT_HOURLY("8h"), - TWELVE_HOURLY("12h"), - DAILY("1d"), - THREE_DAILY("3d"), - WEEKLY("1w"), - MONTHLY("1M"); - - private final String intervalId; - - CandlestickInterval(String intervalId) { - this.intervalId = intervalId; - } - - public String getIntervalId() { - return intervalId; - } -} +package com.binance.api.client.domain.market; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** + * Kline/Candlestick intervals. + * m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public enum CandlestickInterval { + ONE_MINUTE("1m"), + THREE_MINUTES("3m"), + FIVE_MINUTES("5m"), + FIFTEEN_MINUTES("15m"), + HALF_HOURLY("30m"), + HOURLY("1h"), + TWO_HOURLY("2h"), + FOUR_HOURLY("4h"), + SIX_HOURLY("6h"), + EIGHT_HOURLY("8h"), + TWELVE_HOURLY("12h"), + DAILY("1d"), + THREE_DAILY("3d"), + WEEKLY("1w"), + MONTHLY("1M"); + + private final String intervalId; + + CandlestickInterval(String intervalId) { + this.intervalId = intervalId; + } + + public String getIntervalId() { + return intervalId; + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBook.java b/src/main/java/com/binance/api/client/domain/market/OrderBook.java old mode 100644 new mode 100755 index 98ffb10e1..05f78f62f --- a/src/main/java/com/binance/api/client/domain/market/OrderBook.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBook.java @@ -1,62 +1,62 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -import java.util.List; - -/** - * Order book of a symbol in Binance. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderBook { - - /** - * Last update id of this order book. - */ - private long lastUpdateId; - - /** - * List of bids (price/qty). - */ - private List bids; - - /** - * List of asks (price/qty). - */ - private List asks; - - public long getLastUpdateId() { - return lastUpdateId; - } - - public void setLastUpdateId(long lastUpdateId) { - this.lastUpdateId = lastUpdateId; - } - - public List getBids() { - return bids; - } - - public void setBids(List bids) { - this.bids = bids; - } - - public List getAsks() { - return asks; - } - - public void setAsks(List asks) { - this.asks = asks; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("lastUpdateId", lastUpdateId) - .append("bids", bids) - .append("asks", asks) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.util.List; + +/** + * Order book of a symbol in Binance. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderBook { + + /** + * Last update id of this order book. + */ + private long lastUpdateId; + + /** + * List of bids (price/qty). + */ + private List bids; + + /** + * List of asks (price/qty). + */ + private List asks; + + public long getLastUpdateId() { + return lastUpdateId; + } + + public void setLastUpdateId(long lastUpdateId) { + this.lastUpdateId = lastUpdateId; + } + + public List getBids() { + return bids; + } + + public void setBids(List bids) { + this.bids = bids; + } + + public List getAsks() { + return asks; + } + + public void setAsks(List asks) { + this.asks = asks; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("lastUpdateId", lastUpdateId) + .append("bids", bids) + .append("asks", asks) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java b/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java old mode 100644 new mode 100755 index 7d4d2635b..4e2cb65ea --- a/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBookEntry.java @@ -1,44 +1,44 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * An order book entry consisting of price and quantity. - */ -@JsonDeserialize(using = OrderBookEntryDeserializer.class) -@JsonSerialize(using = OrderBookEntrySerializer.class) -@JsonIgnoreProperties(ignoreUnknown = true) -public class OrderBookEntry { - - private String price; - private String qty; - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - public String getQty() { - return qty; - } - - public void setQty(String qty) { - this.qty = qty; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("price", price) - .append("qty", qty) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * An order book entry consisting of price and quantity. + */ +@JsonDeserialize(using = OrderBookEntryDeserializer.class) +@JsonSerialize(using = OrderBookEntrySerializer.class) +@JsonIgnoreProperties(ignoreUnknown = true) +public class OrderBookEntry { + + private String price; + private String qty; + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getQty() { + return qty; + } + + public void setQty(String qty) { + this.qty = qty; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("price", price) + .append("qty", qty) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java b/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java old mode 100644 new mode 100755 index 0d907d37c..4a65e253b --- a/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBookEntryDeserializer.java @@ -1,29 +1,29 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.domain.market.OrderBookEntry; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; - -import java.io.IOException; - -/** - * Custom deserializer for an OrderBookEntry, since the API returns an array in the format [ price, qty, [] ]. - */ -public class OrderBookEntryDeserializer extends JsonDeserializer { - - @Override - public OrderBookEntry deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { - ObjectCodec oc = jp.getCodec(); - JsonNode node = oc.readTree(jp); - final String price = node.get(0).asText(); - final String qty = node.get(1).asText(); - - OrderBookEntry orderBookEntry = new OrderBookEntry(); - orderBookEntry.setPrice(price); - orderBookEntry.setQty(qty); - return orderBookEntry; - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.domain.market.OrderBookEntry; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +import java.io.IOException; + +/** + * Custom deserializer for an OrderBookEntry, since the API returns an array in the format [ price, qty, [] ]. + */ +public class OrderBookEntryDeserializer extends JsonDeserializer { + + @Override + public OrderBookEntry deserialize(JsonParser jp, DeserializationContext ctx) throws IOException { + ObjectCodec oc = jp.getCodec(); + JsonNode node = oc.readTree(jp); + final String price = node.get(0).asText(); + final String qty = node.get(1).asText(); + + OrderBookEntry orderBookEntry = new OrderBookEntry(); + orderBookEntry.setPrice(price); + orderBookEntry.setQty(qty); + return orderBookEntry; + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java b/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java old mode 100644 new mode 100755 index 937892d76..132f8914a --- a/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java +++ b/src/main/java/com/binance/api/client/domain/market/OrderBookEntrySerializer.java @@ -1,21 +1,21 @@ -package com.binance.api.client.domain.market; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.JsonSerializer; - -import java.io.IOException; - -/** - * Custom serializer for an OrderBookEntry. - */ -public class OrderBookEntrySerializer extends JsonSerializer { - - @Override - public void serialize(OrderBookEntry orderBookEntry, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartArray(); - gen.writeString(orderBookEntry.getPrice()); - gen.writeString(orderBookEntry.getQty()); - gen.writeEndArray(); - } -} +package com.binance.api.client.domain.market; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.JsonSerializer; + +import java.io.IOException; + +/** + * Custom serializer for an OrderBookEntry. + */ +public class OrderBookEntrySerializer extends JsonSerializer { + + @Override + public void serialize(OrderBookEntry orderBookEntry, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeStartArray(); + gen.writeString(orderBookEntry.getPrice()); + gen.writeString(orderBookEntry.getQty()); + gen.writeEndArray(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/TickerPrice.java b/src/main/java/com/binance/api/client/domain/market/TickerPrice.java old mode 100644 new mode 100755 index 2c7a036ac..598893c6d --- a/src/main/java/com/binance/api/client/domain/market/TickerPrice.java +++ b/src/main/java/com/binance/api/client/domain/market/TickerPrice.java @@ -1,46 +1,46 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Wraps a symbol and its corresponding latest price. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class TickerPrice { - - /** - * Ticker symbol. - */ - private String symbol; - - /** - * Latest price. - */ - private String price; - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getPrice() { - return price; - } - - public void setPrice(String price) { - this.price = price; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("price", price) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Wraps a symbol and its corresponding latest price. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TickerPrice { + + /** + * Ticker symbol. + */ + private String symbol; + + /** + * Latest price. + */ + private String price; + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("price", price) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java b/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java old mode 100644 new mode 100755 index c23069de0..7cd3a08ca --- a/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java +++ b/src/main/java/com/binance/api/client/domain/market/TickerStatistics.java @@ -1,256 +1,256 @@ -package com.binance.api.client.domain.market; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * 24 hour price change statistics for a ticker. - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class TickerStatistics { - - /** - * Ticker symbol. - */ - private String symbol; - - /** - * Price change during the last 24 hours. - */ - private String priceChange; - - /** - * Price change, in percentage, during the last 24 hours. - */ - private String priceChangePercent; - - /** - * Weighted average price. - */ - private String weightedAvgPrice; - - /** - * Previous close price. - */ - private String prevClosePrice; - - /** - * Last price. - */ - private String lastPrice; - - /** - * Bid price. - */ - private String bidPrice; - - /** - * Ask price. - */ - private String askPrice; - - /** - * Open price 24 hours ago. - */ - private String openPrice; - - /** - * Highest price during the past 24 hours. - */ - private String highPrice; - - /** - * Lowest price during the past 24 hours. - */ - private String lowPrice; - - /** - * Total volume during the past 24 hours. - */ - private String volume; - - /** - * Open time. - */ - private long openTime; - - /** - * Close time. - */ - private long closeTime; - - /** - * First trade id. - */ - private long firstId; - - /** - * Last trade id. - */ - private long lastId; - - /** - * Total number of trades during the last 24 hours. - */ - private long count; - - public String getPriceChange() { - return priceChange; - } - - public void setPriceChange(String priceChange) { - this.priceChange = priceChange; - } - - public String getPriceChangePercent() { - return priceChangePercent; - } - - public void setPriceChangePercent(String priceChangePercent) { - this.priceChangePercent = priceChangePercent; - } - - public String getWeightedAvgPrice() { - return weightedAvgPrice; - } - - public void setWeightedAvgPrice(String weightedAvgPrice) { - this.weightedAvgPrice = weightedAvgPrice; - } - - public String getPrevClosePrice() { - return prevClosePrice; - } - - public void setPrevClosePrice(String prevClosePrice) { - this.prevClosePrice = prevClosePrice; - } - - public String getLastPrice() { - return lastPrice; - } - - public void setLastPrice(String lastPrice) { - this.lastPrice = lastPrice; - } - - public String getBidPrice() { - return bidPrice; - } - - public void setBidPrice(String bidPrice) { - this.bidPrice = bidPrice; - } - - public String getAskPrice() { - return askPrice; - } - - public void setAskPrice(String askPrice) { - this.askPrice = askPrice; - } - - public String getOpenPrice() { - return openPrice; - } - - public void setOpenPrice(String openPrice) { - this.openPrice = openPrice; - } - - public String getHighPrice() { - return highPrice; - } - - public void setHighPrice(String highPrice) { - this.highPrice = highPrice; - } - - public String getLowPrice() { - return lowPrice; - } - - public void setLowPrice(String lowPrice) { - this.lowPrice = lowPrice; - } - - public String getVolume() { - return volume; - } - - public void setVolume(String volume) { - this.volume = volume; - } - - public long getOpenTime() { - return openTime; - } - - public void setOpenTime(long openTime) { - this.openTime = openTime; - } - - public long getCloseTime() { - return closeTime; - } - - public void setCloseTime(long closeTime) { - this.closeTime = closeTime; - } - - public long getFirstId() { - return firstId; - } - - public void setFirstId(long firstId) { - this.firstId = firstId; - } - - public long getLastId() { - return lastId; - } - - public void setLastId(long lastId) { - this.lastId = lastId; - } - - public long getCount() { - return count; - } - - public void setCount(long count) { - this.count = count; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("symbol", symbol) - .append("priceChange", priceChange) - .append("priceChangePercent", priceChangePercent) - .append("weightedAvgPrice", weightedAvgPrice) - .append("prevClosePrice", prevClosePrice) - .append("lastPrice", lastPrice) - .append("bidPrice", bidPrice) - .append("askPrice", askPrice) - .append("openPrice", openPrice) - .append("highPrice", highPrice) - .append("lowPrice", lowPrice) - .append("volume", volume) - .append("openTime", openTime) - .append("closeTime", closeTime) - .append("firstId", firstId) - .append("lastId", lastId) - .append("count", count) - .toString(); - } -} +package com.binance.api.client.domain.market; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * 24 hour price change statistics for a ticker. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class TickerStatistics { + + /** + * Ticker symbol. + */ + private String symbol; + + /** + * Price change during the last 24 hours. + */ + private String priceChange; + + /** + * Price change, in percentage, during the last 24 hours. + */ + private String priceChangePercent; + + /** + * Weighted average price. + */ + private String weightedAvgPrice; + + /** + * Previous close price. + */ + private String prevClosePrice; + + /** + * Last price. + */ + private String lastPrice; + + /** + * Bid price. + */ + private String bidPrice; + + /** + * Ask price. + */ + private String askPrice; + + /** + * Open price 24 hours ago. + */ + private String openPrice; + + /** + * Highest price during the past 24 hours. + */ + private String highPrice; + + /** + * Lowest price during the past 24 hours. + */ + private String lowPrice; + + /** + * Total volume during the past 24 hours. + */ + private String volume; + + /** + * Open time. + */ + private long openTime; + + /** + * Close time. + */ + private long closeTime; + + /** + * First trade id. + */ + private long firstId; + + /** + * Last trade id. + */ + private long lastId; + + /** + * Total number of trades during the last 24 hours. + */ + private long count; + + public String getPriceChange() { + return priceChange; + } + + public void setPriceChange(String priceChange) { + this.priceChange = priceChange; + } + + public String getPriceChangePercent() { + return priceChangePercent; + } + + public void setPriceChangePercent(String priceChangePercent) { + this.priceChangePercent = priceChangePercent; + } + + public String getWeightedAvgPrice() { + return weightedAvgPrice; + } + + public void setWeightedAvgPrice(String weightedAvgPrice) { + this.weightedAvgPrice = weightedAvgPrice; + } + + public String getPrevClosePrice() { + return prevClosePrice; + } + + public void setPrevClosePrice(String prevClosePrice) { + this.prevClosePrice = prevClosePrice; + } + + public String getLastPrice() { + return lastPrice; + } + + public void setLastPrice(String lastPrice) { + this.lastPrice = lastPrice; + } + + public String getBidPrice() { + return bidPrice; + } + + public void setBidPrice(String bidPrice) { + this.bidPrice = bidPrice; + } + + public String getAskPrice() { + return askPrice; + } + + public void setAskPrice(String askPrice) { + this.askPrice = askPrice; + } + + public String getOpenPrice() { + return openPrice; + } + + public void setOpenPrice(String openPrice) { + this.openPrice = openPrice; + } + + public String getHighPrice() { + return highPrice; + } + + public void setHighPrice(String highPrice) { + this.highPrice = highPrice; + } + + public String getLowPrice() { + return lowPrice; + } + + public void setLowPrice(String lowPrice) { + this.lowPrice = lowPrice; + } + + public String getVolume() { + return volume; + } + + public void setVolume(String volume) { + this.volume = volume; + } + + public long getOpenTime() { + return openTime; + } + + public void setOpenTime(long openTime) { + this.openTime = openTime; + } + + public long getCloseTime() { + return closeTime; + } + + public void setCloseTime(long closeTime) { + this.closeTime = closeTime; + } + + public long getFirstId() { + return firstId; + } + + public void setFirstId(long firstId) { + this.firstId = firstId; + } + + public long getLastId() { + return lastId; + } + + public void setLastId(long lastId) { + this.lastId = lastId; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + @Override + public String toString() { + return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) + .append("symbol", symbol) + .append("priceChange", priceChange) + .append("priceChangePercent", priceChangePercent) + .append("weightedAvgPrice", weightedAvgPrice) + .append("prevClosePrice", prevClosePrice) + .append("lastPrice", lastPrice) + .append("bidPrice", bidPrice) + .append("askPrice", askPrice) + .append("openPrice", openPrice) + .append("highPrice", highPrice) + .append("lowPrice", lowPrice) + .append("volume", volume) + .append("openTime", openTime) + .append("closeTime", closeTime) + .append("firstId", firstId) + .append("lastId", lastId) + .append("count", count) + .toString(); + } +} diff --git a/src/main/java/com/binance/api/client/exception/BinanceApiException.java b/src/main/java/com/binance/api/client/exception/BinanceApiException.java old mode 100644 new mode 100755 index a40d9e7a9..80430fd8d --- a/src/main/java/com/binance/api/client/exception/BinanceApiException.java +++ b/src/main/java/com/binance/api/client/exception/BinanceApiException.java @@ -1,74 +1,74 @@ -package com.binance.api.client.exception; - -import com.binance.api.client.BinanceApiError; - -/** - * An exception which can occur while invoking methods of the Binance API. - */ -public class BinanceApiException extends RuntimeException { - - private static final long serialVersionUID = 3788669840036201041L; -/** - * Error response object returned by Binance API. - */ - private BinanceApiError error; - - /** - * Instantiates a new binance api exception. - * - * @param error an error response object - */ - public BinanceApiException(BinanceApiError error) { - this.error = error; - } - - /** - * Instantiates a new binance api exception. - */ - public BinanceApiException() { - super(); - } - - /** - * Instantiates a new binance api exception. - * - * @param message the message - */ - public BinanceApiException(String message) { - super(message); - } - - /** - * Instantiates a new binance api exception. - * - * @param cause the cause - */ - public BinanceApiException(Throwable cause) { - super(cause); - } - - /** - * Instantiates a new binance api exception. - * - * @param message the message - * @param cause the cause - */ - public BinanceApiException(String message, Throwable cause) { - super(message, cause); - } - - /** - * @return the response error object from Binance API, or null if no response object was returned (e.g. server returned 500). - */ - public BinanceApiError getError() { - return error; - } - - @Override - public String getMessage() { - if (error != null) { - return error.getMsg(); - } - return super.getMessage(); - } -} +package com.binance.api.client.exception; + +import com.binance.api.client.BinanceApiError; + +/** + * An exception which can occur while invoking methods of the Binance API. + */ +public class BinanceApiException extends RuntimeException { + + private static final long serialVersionUID = 3788669840036201041L; +/** + * Error response object returned by Binance API. + */ + private BinanceApiError error; + + /** + * Instantiates a new binance api exception. + * + * @param error an error response object + */ + public BinanceApiException(BinanceApiError error) { + this.error = error; + } + + /** + * Instantiates a new binance api exception. + */ + public BinanceApiException() { + super(); + } + + /** + * Instantiates a new binance api exception. + * + * @param message the message + */ + public BinanceApiException(String message) { + super(message); + } + + /** + * Instantiates a new binance api exception. + * + * @param cause the cause + */ + public BinanceApiException(Throwable cause) { + super(cause); + } + + /** + * Instantiates a new binance api exception. + * + * @param message the message + * @param cause the cause + */ + public BinanceApiException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @return the response error object from Binance API, or null if no response object was returned (e.g. server returned 500). + */ + public BinanceApiError getError() { + return error; + } + + @Override + public String getMessage() { + if (error != null) { + return error.getMsg(); + } + return super.getMessage(); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java new file mode 100755 index 000000000..4514bd314 --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java @@ -0,0 +1,103 @@ +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiAsyncMarginRestClient; +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; + +/** + * Implementation of Binance's Margin REST API using Retrofit with asynchronous/non-blocking method calls. + */ +public class BinanceApiAsyncMarginRestClientImpl implements BinanceApiAsyncMarginRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiAsyncMarginRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + // Margin Account endpoints + + @Override + public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { + binanceApiService.getMarginAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAccount(BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { + binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), + orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void newOrder(NewOrder order, BinanceApiCallback callback) { + binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { + binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { + binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getMyTrades(String symbol, BinanceApiCallback> callback) { + binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // user stream endpoints + + @Override + public void startUserDataStream(BinanceApiCallback callback) { + binanceApiService.startMarginUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { + binanceApiService.keepAliveMarginUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void transfer(String asset, String amount, TransferType type, BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void borrow(String asset, String amount, BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void repay(String asset, String amount, BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.repay(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java old mode 100644 new mode 100755 index 97f02148c..c41cba73a --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncRestClientImpl.java @@ -1,242 +1,242 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.event.ListenKey; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.ServerTime; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; - -/** - * Implementation of Binance's REST API using Retrofit with asynchronous/non-blocking method calls. - */ -public class BinanceApiAsyncRestClientImpl implements BinanceApiAsyncRestClient { - - private final BinanceApiService binanceApiService; - - public BinanceApiAsyncRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - // General endpoints - - @Override - public void ping(BinanceApiCallback callback) { - binanceApiService.ping().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getServerTime(BinanceApiCallback callback) { - binanceApiService.getServerTime().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getExchangeInfo(BinanceApiCallback callback) { - binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAllAssets(BinanceApiCallback> callback) { - binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html") - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // Market Data endpoints - - @Override - public void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback) { - binanceApiService.getOrderBook(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getTrades(String symbol, Integer limit, BinanceApiCallback> callback) { - binanceApiService.getTrades(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback) { - binanceApiService.getHistoricalTrades(symbol, limit, fromId).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { - binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAggTrades(String symbol, BinanceApiCallback> callback) { - getAggTrades(symbol, null, null, null, null, callback); - } - - @Override - public void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { - binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback) { - getCandlestickBars(symbol, interval, null, null, null, callback); - } - - @Override - public void get24HrPriceStatistics(String symbol, BinanceApiCallback callback) { - binanceApiService.get24HrPriceStatistics(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAll24HrPriceStatistics(BinanceApiCallback> callback) { - binanceApiService.getAll24HrPriceStatistics().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAllPrices(BinanceApiCallback> callback) { - binanceApiService.getLatestPrices().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getPrice(String symbol , BinanceApiCallback callback) { - binanceApiService.getLatestPrice(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getBookTickers(BinanceApiCallback> callback) { - binanceApiService.getBookTickers().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void newOrder(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void newOrderTest(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // Account endpoints - - @Override - public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { - binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { - binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { - binanceApiService.getOpenOrders(orderRequest.getSymbol(), - orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback) { - binanceApiService.getAllOrders(orderRequest.getSymbol(), - orderRequest.getOrderId(), orderRequest.getLimit(), - orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { - binanceApiService.getAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAccount(BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback) { - binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback) { - getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); - } - - @Override - public void getMyTrades(String symbol, BinanceApiCallback> callback) { - getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); - } - - @Override - public void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback) { - binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getDepositHistory(String asset, BinanceApiCallback callback) { - binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getWithdrawHistory(String asset, BinanceApiCallback callback) { - binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getDepositAddress(String asset, BinanceApiCallback callback) { - binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) - .enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // User stream endpoints - - @Override - public void startUserDataStream(BinanceApiCallback callback) { - binanceApiService.startUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { - binanceApiService.keepAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void closeUserDataStream(String listenKey, BinanceApiCallback callback) { - binanceApiService.closeAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.event.ListenKey; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; + +/** + * Implementation of Binance's REST API using Retrofit with asynchronous/non-blocking method calls. + */ +public class BinanceApiAsyncRestClientImpl implements BinanceApiAsyncRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiAsyncRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + // General endpoints + + @Override + public void ping(BinanceApiCallback callback) { + binanceApiService.ping().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getServerTime(BinanceApiCallback callback) { + binanceApiService.getServerTime().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getExchangeInfo(BinanceApiCallback callback) { + binanceApiService.getExchangeInfo().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAllAssets(BinanceApiCallback> callback) { + binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html") + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // Market Data endpoints + + @Override + public void getOrderBook(String symbol, Integer limit, BinanceApiCallback callback) { + binanceApiService.getOrderBook(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getTrades(String symbol, Integer limit, BinanceApiCallback> callback) { + binanceApiService.getTrades(symbol, limit).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getHistoricalTrades(String symbol, Integer limit, Long fromId, BinanceApiCallback> callback) { + binanceApiService.getHistoricalTrades(symbol, limit, fromId).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { + binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAggTrades(String symbol, BinanceApiCallback> callback) { + getAggTrades(symbol, null, null, null, null, callback); + } + + @Override + public void getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime, BinanceApiCallback> callback) { + binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getCandlestickBars(String symbol, CandlestickInterval interval, BinanceApiCallback> callback) { + getCandlestickBars(symbol, interval, null, null, null, callback); + } + + @Override + public void get24HrPriceStatistics(String symbol, BinanceApiCallback callback) { + binanceApiService.get24HrPriceStatistics(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAll24HrPriceStatistics(BinanceApiCallback> callback) { + binanceApiService.getAll24HrPriceStatistics().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAllPrices(BinanceApiCallback> callback) { + binanceApiService.getLatestPrices().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getPrice(String symbol , BinanceApiCallback callback) { + binanceApiService.getLatestPrice(symbol).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getBookTickers(BinanceApiCallback> callback) { + binanceApiService.getBookTickers().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void newOrder(NewOrder order, BinanceApiCallback callback) { + binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void newOrderTest(NewOrder order, BinanceApiCallback callback) { + binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // Account endpoints + + @Override + public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { + binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { + binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { + binanceApiService.getOpenOrders(orderRequest.getSymbol(), + orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAllOrders(AllOrdersRequest orderRequest, BinanceApiCallback> callback) { + binanceApiService.getAllOrders(orderRequest.getSymbol(), + orderRequest.getOrderId(), orderRequest.getLimit(), + orderRequest.getRecvWindow(), orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { + binanceApiService.getAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getAccount(BinanceApiCallback callback) { + long timestamp = System.currentTimeMillis(); + binanceApiService.getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp, BinanceApiCallback> callback) { + binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getMyTrades(String symbol, Integer limit, BinanceApiCallback> callback) { + getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); + } + + @Override + public void getMyTrades(String symbol, BinanceApiCallback> callback) { + getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis(), callback); + } + + @Override + public void withdraw(String asset, String address, String amount, String name, String addressTag, BinanceApiCallback callback) { + binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getDepositHistory(String asset, BinanceApiCallback callback) { + binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getWithdrawHistory(String asset, BinanceApiCallback callback) { + binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void getDepositAddress(String asset, BinanceApiCallback callback) { + binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()) + .enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + // User stream endpoints + + @Override + public void startUserDataStream(BinanceApiCallback callback) { + binanceApiService.startUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { + binanceApiService.keepAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } + + @Override + public void closeUserDataStream(String listenKey, BinanceApiCallback callback) { + binanceApiService.closeAliveUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java old mode 100644 new mode 100755 index 10b896ac6..355fa1348 --- a/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiCallbackAdapter.java @@ -1,51 +1,51 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.BinanceApiError; -import com.binance.api.client.exception.BinanceApiException; -import retrofit2.Call; -import retrofit2.Callback; -import retrofit2.Response; - -import java.io.IOException; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.getBinanceApiError; - -/** - * An adapter/wrapper which transforms a Callback from Retrofit into a BinanceApiCallback which is exposed to the client. - */ -public class BinanceApiCallbackAdapter implements Callback { - - private final BinanceApiCallback callback; - - public BinanceApiCallbackAdapter(BinanceApiCallback callback) { - this.callback = callback; - } - - public void onResponse(Call call, Response response) { - if (response.isSuccessful()) { - callback.onResponse(response.body()); - } else { - if (response.code() == 504) { - // HTTP 504 return code is used when the API successfully sent the message but not get a response within the timeout period. - // It is important to NOT treat this as a failure; the execution status is UNKNOWN and could have been a success. - return; - } - try { - BinanceApiError apiError = getBinanceApiError(response); - onFailure(call, new BinanceApiException(apiError)); - } catch (IOException e) { - onFailure(call, new BinanceApiException(e)); - } - } - } - - @Override - public void onFailure(Call call, Throwable throwable) { - if (throwable instanceof BinanceApiException) { - callback.onFailure(throwable); - } else { - callback.onFailure(new BinanceApiException(throwable)); - } - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiError; +import com.binance.api.client.exception.BinanceApiException; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +import java.io.IOException; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.getBinanceApiError; + +/** + * An adapter/wrapper which transforms a Callback from Retrofit into a BinanceApiCallback which is exposed to the client. + */ +public class BinanceApiCallbackAdapter implements Callback { + + private final BinanceApiCallback callback; + + public BinanceApiCallbackAdapter(BinanceApiCallback callback) { + this.callback = callback; + } + + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + callback.onResponse(response.body()); + } else { + if (response.code() == 504) { + // HTTP 504 return code is used when the API successfully sent the message but not get a response within the timeout period. + // It is important to NOT treat this as a failure; the execution status is UNKNOWN and could have been a success. + return; + } + try { + BinanceApiError apiError = getBinanceApiError(response); + onFailure(call, new BinanceApiException(apiError)); + } catch (IOException e) { + onFailure(call, new BinanceApiException(e)); + } + } + } + + @Override + public void onFailure(Call call, Throwable throwable) { + if (throwable instanceof BinanceApiException) { + callback.onFailure(throwable); + } else { + callback.onFailure(new BinanceApiException(throwable)); + } + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java new file mode 100755 index 000000000..93bf3244d --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -0,0 +1,101 @@ +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; + +/** + * Implementation of Binance's Margin REST API using Retrofit with asynchronous/non-blocking method calls. + */ +public class BinanceApiMarginRestClientImpl implements BinanceApiMarginRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiMarginRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + @Override + public MarginAccount getAccount() { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } + + @Override + public List getOpenOrders(OrderRequest orderRequest) { + return executeSync(binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), + orderRequest.getTimestamp())); + } + + @Override + public NewOrderResponse newOrder(NewOrder order) { + return executeSync(binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + } + + @Override + public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { + return executeSync(binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); + } + + @Override + public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { + return executeSync(binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); + } + + @Override + public List getMyTrades(String symbol) { + return executeSync(binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + // user stream endpoints + + @Override + public String startUserDataStream() { + return executeSync(binanceApiService.startMarginUserDataStream()).toString(); + } + + @Override + public void keepAliveUserDataStream(String listenKey) { + executeSync(binanceApiService.keepAliveMarginUserDataStream(listenKey)); + } + + @Override + public MarginTransaction transfer(String asset, String amount, TransferType type) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } + + @Override + public MarginTransaction borrow(String asset, String amount) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } + + @Override + public LoanQueryResult queryLoan(String asset, String txId) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryLoan(asset, txId, timestamp)); + } + + @Override + public MarginTransaction repay(String asset, String amount) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.repay(asset, amount, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); + } +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java old mode 100644 new mode 100755 index aceb3799a..b52fccd0f --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -1,233 +1,233 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; - -import java.util.List; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; -import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; - -/** - * Implementation of Binance's REST API using Retrofit with synchronous/blocking method calls. - */ -public class BinanceApiRestClientImpl implements BinanceApiRestClient { - - private final BinanceApiService binanceApiService; - - public BinanceApiRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - // General endpoints - - @Override - public void ping() { - executeSync(binanceApiService.ping()); - } - - @Override - public Long getServerTime() { - return executeSync(binanceApiService.getServerTime()).getServerTime(); - } - - @Override - public ExchangeInfo getExchangeInfo() { - return executeSync(binanceApiService.getExchangeInfo()); - } - - @Override - public List getAllAssets() { - return executeSync(binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html")); - } - - // Market Data endpoints - - @Override - public OrderBook getOrderBook(String symbol, Integer limit) { - return executeSync(binanceApiService.getOrderBook(symbol, limit)); - } - - @Override - public List getTrades(String symbol, Integer limit) { - return executeSync(binanceApiService.getTrades(symbol, limit)); - } - - @Override - public List getHistoricalTrades(String symbol, Integer limit, Long fromId) { - return executeSync(binanceApiService.getHistoricalTrades(symbol, limit, fromId)); - } - - @Override - public List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime) { - return executeSync(binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime)); - } - - @Override - public List getAggTrades(String symbol) { - return getAggTrades(symbol, null, null, null, null); - } - - @Override - public List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime) { - return executeSync(binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime)); - } - - @Override - public List getCandlestickBars(String symbol, CandlestickInterval interval) { - return getCandlestickBars(symbol, interval, null, null, null); - } - - @Override - public TickerStatistics get24HrPriceStatistics(String symbol) { - return executeSync(binanceApiService.get24HrPriceStatistics(symbol)); - } - - @Override - public List getAll24HrPriceStatistics() { - return executeSync(binanceApiService.getAll24HrPriceStatistics()); - } - - @Override - public TickerPrice getPrice(String symbol) { - return executeSync(binanceApiService.getLatestPrice(symbol)); - } - - @Override - public List getAllPrices() { - return executeSync(binanceApiService.getLatestPrices()); - } - - @Override - public List getBookTickers() { - return executeSync(binanceApiService.getBookTickers()); - } - - @Override - public NewOrderResponse newOrder(NewOrder order) { - return executeSync(binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); - } - - @Override - public void newOrderTest(NewOrder order) { - executeSync(binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); - } - - // Account endpoints - - @Override - public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { - return executeSync(binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); - } - - @Override - public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { - return executeSync(binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); - } - - @Override - public List getOpenOrders(OrderRequest orderRequest) { - return executeSync(binanceApiService.getOpenOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), orderRequest.getTimestamp())); - } - - @Override - public List getAllOrders(AllOrdersRequest orderRequest) { - return executeSync(binanceApiService.getAllOrders(orderRequest.getSymbol(), - orderRequest.getOrderId(), orderRequest.getLimit(), - orderRequest.getRecvWindow(), orderRequest.getTimestamp())); - } - - @Override - public Account getAccount(Long recvWindow, Long timestamp) { - return executeSync(binanceApiService.getAccount(recvWindow, timestamp)); - } - - @Override - public Account getAccount() { - return getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp) { - return executeSync(binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp)); - } - - @Override - public List getMyTrades(String symbol, Integer limit) { - return getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public List getMyTrades(String symbol) { - return getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag) { - return executeSync(binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public DepositHistory getDepositHistory(String asset) { - return executeSync(binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public WithdrawHistory getWithdrawHistory(String asset) { - return executeSync(binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public DepositAddress getDepositAddress(String asset) { - return executeSync(binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - // User stream endpoints - - @Override - public String startUserDataStream() { - return executeSync(binanceApiService.startUserDataStream()).toString(); - } - - @Override - public void keepAliveUserDataStream(String listenKey) { - executeSync(binanceApiService.keepAliveUserDataStream(listenKey)); - } - - @Override - public void closeUserDataStream(String listenKey) { - executeSync(binanceApiService.closeAliveUserDataStream(listenKey)); - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.DepositAddress; +import com.binance.api.client.domain.account.DepositHistory; +import com.binance.api.client.domain.account.NewOrder; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.Trade; +import com.binance.api.client.domain.account.TradeHistoryItem; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; + +/** + * Implementation of Binance's REST API using Retrofit with synchronous/blocking method calls. + */ +public class BinanceApiRestClientImpl implements BinanceApiRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + // General endpoints + + @Override + public void ping() { + executeSync(binanceApiService.ping()); + } + + @Override + public Long getServerTime() { + return executeSync(binanceApiService.getServerTime()).getServerTime(); + } + + @Override + public ExchangeInfo getExchangeInfo() { + return executeSync(binanceApiService.getExchangeInfo()); + } + + @Override + public List getAllAssets() { + return executeSync(binanceApiService.getAllAssets(BinanceApiConstants.ASSET_INFO_API_BASE_URL + "assetWithdraw/getAllAsset.html")); + } + + // Market Data endpoints + + @Override + public OrderBook getOrderBook(String symbol, Integer limit) { + return executeSync(binanceApiService.getOrderBook(symbol, limit)); + } + + @Override + public List getTrades(String symbol, Integer limit) { + return executeSync(binanceApiService.getTrades(symbol, limit)); + } + + @Override + public List getHistoricalTrades(String symbol, Integer limit, Long fromId) { + return executeSync(binanceApiService.getHistoricalTrades(symbol, limit, fromId)); + } + + @Override + public List getAggTrades(String symbol, String fromId, Integer limit, Long startTime, Long endTime) { + return executeSync(binanceApiService.getAggTrades(symbol, fromId, limit, startTime, endTime)); + } + + @Override + public List getAggTrades(String symbol) { + return getAggTrades(symbol, null, null, null, null); + } + + @Override + public List getCandlestickBars(String symbol, CandlestickInterval interval, Integer limit, Long startTime, Long endTime) { + return executeSync(binanceApiService.getCandlestickBars(symbol, interval.getIntervalId(), limit, startTime, endTime)); + } + + @Override + public List getCandlestickBars(String symbol, CandlestickInterval interval) { + return getCandlestickBars(symbol, interval, null, null, null); + } + + @Override + public TickerStatistics get24HrPriceStatistics(String symbol) { + return executeSync(binanceApiService.get24HrPriceStatistics(symbol)); + } + + @Override + public List getAll24HrPriceStatistics() { + return executeSync(binanceApiService.getAll24HrPriceStatistics()); + } + + @Override + public TickerPrice getPrice(String symbol) { + return executeSync(binanceApiService.getLatestPrice(symbol)); + } + + @Override + public List getAllPrices() { + return executeSync(binanceApiService.getLatestPrices()); + } + + @Override + public List getBookTickers() { + return executeSync(binanceApiService.getBookTickers()); + } + + @Override + public NewOrderResponse newOrder(NewOrder order) { + return executeSync(binanceApiService.newOrder(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + } + + @Override + public void newOrderTest(NewOrder order) { + executeSync(binanceApiService.newOrderTest(order.getSymbol(), order.getSide(), order.getType(), + order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), + order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); + } + + // Account endpoints + + @Override + public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { + return executeSync(binanceApiService.getOrderStatus(orderStatusRequest.getSymbol(), + orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), + orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); + } + + @Override + public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { + return executeSync(binanceApiService.cancelOrder(cancelOrderRequest.getSymbol(), + cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), + cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); + } + + @Override + public List getOpenOrders(OrderRequest orderRequest) { + return executeSync(binanceApiService.getOpenOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), orderRequest.getTimestamp())); + } + + @Override + public List getAllOrders(AllOrdersRequest orderRequest) { + return executeSync(binanceApiService.getAllOrders(orderRequest.getSymbol(), + orderRequest.getOrderId(), orderRequest.getLimit(), + orderRequest.getRecvWindow(), orderRequest.getTimestamp())); + } + + @Override + public Account getAccount(Long recvWindow, Long timestamp) { + return executeSync(binanceApiService.getAccount(recvWindow, timestamp)); + } + + @Override + public Account getAccount() { + return getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); + } + + @Override + public List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp) { + return executeSync(binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp)); + } + + @Override + public List getMyTrades(String symbol, Integer limit) { + return getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); + } + + @Override + public List getMyTrades(String symbol) { + return getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); + } + + @Override + public WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag) { + return executeSync(binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + @Override + public DepositHistory getDepositHistory(String asset) { + return executeSync(binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + @Override + public WithdrawHistory getWithdrawHistory(String asset) { + return executeSync(binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + @Override + public DepositAddress getDepositAddress(String asset) { + return executeSync(binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); + } + + // User stream endpoints + + @Override + public String startUserDataStream() { + return executeSync(binanceApiService.startUserDataStream()).toString(); + } + + @Override + public void keepAliveUserDataStream(String listenKey) { + executeSync(binanceApiService.keepAliveUserDataStream(listenKey)); + } + + @Override + public void closeUserDataStream(String listenKey) { + executeSync(binanceApiService.closeAliveUserDataStream(listenKey)); + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java old mode 100644 new mode 100755 index 9643c8e90..7ee0513f3 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -1,172 +1,221 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.NewOrderResponseType; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.event.ListenKey; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.ServerTime; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; -import retrofit2.Call; -import retrofit2.http.DELETE; -import retrofit2.http.GET; -import retrofit2.http.Headers; -import retrofit2.http.POST; -import retrofit2.http.PUT; -import retrofit2.http.Query; -import retrofit2.http.Url; - -import java.util.List; - -/** - * Binance's REST API URL mappings and endpoint security configuration. - */ -public interface BinanceApiService { - - // General endpoints - - @GET("/api/v1/ping") - Call ping(); - - @GET("/api/v1/time") - Call getServerTime(); - - @GET("/api/v1/exchangeInfo") - Call getExchangeInfo(); - - @GET - Call> getAllAssets(@Url String url); - - // Market data endpoints - - @GET("/api/v1/depth") - Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); - - @GET("/api/v1/trades") - Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @GET("/api/v1/historicalTrades") - Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); - - @GET("/api/v1/aggTrades") - Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); - - @GET("/api/v1/klines") - Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); - - @GET("/api/v1/ticker/24hr") - Call get24HrPriceStatistics(@Query("symbol") String symbol); - - @GET("/api/v1/ticker/24hr") - Call> getAll24HrPriceStatistics(); - - @GET("/api/v1/ticker/allPrices") - Call> getLatestPrices(); - - @GET("/api/v3/ticker/price") - Call getLatestPrice(@Query("symbol") String symbol); - - @GET("/api/v1/ticker/allBookTickers") - Call> getBookTickers(); - - // Account endpoints - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order") - Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order/test") - Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/order") - Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, - @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @DELETE("/api/v3/order") - Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/openOrders") - Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/allOrders") - Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/account") - Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/myTrades") - Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/wapi/v3/withdraw.html") - Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositHistory.html") - Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/withdrawHistory.html") - Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositAddress.html") - Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - // User stream endpoints - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @POST("/api/v1/userDataStream") - Call startUserDataStream(); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @PUT("/api/v1/userDataStream") - Call keepAliveUserDataStream(@Query("listenKey") String listenKey); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @DELETE("/api/v1/userDataStream") - Call closeAliveUserDataStream(@Query("listenKey") String listenKey); -} +package com.binance.api.client.impl; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.event.ListenKey; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.ServerTime; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; +import retrofit2.Call; +import retrofit2.http.DELETE; +import retrofit2.http.GET; +import retrofit2.http.Headers; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; + +import java.util.List; + +/** + * Binance's REST API URL mappings and endpoint security configuration. + */ +public interface BinanceApiService { + + // General endpoints + + @GET("/api/v1/ping") + Call ping(); + + @GET("/api/v1/time") + Call getServerTime(); + + @GET("/api/v1/exchangeInfo") + Call getExchangeInfo(); + + @GET + Call> getAllAssets(@Url String url); + + // Market data endpoints + + @GET("/api/v1/depth") + Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); + + @GET("/api/v1/trades") + Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @GET("/api/v1/historicalTrades") + Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); + + @GET("/api/v1/aggTrades") + Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); + + @GET("/api/v1/klines") + Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); + + @GET("/api/v1/ticker/24hr") + Call get24HrPriceStatistics(@Query("symbol") String symbol); + + @GET("/api/v1/ticker/24hr") + Call> getAll24HrPriceStatistics(); + + @GET("/api/v1/ticker/allPrices") + Call> getLatestPrices(); + + @GET("/api/v3/ticker/price") + Call getLatestPrice(@Query("symbol") String symbol); + + @GET("/api/v1/ticker/allBookTickers") + Call> getBookTickers(); + + // Account endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order") + Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order/test") + Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/order") + Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/api/v3/order") + Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/openOrders") + Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/allOrders") + Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/account") + Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/myTrades") + Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/wapi/v3/withdraw.html") + Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositHistory.html") + Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/withdrawHistory.html") + Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositAddress.html") + Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + // User stream endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/api/v1/userDataStream") + Call startUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/api/v1/userDataStream") + Call keepAliveUserDataStream(@Query("listenKey") String listenKey); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @DELETE("/api/v1/userDataStream") + Call closeAliveUserDataStream(@Query("listenKey") String listenKey); + + // Margin Account endpoints + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/transfer") + Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/loan") + Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/loan") + Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/repay") + Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/account") + Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/openOrders") + Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/margin/order") + Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/sapi/v1/margin/order") + Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/order") + Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/myTrades") + Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/sapi/v1/userDataStream") + Call startMarginUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/sapi/v1/userDataStream") + Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java old mode 100644 new mode 100755 index 8307f48b9..40acec7d2 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -1,97 +1,97 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiError; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.exception.BinanceApiException; -import com.binance.api.client.security.AuthenticationInterceptor; -import okhttp3.Dispatcher; -import okhttp3.OkHttpClient; -import okhttp3.RequestBody; -import okhttp3.ResponseBody; -import org.apache.commons.lang3.StringUtils; -import retrofit2.Call; -import retrofit2.Converter; -import retrofit2.Response; -import retrofit2.Retrofit; -import retrofit2.converter.jackson.JacksonConverterFactory; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.concurrent.TimeUnit; - -/** - * Generates a Binance API implementation based on @see {@link BinanceApiService}. - */ -public class BinanceApiServiceGenerator { - - private static final OkHttpClient sharedClient; - private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); - - static { - Dispatcher dispatcher = new Dispatcher(); - dispatcher.setMaxRequestsPerHost(500); - dispatcher.setMaxRequests(500); - sharedClient = new OkHttpClient.Builder() - .dispatcher(dispatcher) - .pingInterval(20, TimeUnit.SECONDS) - .build(); - } - - @SuppressWarnings("unchecked") - private static final Converter errorBodyConverter = - (Converter)converterFactory.responseBodyConverter( - BinanceApiError.class, new Annotation[0], null); - - public static S createService(Class serviceClass) { - return createService(serviceClass, null, null); - } - - public static S createService(Class serviceClass, String apiKey, String secret) { - Retrofit.Builder retrofitBuilder = new Retrofit.Builder() - .baseUrl(BinanceApiConstants.API_BASE_URL) - .addConverterFactory(converterFactory); - - if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { - retrofitBuilder.client(sharedClient); - } else { - // `adaptedClient` will use its own interceptor, but share thread pool etc with the 'parent' client - AuthenticationInterceptor interceptor = new AuthenticationInterceptor(apiKey, secret); - OkHttpClient adaptedClient = sharedClient.newBuilder().addInterceptor(interceptor).build(); - retrofitBuilder.client(adaptedClient); - } - - Retrofit retrofit = retrofitBuilder.build(); - return retrofit.create(serviceClass); - } - - /** - * Execute a REST call and block until the response is received. - */ - public static T executeSync(Call call) { - try { - Response response = call.execute(); - if (response.isSuccessful()) { - return response.body(); - } else { - BinanceApiError apiError = getBinanceApiError(response); - throw new BinanceApiException(apiError); - } - } catch (IOException e) { - throw new BinanceApiException(e); - } - } - - /** - * Extracts and converts the response error body into an object. - */ - public static BinanceApiError getBinanceApiError(Response response) throws IOException, BinanceApiException { - return errorBodyConverter.convert(response.errorBody()); - } - - /** - * Returns the shared OkHttpClient instance. - */ - public static OkHttpClient getSharedClient() { - return sharedClient; - } +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiError; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.exception.BinanceApiException; +import com.binance.api.client.security.AuthenticationInterceptor; +import okhttp3.Dispatcher; +import okhttp3.OkHttpClient; +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import org.apache.commons.lang3.StringUtils; +import retrofit2.Call; +import retrofit2.Converter; +import retrofit2.Response; +import retrofit2.Retrofit; +import retrofit2.converter.jackson.JacksonConverterFactory; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.util.concurrent.TimeUnit; + +/** + * Generates a Binance API implementation based on @see {@link BinanceApiService}. + */ +public class BinanceApiServiceGenerator { + + private static final OkHttpClient sharedClient; + private static final Converter.Factory converterFactory = JacksonConverterFactory.create(); + + static { + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequestsPerHost(500); + dispatcher.setMaxRequests(500); + sharedClient = new OkHttpClient.Builder() + .dispatcher(dispatcher) + .pingInterval(20, TimeUnit.SECONDS) + .build(); + } + + @SuppressWarnings("unchecked") + private static final Converter errorBodyConverter = + (Converter)converterFactory.responseBodyConverter( + BinanceApiError.class, new Annotation[0], null); + + public static S createService(Class serviceClass) { + return createService(serviceClass, null, null); + } + + public static S createService(Class serviceClass, String apiKey, String secret) { + Retrofit.Builder retrofitBuilder = new Retrofit.Builder() + .baseUrl(BinanceApiConstants.API_BASE_URL) + .addConverterFactory(converterFactory); + + if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { + retrofitBuilder.client(sharedClient); + } else { + // `adaptedClient` will use its own interceptor, but share thread pool etc with the 'parent' client + AuthenticationInterceptor interceptor = new AuthenticationInterceptor(apiKey, secret); + OkHttpClient adaptedClient = sharedClient.newBuilder().addInterceptor(interceptor).build(); + retrofitBuilder.client(adaptedClient); + } + + Retrofit retrofit = retrofitBuilder.build(); + return retrofit.create(serviceClass); + } + + /** + * Execute a REST call and block until the response is received. + */ + public static T executeSync(Call call) { + try { + Response response = call.execute(); + if (response.isSuccessful()) { + return response.body(); + } else { + BinanceApiError apiError = getBinanceApiError(response); + throw new BinanceApiException(apiError); + } + } catch (IOException e) { + throw new BinanceApiException(e); + } + } + + /** + * Extracts and converts the response error body into an object. + */ + public static BinanceApiError getBinanceApiError(Response response) throws IOException, BinanceApiException { + return errorBodyConverter.convert(response.errorBody()); + } + + /** + * Returns the shared OkHttpClient instance. + */ + public static OkHttpClient getSharedClient() { + return sharedClient; + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java old mode 100644 new mode 100755 index b9e530b0a..6583bae5f --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -1,86 +1,86 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.event.AggTradeEvent; -import com.binance.api.client.domain.event.AllMarketTickersEvent; -import com.binance.api.client.domain.event.CandlestickEvent; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.fasterxml.jackson.core.type.TypeReference; - -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.WebSocket; - -import java.io.Closeable; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Binance API WebSocket client implementation using OkHttp. - */ -public class BinanceApiWebSocketClientImpl implements BinanceApiWebSocketClient, Closeable { - - private final OkHttpClient client; - - public BinanceApiWebSocketClientImpl(OkHttpClient client) { - this.client = client; - } - - @Override - public Closeable onDepthEvent(String symbols, BinanceApiCallback callback) { - final String channel = Arrays.stream(symbols.split(",")) - .map(String::trim) - .map(s -> String.format("%s@depth", s)) - .collect(Collectors.joining("/")); - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, DepthEvent.class)); - } - - @Override - public Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback) { - final String channel = Arrays.stream(symbols.split(",")) - .map(String::trim) - .map(s -> String.format("%s@kline_%s", s, interval.getIntervalId())) - .collect(Collectors.joining("/")); - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, CandlestickEvent.class)); - } - - public Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback) { - final String channel = Arrays.stream(symbols.split(",")) - .map(String::trim) - .map(s -> String.format("%s@aggTrade", s)) - .collect(Collectors.joining("/")); - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, AggTradeEvent.class)); - } - - public Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback) { - return createNewWebSocket(listenKey, new BinanceApiWebSocketListener<>(callback, UserDataUpdateEvent.class)); - } - - public Closeable onAllMarketTickersEvent(BinanceApiCallback> callback) { - final String channel = "!ticker@arr"; - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() {})); - } - - /** - * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. - */ - @Override - public void close() { } - - private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { - String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); - Request request = new Request.Builder().url(streamingUrl).build(); - final WebSocket webSocket = client.newWebSocket(request, listener); - return () -> { - final int code = 1000; - listener.onClosing(webSocket, code, null); - webSocket.close(code, null); - listener.onClosed(webSocket, code, null); - }; - } -} +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.event.AggTradeEvent; +import com.binance.api.client.domain.event.AllMarketTickersEvent; +import com.binance.api.client.domain.event.CandlestickEvent; +import com.binance.api.client.domain.event.DepthEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.fasterxml.jackson.core.type.TypeReference; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.WebSocket; + +import java.io.Closeable; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Binance API WebSocket client implementation using OkHttp. + */ +public class BinanceApiWebSocketClientImpl implements BinanceApiWebSocketClient, Closeable { + + private final OkHttpClient client; + + public BinanceApiWebSocketClientImpl(OkHttpClient client) { + this.client = client; + } + + @Override + public Closeable onDepthEvent(String symbols, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@depth", s)) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, DepthEvent.class)); + } + + @Override + public Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@kline_%s", s, interval.getIntervalId())) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, CandlestickEvent.class)); + } + + public Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback) { + final String channel = Arrays.stream(symbols.split(",")) + .map(String::trim) + .map(s -> String.format("%s@aggTrade", s)) + .collect(Collectors.joining("/")); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, AggTradeEvent.class)); + } + + public Closeable onUserDataUpdateEvent(String listenKey, BinanceApiCallback callback) { + return createNewWebSocket(listenKey, new BinanceApiWebSocketListener<>(callback, UserDataUpdateEvent.class)); + } + + public Closeable onAllMarketTickersEvent(BinanceApiCallback> callback) { + final String channel = "!ticker@arr"; + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() {})); + } + + /** + * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. + */ + @Override + public void close() { } + + private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { + String streamingUrl = String.format("%s/%s", BinanceApiConstants.WS_API_BASE_URL, channel); + Request request = new Request.Builder().url(streamingUrl).build(); + final WebSocket webSocket = client.newWebSocket(request, listener); + return () -> { + final int code = 1000; + listener.onClosing(webSocket, code, null); + webSocket.close(code, null); + listener.onClosed(webSocket, code, null); + }; + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java old mode 100644 new mode 100755 index 8c84dbe3f..e2004090e --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketListener.java @@ -1,58 +1,58 @@ -package com.binance.api.client.impl; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.exception.BinanceApiException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; - -import java.io.IOException; - -/** - * Binance API WebSocket listener. - */ -public class BinanceApiWebSocketListener extends WebSocketListener { - - private BinanceApiCallback callback; - - private static final ObjectMapper mapper = new ObjectMapper(); - - private final ObjectReader objectReader; - - private boolean closing = false; - - public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) { - this.callback = callback; - this.objectReader = mapper.readerFor(eventClass); - } - - public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) { - this.callback = callback; - this.objectReader = mapper.readerFor(eventTypeReference); - } - - @Override - public void onMessage(WebSocket webSocket, String text) { - try { - T event = objectReader.readValue(text); - callback.onResponse(event); - } catch (IOException e) { - throw new BinanceApiException(e); - } - } - - @Override - public void onClosing(final WebSocket webSocket, final int code, final String reason) { - closing = true; - } - - @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { - if (!closing) { - callback.onFailure(t); - } - } +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.exception.BinanceApiException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; + +import java.io.IOException; + +/** + * Binance API WebSocket listener. + */ +public class BinanceApiWebSocketListener extends WebSocketListener { + + private BinanceApiCallback callback; + + private static final ObjectMapper mapper = new ObjectMapper(); + + private final ObjectReader objectReader; + + private boolean closing = false; + + public BinanceApiWebSocketListener(BinanceApiCallback callback, Class eventClass) { + this.callback = callback; + this.objectReader = mapper.readerFor(eventClass); + } + + public BinanceApiWebSocketListener(BinanceApiCallback callback, TypeReference eventTypeReference) { + this.callback = callback; + this.objectReader = mapper.readerFor(eventTypeReference); + } + + @Override + public void onMessage(WebSocket webSocket, String text) { + try { + T event = objectReader.readValue(text); + callback.onResponse(event); + } catch (IOException e) { + throw new BinanceApiException(e); + } + } + + @Override + public void onClosing(final WebSocket webSocket, final int code, final String reason) { + closing = true; + } + + @Override + public void onFailure(WebSocket webSocket, Throwable t, Response response) { + if (!closing) { + callback.onFailure(t); + } + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java b/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java old mode 100644 new mode 100755 index a2eff2281..197aaabcb --- a/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java +++ b/src/main/java/com/binance/api/client/security/AuthenticationInterceptor.java @@ -1,92 +1,92 @@ -package com.binance.api.client.security; - -import com.binance.api.client.constant.BinanceApiConstants; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okio.Buffer; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.util.Objects; - -/** - * A request interceptor that injects the API Key Header into requests, and signs messages, whenever required. - */ -public class AuthenticationInterceptor implements Interceptor { - - private final String apiKey; - - private final String secret; - - public AuthenticationInterceptor(String apiKey, String secret) { - this.apiKey = apiKey; - this.secret = secret; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request original = chain.request(); - Request.Builder newRequestBuilder = original.newBuilder(); - - boolean isApiKeyRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) != null; - boolean isSignatureRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED) != null; - newRequestBuilder.removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) - .removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED); - - // Endpoint requires sending a valid API-KEY - if (isApiKeyRequired || isSignatureRequired) { - newRequestBuilder.addHeader(BinanceApiConstants.API_KEY_HEADER, apiKey); - } - - // Endpoint requires signing the payload - if (isSignatureRequired) { - String payload = original.url().query(); - if (!StringUtils.isEmpty(payload)) { - String signature = HmacSHA256Signer.sign(payload, secret); - HttpUrl signedUrl = original.url().newBuilder().addQueryParameter("signature", signature).build(); - newRequestBuilder.url(signedUrl); - } - } - - // Build new request after adding the necessary authentication information - Request newRequest = newRequestBuilder.build(); - return chain.proceed(newRequest); - } - - /** - * Extracts the request body into a String. - * - * @return request body as a string - */ - @SuppressWarnings("unused") - private static String bodyToString(RequestBody request) { - try (final Buffer buffer = new Buffer()) { - final RequestBody copy = request; - if (copy != null) { - copy.writeTo(buffer); - } else { - return ""; - } - return buffer.readUtf8(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final AuthenticationInterceptor that = (AuthenticationInterceptor) o; - return Objects.equals(apiKey, that.apiKey) && - Objects.equals(secret, that.secret); - } - - @Override - public int hashCode() { - return Objects.hash(apiKey, secret); - } +package com.binance.api.client.security; + +import com.binance.api.client.constant.BinanceApiConstants; +import okhttp3.HttpUrl; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okio.Buffer; +import org.apache.commons.lang3.StringUtils; + +import java.io.IOException; +import java.util.Objects; + +/** + * A request interceptor that injects the API Key Header into requests, and signs messages, whenever required. + */ +public class AuthenticationInterceptor implements Interceptor { + + private final String apiKey; + + private final String secret; + + public AuthenticationInterceptor(String apiKey, String secret) { + this.apiKey = apiKey; + this.secret = secret; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request original = chain.request(); + Request.Builder newRequestBuilder = original.newBuilder(); + + boolean isApiKeyRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) != null; + boolean isSignatureRequired = original.header(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED) != null; + newRequestBuilder.removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY) + .removeHeader(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED); + + // Endpoint requires sending a valid API-KEY + if (isApiKeyRequired || isSignatureRequired) { + newRequestBuilder.addHeader(BinanceApiConstants.API_KEY_HEADER, apiKey); + } + + // Endpoint requires signing the payload + if (isSignatureRequired) { + String payload = original.url().query(); + if (!StringUtils.isEmpty(payload)) { + String signature = HmacSHA256Signer.sign(payload, secret); + HttpUrl signedUrl = original.url().newBuilder().addQueryParameter("signature", signature).build(); + newRequestBuilder.url(signedUrl); + } + } + + // Build new request after adding the necessary authentication information + Request newRequest = newRequestBuilder.build(); + return chain.proceed(newRequest); + } + + /** + * Extracts the request body into a String. + * + * @return request body as a string + */ + @SuppressWarnings("unused") + private static String bodyToString(RequestBody request) { + try (final Buffer buffer = new Buffer()) { + final RequestBody copy = request; + if (copy != null) { + copy.writeTo(buffer); + } else { + return ""; + } + return buffer.readUtf8(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final AuthenticationInterceptor that = (AuthenticationInterceptor) o; + return Objects.equals(apiKey, that.apiKey) && + Objects.equals(secret, that.secret); + } + + @Override + public int hashCode() { + return Objects.hash(apiKey, secret); + } } \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java b/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java old mode 100644 new mode 100755 index fc5f06702..17309e273 --- a/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java +++ b/src/main/java/com/binance/api/client/security/HmacSHA256Signer.java @@ -1,29 +1,29 @@ -package com.binance.api.client.security; - -import org.apache.commons.codec.binary.Hex; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - * Utility class to sign messages using HMAC-SHA256. - */ -public class HmacSHA256Signer { - - /** - * Sign the given message using the given secret. - * @param message message to sign - * @param secret secret key - * @return a signed message - */ - public static String sign(String message, String secret) { - try { - Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); - SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); - sha256_HMAC.init(secretKeySpec); - return new String(Hex.encodeHex(sha256_HMAC.doFinal(message.getBytes()))); - } catch (Exception e) { - throw new RuntimeException("Unable to sign message.", e); - } - } -} +package com.binance.api.client.security; + +import org.apache.commons.codec.binary.Hex; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * Utility class to sign messages using HMAC-SHA256. + */ +public class HmacSHA256Signer { + + /** + * Sign the given message using the given secret. + * @param message message to sign + * @param secret secret key + * @return a signed message + */ + public static String sign(String message, String secret) { + try { + Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); + sha256_HMAC.init(secretKeySpec); + return new String(Hex.encodeHex(sha256_HMAC.doFinal(message.getBytes()))); + } catch (Exception e) { + throw new RuntimeException("Unable to sign message.", e); + } + } +} diff --git a/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java b/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java old mode 100644 new mode 100755 index d003a8d94..62d100ef2 --- a/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java +++ b/src/test/java/com/binance/api/client/constant/BinanceApiConstantsTest.java @@ -1,81 +1,81 @@ -package com.binance.api.client.constant; - -import com.binance.api.client.domain.market.Candlestick; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * @see BinanceApiConstants - */ -public class BinanceApiConstantsTest { - - private static String candlestickRaw; - private static Candlestick candlestick; - private static ToStringStyle DEFAULT_TO_STRING_BUILDER_STYLE; - - public BinanceApiConstantsTest() { - } - - @BeforeClass - public static void setUpClass() { - - DEFAULT_TO_STRING_BUILDER_STYLE = BinanceApiConstants.TO_STRING_BUILDER_STYLE; - - candlestickRaw = "[\n" - + " 1499040000000,\n" - + " \"0.01634790\",\n" - + " \"0.80000000\",\n" - + " \"0.01575800\",\n" - + " \"0.01577100\",\n" - + " \"148976.11427815\",\n" - + " 1499644799999,\n" - + " \"2434.19055334\",\n" - + " 308,\n" - + " \"1756.87402397\",\n" - + " \"28.46694368\",\n" - + " \"17928899.62484339\"\n" - + " ]"; - ObjectMapper mapper = new ObjectMapper(); - - try { - candlestick = mapper.readValue(candlestickRaw, Candlestick.class); - } catch (IOException e) { - fail(); - } - } - - @AfterClass - public static void tearDownClass() { - BinanceApiConstants.TO_STRING_BUILDER_STYLE = DEFAULT_TO_STRING_BUILDER_STYLE; - } - - @Test - public void testToStringBuilderStyleChange() { - String binaceApiDefaultStyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; - assertEquals(candlestick.toString(), binaceApiDefaultStyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.JSON_STYLE; - String jsonSyle = "{\"openTime\":1499040000000,\"open\":\"0.01634790\",\"high\":\"0.80000000\",\"low\":\"0.01575800\",\"close\":\"0.01577100\",\"volume\":\"148976.11427815\",\"closeTime\":1499644799999,\"quoteAssetVolume\":\"2434.19055334\",\"numberOfTrades\":308,\"takerBuyBaseAssetVolume\":\"1756.87402397\",\"takerBuyQuoteAssetVolume\":\"28.46694368\"}"; - assertEquals(candlestick.toString(), jsonSyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.NO_CLASS_NAME_STYLE; - String noClassNameSyle = "[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; - assertEquals(candlestick.toString(), noClassNameSyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; - String shortPrefixSyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; - assertEquals(candlestick.toString(), shortPrefixSyle); - - BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SIMPLE_STYLE; - String simpleSyle = "1499040000000,0.01634790,0.80000000,0.01575800,0.01577100,148976.11427815,1499644799999,2434.19055334,308,1756.87402397,28.46694368"; - assertEquals(candlestick.toString(), simpleSyle); - } +package com.binance.api.client.constant; + +import com.binance.api.client.domain.market.Candlestick; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * @see BinanceApiConstants + */ +public class BinanceApiConstantsTest { + + private static String candlestickRaw; + private static Candlestick candlestick; + private static ToStringStyle DEFAULT_TO_STRING_BUILDER_STYLE; + + public BinanceApiConstantsTest() { + } + + @BeforeClass + public static void setUpClass() { + + DEFAULT_TO_STRING_BUILDER_STYLE = BinanceApiConstants.TO_STRING_BUILDER_STYLE; + + candlestickRaw = "[\n" + + " 1499040000000,\n" + + " \"0.01634790\",\n" + + " \"0.80000000\",\n" + + " \"0.01575800\",\n" + + " \"0.01577100\",\n" + + " \"148976.11427815\",\n" + + " 1499644799999,\n" + + " \"2434.19055334\",\n" + + " 308,\n" + + " \"1756.87402397\",\n" + + " \"28.46694368\",\n" + + " \"17928899.62484339\"\n" + + " ]"; + ObjectMapper mapper = new ObjectMapper(); + + try { + candlestick = mapper.readValue(candlestickRaw, Candlestick.class); + } catch (IOException e) { + fail(); + } + } + + @AfterClass + public static void tearDownClass() { + BinanceApiConstants.TO_STRING_BUILDER_STYLE = DEFAULT_TO_STRING_BUILDER_STYLE; + } + + @Test + public void testToStringBuilderStyleChange() { + String binaceApiDefaultStyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; + assertEquals(candlestick.toString(), binaceApiDefaultStyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.JSON_STYLE; + String jsonSyle = "{\"openTime\":1499040000000,\"open\":\"0.01634790\",\"high\":\"0.80000000\",\"low\":\"0.01575800\",\"close\":\"0.01577100\",\"volume\":\"148976.11427815\",\"closeTime\":1499644799999,\"quoteAssetVolume\":\"2434.19055334\",\"numberOfTrades\":308,\"takerBuyBaseAssetVolume\":\"1756.87402397\",\"takerBuyQuoteAssetVolume\":\"28.46694368\"}"; + assertEquals(candlestick.toString(), jsonSyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.NO_CLASS_NAME_STYLE; + String noClassNameSyle = "[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; + assertEquals(candlestick.toString(), noClassNameSyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SHORT_PREFIX_STYLE; + String shortPrefixSyle = "Candlestick[openTime=1499040000000,open=0.01634790,high=0.80000000,low=0.01575800,close=0.01577100,volume=148976.11427815,closeTime=1499644799999,quoteAssetVolume=2434.19055334,numberOfTrades=308,takerBuyBaseAssetVolume=1756.87402397,takerBuyQuoteAssetVolume=28.46694368]"; + assertEquals(candlestick.toString(), shortPrefixSyle); + + BinanceApiConstants.TO_STRING_BUILDER_STYLE = ToStringStyle.SIMPLE_STYLE; + String simpleSyle = "1499040000000,0.01634790,0.80000000,0.01575800,0.01577100,148976.11427815,1499644799999,2434.19055334,308,1756.87402397,28.46694368"; + assertEquals(candlestick.toString(), simpleSyle); + } } \ No newline at end of file diff --git a/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java b/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java old mode 100644 new mode 100755 index 277a86162..f65e5eefe --- a/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java +++ b/src/test/java/com/binance/api/client/domain/account/NewOrderResponseTest.java @@ -1,49 +1,49 @@ -package com.binance.api.client.domain.account; - -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * @see NewOrderResponse - */ -public class NewOrderResponseTest { - - private NewOrderResponse newOrderResponse; - private Trade trade; - - @Before - public void setUp() { - newOrderResponse = new NewOrderResponse(); - trade = new Trade(); - trade.setId(123L); - } - - @Test - public void shouldHandleToStringWithNullFills() { - assertThat(newOrderResponse.toString(), containsString(",fills=")); - } - - @Test - public void shouldHandleToStringWithNoFills() { - newOrderResponse.setFills(Collections.emptyList()); - assertThat(newOrderResponse.toString(), containsString(",fills=")); - } - - @Test - public void shouldHandleToStringWithFills() { - newOrderResponse.setFills(trades(trade)); - assertThat(newOrderResponse.toString(), containsString(",fills=Trade[id=123,")); - } - - private static List trades(final Trade... trades) { - return Arrays.asList(trades); - } +package com.binance.api.client.domain.account; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @see NewOrderResponse + */ +public class NewOrderResponseTest { + + private NewOrderResponse newOrderResponse; + private Trade trade; + + @Before + public void setUp() { + newOrderResponse = new NewOrderResponse(); + trade = new Trade(); + trade.setId(123L); + } + + @Test + public void shouldHandleToStringWithNullFills() { + assertThat(newOrderResponse.toString(), containsString(",fills=")); + } + + @Test + public void shouldHandleToStringWithNoFills() { + newOrderResponse.setFills(Collections.emptyList()); + assertThat(newOrderResponse.toString(), containsString(",fills=")); + } + + @Test + public void shouldHandleToStringWithFills() { + newOrderResponse.setFills(trades(trade)); + assertThat(newOrderResponse.toString(), containsString(",fills=Trade[id=123,")); + } + + private static List trades(final Trade... trades) { + return Arrays.asList(trades); + } } \ No newline at end of file diff --git a/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java b/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java old mode 100644 new mode 100755 index 133c1ebba..d0a99bf85 --- a/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/account/WithdrawHistoryDeserializerTest.java @@ -1,44 +1,44 @@ -package com.binance.api.domain.account; - -import com.binance.api.client.domain.account.Withdraw; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.util.List; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; -import static junit.framework.TestCase.fail; - -/** - * Test deserialization of a withdraw/deposit history. - */ -public class WithdrawHistoryDeserializerTest { - - @Test - public void testWithdrawHistoryDeserialziation() { - String withdrawHistoryJson = "{\"withdrawList\":\n" + - "[{\"amount\":0.1,\"address\":\"0x456\",\"successTime\":\"2017-10-13 21:20:09\",\n" + - "\"txId\":\"0x123\",\"id\":\"1\",\"asset\":\"ETH\",\"applyTime\":\"2017-10-13 20:59:38\",\"userId\":\"1\",\"status\":6}],\n" + - "\"success\":true}"; - ObjectMapper mapper = new ObjectMapper(); - try { - WithdrawHistory withdrawHistory = mapper.readValue(withdrawHistoryJson, WithdrawHistory.class); - assertTrue(withdrawHistory.isSuccess()); - List withdrawList = withdrawHistory.getWithdrawList(); - assertEquals(withdrawHistory.getWithdrawList().size(), 1); - Withdraw withdraw = withdrawList.get(0); - assertEquals(withdraw.getAmount(), "0.1"); - assertEquals(withdraw.getAddress(), "0x456"); - assertEquals(withdraw.getAsset(), "ETH"); - assertEquals(withdraw.getApplyTime(), "2017-10-13 20:59:38"); - assertEquals(withdraw.getSuccessTime(), "2017-10-13 21:20:09"); - assertEquals(withdraw.getTxId(), "0x123"); - assertEquals(withdraw.getId(), "1"); - } catch (IOException e) { - fail(e.getMessage()); - } - } -} +package com.binance.api.domain.account; + +import com.binance.api.client.domain.account.Withdraw; +import com.binance.api.client.domain.account.WithdrawHistory; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertTrue; +import static junit.framework.TestCase.fail; + +/** + * Test deserialization of a withdraw/deposit history. + */ +public class WithdrawHistoryDeserializerTest { + + @Test + public void testWithdrawHistoryDeserialziation() { + String withdrawHistoryJson = "{\"withdrawList\":\n" + + "[{\"amount\":0.1,\"address\":\"0x456\",\"successTime\":\"2017-10-13 21:20:09\",\n" + + "\"txId\":\"0x123\",\"id\":\"1\",\"asset\":\"ETH\",\"applyTime\":\"2017-10-13 20:59:38\",\"userId\":\"1\",\"status\":6}],\n" + + "\"success\":true}"; + ObjectMapper mapper = new ObjectMapper(); + try { + WithdrawHistory withdrawHistory = mapper.readValue(withdrawHistoryJson, WithdrawHistory.class); + assertTrue(withdrawHistory.isSuccess()); + List withdrawList = withdrawHistory.getWithdrawList(); + assertEquals(withdrawHistory.getWithdrawList().size(), 1); + Withdraw withdraw = withdrawList.get(0); + assertEquals(withdraw.getAmount(), "0.1"); + assertEquals(withdraw.getAddress(), "0x456"); + assertEquals(withdraw.getAsset(), "ETH"); + assertEquals(withdraw.getApplyTime(), "2017-10-13 20:59:38"); + assertEquals(withdraw.getSuccessTime(), "2017-10-13 21:20:09"); + assertEquals(withdraw.getTxId(), "0x123"); + assertEquals(withdraw.getId(), "1"); + } catch (IOException e) { + fail(e.getMessage()); + } + } +} diff --git a/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java b/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java old mode 100644 new mode 100755 index f4b01af40..8f7e40f43 --- a/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/event/CandlestickEventDeserializerTest.java @@ -1,68 +1,68 @@ -package com.binance.api.domain.event; - -import com.binance.api.client.domain.event.CandlestickEvent; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Tests that JSON responses from ta candlestick event are converted to the appropriate CandlestickEvent object. - */ -public class CandlestickEventDeserializerTest { - - @Test - public void testCandlestickEventDeserializer() { - String candlestickEventJson = "{\n" + - " \"e\": \"kline\",\n" + - " \"E\": 1,\n" + - " \"s\": \"ETHBTC\",\n" + - " \"k\": {\n" + - " \"t\": 1499404860000,\n" + - " \"T\": 1499404919999,\n" + - " \"s\": \"ETHBTC\", \n" + - " \"i\": \"1m\",\n" + - " \"f\": 77462, \n" + - " \"L\": 77465, \n" + - " \"o\": \"0.10278577\", \n" + - " \"c\": \"0.10278645\", \n" + - " \"h\": \"0.10278712\", \n" + - " \"l\": \"0.10278518\", \n" + - " \"v\": \"17.47929838\", \n" + - " \"n\": 4, \n" + - " \"x\": false, \n" + - " \"q\": \"1.79662878\", \n" + - " \"V\": \"2.34879839\", \n" + - " \"Q\": \"0.24142166\", \n" + - " \"B\": \"13279784.01349473\"\n" + - " }}"; - ObjectMapper mapper = new ObjectMapper(); - try { - CandlestickEvent candlestickEvent = mapper.readValue(candlestickEventJson, CandlestickEvent.class); - assertEquals(candlestickEvent.getEventType(), "kline"); - assertEquals(candlestickEvent.getEventTime(), 1L); - assertEquals(candlestickEvent.getSymbol(), "ETHBTC"); - - assertEquals((long)candlestickEvent.getOpenTime(), 1499404860000L); - assertEquals(candlestickEvent.getOpen(), "0.10278577"); - assertEquals(candlestickEvent.getHigh(), "0.10278712"); - assertEquals(candlestickEvent.getLow(), "0.10278518"); - assertEquals(candlestickEvent.getClose(), "0.10278645"); - assertEquals(candlestickEvent.getVolume(), "17.47929838"); - assertEquals((long)candlestickEvent.getCloseTime(), 1499404919999L); - assertEquals(candlestickEvent.getIntervalId(), "1m"); - assertEquals((long)candlestickEvent.getFirstTradeId(), 77462L); - assertEquals((long)candlestickEvent.getLastTradeId(), 77465L); - assertEquals(candlestickEvent.getQuoteAssetVolume(), "1.79662878"); - assertEquals((long)candlestickEvent.getNumberOfTrades(), 4L); - assertEquals(candlestickEvent.getTakerBuyBaseAssetVolume(), "2.34879839"); - assertEquals(candlestickEvent.getTakerBuyQuoteAssetVolume(), "0.24142166"); - assertEquals(candlestickEvent.getBarFinal(), false); - } catch (IOException e) { - fail(e.getMessage()); - } - } -} +package com.binance.api.domain.event; + +import com.binance.api.client.domain.event.CandlestickEvent; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Tests that JSON responses from ta candlestick event are converted to the appropriate CandlestickEvent object. + */ +public class CandlestickEventDeserializerTest { + + @Test + public void testCandlestickEventDeserializer() { + String candlestickEventJson = "{\n" + + " \"e\": \"kline\",\n" + + " \"E\": 1,\n" + + " \"s\": \"ETHBTC\",\n" + + " \"k\": {\n" + + " \"t\": 1499404860000,\n" + + " \"T\": 1499404919999,\n" + + " \"s\": \"ETHBTC\", \n" + + " \"i\": \"1m\",\n" + + " \"f\": 77462, \n" + + " \"L\": 77465, \n" + + " \"o\": \"0.10278577\", \n" + + " \"c\": \"0.10278645\", \n" + + " \"h\": \"0.10278712\", \n" + + " \"l\": \"0.10278518\", \n" + + " \"v\": \"17.47929838\", \n" + + " \"n\": 4, \n" + + " \"x\": false, \n" + + " \"q\": \"1.79662878\", \n" + + " \"V\": \"2.34879839\", \n" + + " \"Q\": \"0.24142166\", \n" + + " \"B\": \"13279784.01349473\"\n" + + " }}"; + ObjectMapper mapper = new ObjectMapper(); + try { + CandlestickEvent candlestickEvent = mapper.readValue(candlestickEventJson, CandlestickEvent.class); + assertEquals(candlestickEvent.getEventType(), "kline"); + assertEquals(candlestickEvent.getEventTime(), 1L); + assertEquals(candlestickEvent.getSymbol(), "ETHBTC"); + + assertEquals((long)candlestickEvent.getOpenTime(), 1499404860000L); + assertEquals(candlestickEvent.getOpen(), "0.10278577"); + assertEquals(candlestickEvent.getHigh(), "0.10278712"); + assertEquals(candlestickEvent.getLow(), "0.10278518"); + assertEquals(candlestickEvent.getClose(), "0.10278645"); + assertEquals(candlestickEvent.getVolume(), "17.47929838"); + assertEquals((long)candlestickEvent.getCloseTime(), 1499404919999L); + assertEquals(candlestickEvent.getIntervalId(), "1m"); + assertEquals((long)candlestickEvent.getFirstTradeId(), 77462L); + assertEquals((long)candlestickEvent.getLastTradeId(), 77465L); + assertEquals(candlestickEvent.getQuoteAssetVolume(), "1.79662878"); + assertEquals((long)candlestickEvent.getNumberOfTrades(), 4L); + assertEquals(candlestickEvent.getTakerBuyBaseAssetVolume(), "2.34879839"); + assertEquals(candlestickEvent.getTakerBuyQuoteAssetVolume(), "0.24142166"); + assertEquals(candlestickEvent.getBarFinal(), false); + } catch (IOException e) { + fail(e.getMessage()); + } + } +} diff --git a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java old mode 100644 new mode 100755 index 23b1ced98..a50d31221 --- a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java @@ -1,81 +1,81 @@ -package com.binance.api.domain.event; - - -import com.binance.api.client.domain.account.AssetBalance; -import com.binance.api.client.domain.ExecutionType; -import com.binance.api.client.domain.OrderRejectReason; -import com.binance.api.client.domain.OrderSide; -import com.binance.api.client.domain.OrderStatus; -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.event.AccountUpdateEvent; -import com.binance.api.client.domain.event.OrderTradeUpdateEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Tests that JSON responses from the stream API are converted to the appropriate object. - */ -public class UserDataUpdateEventDeserializerTest { - - @Test - public void testAccountUpdateEventDeserializer() { - final String accountUpdateJson = "{\"e\":\"outboundAccountInfo\",\"E\":1,\"m\":10,\"t\":10,\"b\":0,\"s\":0,\"T\":true,\"W\":true,\"D\":true,\"B\":[{\"a\":\"BTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETH\",\"f\":\"0.10000000\",\"l\":\"0.00000000\"},{\"a\":\"BNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NEO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"123\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"456\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"QTUM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"EOS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"GAS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BTM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"USDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HSR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OAX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"DNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MCO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ELC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PAY\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OMG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"WTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"YOYO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LLT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FID\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNGLS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STRAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BQX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FUN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"KNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"XVG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"IOTA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LINK\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CVC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"REP\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CTR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MDA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTL\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SALT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NULS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SUB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTH\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ADX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PIX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ENG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZEC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"}]}"; - ObjectMapper mapper = new ObjectMapper(); - try { - UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(accountUpdateJson, UserDataUpdateEvent.class); - assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "outboundAccountInfo"); - assertEquals(userDataUpdateEvent.getEventTime(), 1L); - AccountUpdateEvent accountUpdateEvent = userDataUpdateEvent.getAccountUpdateEvent(); - for (AssetBalance assetBalance : accountUpdateEvent.getBalances()) { - if ("ETH".equals(assetBalance.getAsset())) { - assertEquals(assetBalance.getFree(), "0.10000000"); - } else { - assertEquals(assetBalance.getFree(), "0.00000000"); - } - assertEquals(assetBalance.getLocked(), "0.00000000"); - } - } catch (IOException e) { - fail(); - } - } - - @Test - public void testOrderUpdateEventDeserializer() { - final String orderUpdateEventJson = "{\"e\":\"executionReport\",\"E\":1,\"s\":\"NEOETH\",\"c\":\"XXX\",\"S\":\"BUY\",\"o\":\"LIMIT\",\"f\":\"GTC\",\"q\":\"1000.00000000\",\"p\":\"0.00010000\",\"P\":\"0.00000000\",\"F\":\"0.00000000\",\"g\":-1,\"C\":\"5yairWLqfzbusOUdPyG712\",\"x\":\"CANCELED\",\"X\":\"CANCELED\",\"r\":\"NONE\",\"i\":123456,\"l\":\"0.00000000\",\"z\":\"0.00000000\",\"L\":\"0.00000000\",\"n\":\"0\",\"N\":null,\"T\":1,\"t\":-1,\"I\":1,\"w\":false,\"m\":false,\"M\":false}"; - ObjectMapper mapper = new ObjectMapper(); - try { - UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(orderUpdateEventJson, UserDataUpdateEvent.class); - assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "executionReport"); - assertEquals(userDataUpdateEvent.getEventTime(), 1L); - - OrderTradeUpdateEvent orderTradeUpdateEvent = userDataUpdateEvent.getOrderTradeUpdateEvent(); - assertEquals(orderTradeUpdateEvent.getSymbol(), "NEOETH"); - assertEquals(orderTradeUpdateEvent.getNewClientOrderId(), "XXX"); - - assertEquals(orderTradeUpdateEvent.getSide(), OrderSide.BUY); - assertEquals(orderTradeUpdateEvent.getType(), OrderType.LIMIT); - assertEquals(orderTradeUpdateEvent.getTimeInForce(), TimeInForce.GTC); - - assertEquals(orderTradeUpdateEvent.getOriginalQuantity(), "1000.00000000"); - assertEquals(orderTradeUpdateEvent.getPrice(), "0.00010000"); - - assertEquals(orderTradeUpdateEvent.getExecutionType(), ExecutionType.CANCELED); - assertEquals(orderTradeUpdateEvent.getOrderStatus(), OrderStatus.CANCELED); - assertEquals(orderTradeUpdateEvent.getOrderRejectReason(), OrderRejectReason.NONE); - - assertEquals(orderTradeUpdateEvent.getOrderId(), new Long(123456)); - assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), new Long(1)); - } catch (IOException e) { - fail(); - } - } - -} - +package com.binance.api.domain.event; + + +import com.binance.api.client.domain.account.AssetBalance; +import com.binance.api.client.domain.ExecutionType; +import com.binance.api.client.domain.OrderRejectReason; +import com.binance.api.client.domain.OrderSide; +import com.binance.api.client.domain.OrderStatus; +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.event.AccountUpdateEvent; +import com.binance.api.client.domain.event.OrderTradeUpdateEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Tests that JSON responses from the stream API are converted to the appropriate object. + */ +public class UserDataUpdateEventDeserializerTest { + + @Test + public void testAccountUpdateEventDeserializer() { + final String accountUpdateJson = "{\"e\":\"outboundAccountInfo\",\"E\":1,\"m\":10,\"t\":10,\"b\":0,\"s\":0,\"T\":true,\"W\":true,\"D\":true,\"B\":[{\"a\":\"BTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETH\",\"f\":\"0.10000000\",\"l\":\"0.00000000\"},{\"a\":\"BNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NEO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"123\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"456\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"QTUM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"EOS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"GAS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BTM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"USDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HCC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"HSR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OAX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"DNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MCO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ICN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ELC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PAY\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"OMG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"WTC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"YOYO\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LRC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LLT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TRX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FID\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNGLS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STRAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"BQX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"FUN\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"KNC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CDT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"XVG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"IOTA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SNM\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"LINK\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CVC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"TNT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"REP\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CTR\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MDA\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTL\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SALT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"NULS\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"SUB\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"STX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"MTH\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"CAT\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ADX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"PIX\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ETC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ENG\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"},{\"a\":\"ZEC\",\"f\":\"0.00000000\",\"l\":\"0.00000000\"}]}"; + ObjectMapper mapper = new ObjectMapper(); + try { + UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(accountUpdateJson, UserDataUpdateEvent.class); + assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "outboundAccountInfo"); + assertEquals(userDataUpdateEvent.getEventTime(), 1L); + AccountUpdateEvent accountUpdateEvent = userDataUpdateEvent.getAccountUpdateEvent(); + for (AssetBalance assetBalance : accountUpdateEvent.getBalances()) { + if ("ETH".equals(assetBalance.getAsset())) { + assertEquals(assetBalance.getFree(), "0.10000000"); + } else { + assertEquals(assetBalance.getFree(), "0.00000000"); + } + assertEquals(assetBalance.getLocked(), "0.00000000"); + } + } catch (IOException e) { + fail(); + } + } + + @Test + public void testOrderUpdateEventDeserializer() { + final String orderUpdateEventJson = "{\"e\":\"executionReport\",\"E\":1,\"s\":\"NEOETH\",\"c\":\"XXX\",\"S\":\"BUY\",\"o\":\"LIMIT\",\"f\":\"GTC\",\"q\":\"1000.00000000\",\"p\":\"0.00010000\",\"P\":\"0.00000000\",\"F\":\"0.00000000\",\"g\":-1,\"C\":\"5yairWLqfzbusOUdPyG712\",\"x\":\"CANCELED\",\"X\":\"CANCELED\",\"r\":\"NONE\",\"i\":123456,\"l\":\"0.00000000\",\"z\":\"0.00000000\",\"L\":\"0.00000000\",\"n\":\"0\",\"N\":null,\"T\":1,\"t\":-1,\"I\":1,\"w\":false,\"m\":false,\"M\":false}"; + ObjectMapper mapper = new ObjectMapper(); + try { + UserDataUpdateEvent userDataUpdateEvent = mapper.readValue(orderUpdateEventJson, UserDataUpdateEvent.class); + assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "executionReport"); + assertEquals(userDataUpdateEvent.getEventTime(), 1L); + + OrderTradeUpdateEvent orderTradeUpdateEvent = userDataUpdateEvent.getOrderTradeUpdateEvent(); + assertEquals(orderTradeUpdateEvent.getSymbol(), "NEOETH"); + assertEquals(orderTradeUpdateEvent.getNewClientOrderId(), "XXX"); + + assertEquals(orderTradeUpdateEvent.getSide(), OrderSide.BUY); + assertEquals(orderTradeUpdateEvent.getType(), OrderType.LIMIT); + assertEquals(orderTradeUpdateEvent.getTimeInForce(), TimeInForce.GTC); + + assertEquals(orderTradeUpdateEvent.getOriginalQuantity(), "1000.00000000"); + assertEquals(orderTradeUpdateEvent.getPrice(), "0.00010000"); + + assertEquals(orderTradeUpdateEvent.getExecutionType(), ExecutionType.CANCELED); + assertEquals(orderTradeUpdateEvent.getOrderStatus(), OrderStatus.CANCELED); + assertEquals(orderTradeUpdateEvent.getOrderRejectReason(), OrderRejectReason.NONE); + + assertEquals(orderTradeUpdateEvent.getOrderId(), new Long(123456)); + assertEquals(orderTradeUpdateEvent.getOrderTradeTime(), new Long(1)); + } catch (IOException e) { + fail(); + } + } + +} + diff --git a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java old mode 100644 new mode 100755 index b865a8b68..94467915b --- a/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/general/ExchangeInfoDeserializerTest.java @@ -1,128 +1,128 @@ -package com.binance.api.domain.general; - -import com.binance.api.client.domain.OrderType; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.FilterType; -import com.binance.api.client.domain.general.RateLimit; -import com.binance.api.client.domain.general.RateLimitInterval; -import com.binance.api.client.domain.general.RateLimitType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; -import com.binance.api.client.domain.general.SymbolStatus; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -/** - * Test deserialization of exchange information. - */ -public class ExchangeInfoDeserializerTest { - - @Test - public void testExchangeInfoDeserialization() { - final String json = "{\n" + - " \"timezone\": \"UTC\",\n" + - " \"serverTime\": 1508631584636,\n" + - " \"rateLimits\": [{\n" + - " \"rateLimitType\": \"REQUEST_WEIGHT\",\n" + - " \"interval\": \"MINUTE\",\n" + - " \"limit\": 1200\n" + - " },\n" + - " {\n" + - " \"rateLimitType\": \"ORDERS\",\n" + - " \"interval\": \"SECOND\",\n" + - " \"limit\": 10\n" + - " },\n" + - " {\n" + - " \"rateLimitType\": \"ORDERS\",\n" + - " \"interval\": \"DAY\",\n" + - " \"limit\": 100000\n" + - " }\n" + - " ],\n" + - " \"exchangeFilters\": [],\n" + - " \"symbols\": [{\n" + - " \"symbol\": \"ETHBTC\",\n" + - " \"status\": \"TRADING\",\n" + - " \"baseAsset\": \"ETH\",\n" + - " \"baseAssetPrecision\": 8,\n" + - " \"quoteAsset\": \"BTC\",\n" + - " \"quotePrecision\": 8,\n" + - " \"orderTypes\": [\"LIMIT\", \"MARKET\"],\n" + - " \"icebergAllowed\": false,\n" + - " \"filters\": [{\n" + - " \"filterType\": \"PRICE_FILTER\",\n" + - " \"minPrice\": \"0.00000100\",\n" + - " \"maxPrice\": \"100000.00000000\",\n" + - " \"tickSize\": \"0.00000100\"\n" + - " }, {\n" + - " \"filterType\": \"LOT_SIZE\",\n" + - " \"minQty\": \"0.00100000\",\n" + - " \"maxQty\": \"100000.00000000\",\n" + - " \"stepSize\": \"0.00100000\"\n" + - " }, {\n" + - " \"filterType\": \"MIN_NOTIONAL\",\n" + - " \"minNotional\": \"0.00100000\"\n" + - " }]\n" + - " }]" + - "}"; - ObjectMapper mapper = new ObjectMapper(); - try { - ExchangeInfo exchangeInfo = mapper.readValue(json, ExchangeInfo.class); - System.out.println(exchangeInfo); - assertEquals(exchangeInfo.getTimezone(), "UTC"); - assertEquals((long)exchangeInfo.getServerTime(), 1508631584636L); - - List rateLimits = exchangeInfo.getRateLimits(); - assertEquals(rateLimits.size(), 3); - testRateLimit(rateLimits.get(0), RateLimitType.REQUEST_WEIGHT, RateLimitInterval.MINUTE, 1200); - testRateLimit(rateLimits.get(1), RateLimitType.ORDERS, RateLimitInterval.SECOND, 10); - testRateLimit(rateLimits.get(2), RateLimitType.ORDERS, RateLimitInterval.DAY, 100000); - - List symbols = exchangeInfo.getSymbols(); - assertEquals(symbols.size(), 1); - SymbolInfo symbolInfo = symbols.get(0); - assertEquals(symbolInfo.getSymbol(), "ETHBTC"); - assertEquals(symbolInfo.getStatus(), SymbolStatus.TRADING); - assertEquals(symbolInfo.getBaseAsset(), "ETH"); - assertEquals((int)symbolInfo.getBaseAssetPrecision(), 8); - assertEquals(symbolInfo.getQuoteAsset(), "BTC"); - assertEquals((int)symbolInfo.getQuotePrecision(), 8); - assertEquals(symbolInfo.getOrderTypes(), Arrays.asList(OrderType.LIMIT, OrderType.MARKET)); - assertFalse(symbolInfo.isIcebergAllowed()); - - List symbolFilters = symbolInfo.getFilters(); - assertEquals(symbolFilters.size(), 3); - - SymbolFilter priceFilter = symbolFilters.get(0); - assertEquals(priceFilter.getFilterType(), FilterType.PRICE_FILTER); - assertEquals(priceFilter.getMinPrice(), "0.00000100"); - assertEquals(priceFilter.getMaxPrice(), "100000.00000000"); - assertEquals(priceFilter.getTickSize(), "0.00000100"); - - SymbolFilter lotSizeFilter = symbolFilters.get(1); - assertEquals(lotSizeFilter.getFilterType(), FilterType.LOT_SIZE); - assertEquals(lotSizeFilter.getMinQty(), "0.00100000"); - assertEquals(lotSizeFilter.getMaxQty(), "100000.00000000"); - assertEquals(lotSizeFilter.getStepSize(), "0.00100000"); - - SymbolFilter minNotionalFilter = symbolFilters.get(2); - assertEquals(minNotionalFilter.getFilterType(), FilterType.MIN_NOTIONAL); - assertEquals(minNotionalFilter.getMinNotional(), "0.00100000"); - } catch (IOException e) { - fail(); - } - } - - private void testRateLimit(RateLimit rateLimit, RateLimitType expectedRateLimitType, RateLimitInterval expectedInterval, int expectedLimit) { - assertEquals(rateLimit.getRateLimitType(), expectedRateLimitType); - assertEquals(rateLimit.getInterval(), expectedInterval); - assertEquals((long)rateLimit.getLimit(), expectedLimit); - } -} +package com.binance.api.domain.general; + +import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.FilterType; +import com.binance.api.client.domain.general.RateLimit; +import com.binance.api.client.domain.general.RateLimitInterval; +import com.binance.api.client.domain.general.RateLimitType; +import com.binance.api.client.domain.general.SymbolFilter; +import com.binance.api.client.domain.general.SymbolInfo; +import com.binance.api.client.domain.general.SymbolStatus; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +/** + * Test deserialization of exchange information. + */ +public class ExchangeInfoDeserializerTest { + + @Test + public void testExchangeInfoDeserialization() { + final String json = "{\n" + + " \"timezone\": \"UTC\",\n" + + " \"serverTime\": 1508631584636,\n" + + " \"rateLimits\": [{\n" + + " \"rateLimitType\": \"REQUEST_WEIGHT\",\n" + + " \"interval\": \"MINUTE\",\n" + + " \"limit\": 1200\n" + + " },\n" + + " {\n" + + " \"rateLimitType\": \"ORDERS\",\n" + + " \"interval\": \"SECOND\",\n" + + " \"limit\": 10\n" + + " },\n" + + " {\n" + + " \"rateLimitType\": \"ORDERS\",\n" + + " \"interval\": \"DAY\",\n" + + " \"limit\": 100000\n" + + " }\n" + + " ],\n" + + " \"exchangeFilters\": [],\n" + + " \"symbols\": [{\n" + + " \"symbol\": \"ETHBTC\",\n" + + " \"status\": \"TRADING\",\n" + + " \"baseAsset\": \"ETH\",\n" + + " \"baseAssetPrecision\": 8,\n" + + " \"quoteAsset\": \"BTC\",\n" + + " \"quotePrecision\": 8,\n" + + " \"orderTypes\": [\"LIMIT\", \"MARKET\"],\n" + + " \"icebergAllowed\": false,\n" + + " \"filters\": [{\n" + + " \"filterType\": \"PRICE_FILTER\",\n" + + " \"minPrice\": \"0.00000100\",\n" + + " \"maxPrice\": \"100000.00000000\",\n" + + " \"tickSize\": \"0.00000100\"\n" + + " }, {\n" + + " \"filterType\": \"LOT_SIZE\",\n" + + " \"minQty\": \"0.00100000\",\n" + + " \"maxQty\": \"100000.00000000\",\n" + + " \"stepSize\": \"0.00100000\"\n" + + " }, {\n" + + " \"filterType\": \"MIN_NOTIONAL\",\n" + + " \"minNotional\": \"0.00100000\"\n" + + " }]\n" + + " }]" + + "}"; + ObjectMapper mapper = new ObjectMapper(); + try { + ExchangeInfo exchangeInfo = mapper.readValue(json, ExchangeInfo.class); + System.out.println(exchangeInfo); + assertEquals(exchangeInfo.getTimezone(), "UTC"); + assertEquals((long)exchangeInfo.getServerTime(), 1508631584636L); + + List rateLimits = exchangeInfo.getRateLimits(); + assertEquals(rateLimits.size(), 3); + testRateLimit(rateLimits.get(0), RateLimitType.REQUEST_WEIGHT, RateLimitInterval.MINUTE, 1200); + testRateLimit(rateLimits.get(1), RateLimitType.ORDERS, RateLimitInterval.SECOND, 10); + testRateLimit(rateLimits.get(2), RateLimitType.ORDERS, RateLimitInterval.DAY, 100000); + + List symbols = exchangeInfo.getSymbols(); + assertEquals(symbols.size(), 1); + SymbolInfo symbolInfo = symbols.get(0); + assertEquals(symbolInfo.getSymbol(), "ETHBTC"); + assertEquals(symbolInfo.getStatus(), SymbolStatus.TRADING); + assertEquals(symbolInfo.getBaseAsset(), "ETH"); + assertEquals((int)symbolInfo.getBaseAssetPrecision(), 8); + assertEquals(symbolInfo.getQuoteAsset(), "BTC"); + assertEquals((int)symbolInfo.getQuotePrecision(), 8); + assertEquals(symbolInfo.getOrderTypes(), Arrays.asList(OrderType.LIMIT, OrderType.MARKET)); + assertFalse(symbolInfo.isIcebergAllowed()); + + List symbolFilters = symbolInfo.getFilters(); + assertEquals(symbolFilters.size(), 3); + + SymbolFilter priceFilter = symbolFilters.get(0); + assertEquals(priceFilter.getFilterType(), FilterType.PRICE_FILTER); + assertEquals(priceFilter.getMinPrice(), "0.00000100"); + assertEquals(priceFilter.getMaxPrice(), "100000.00000000"); + assertEquals(priceFilter.getTickSize(), "0.00000100"); + + SymbolFilter lotSizeFilter = symbolFilters.get(1); + assertEquals(lotSizeFilter.getFilterType(), FilterType.LOT_SIZE); + assertEquals(lotSizeFilter.getMinQty(), "0.00100000"); + assertEquals(lotSizeFilter.getMaxQty(), "100000.00000000"); + assertEquals(lotSizeFilter.getStepSize(), "0.00100000"); + + SymbolFilter minNotionalFilter = symbolFilters.get(2); + assertEquals(minNotionalFilter.getFilterType(), FilterType.MIN_NOTIONAL); + assertEquals(minNotionalFilter.getMinNotional(), "0.00100000"); + } catch (IOException e) { + fail(); + } + } + + private void testRateLimit(RateLimit rateLimit, RateLimitType expectedRateLimitType, RateLimitInterval expectedInterval, int expectedLimit) { + assertEquals(rateLimit.getRateLimitType(), expectedRateLimitType); + assertEquals(rateLimit.getInterval(), expectedInterval); + assertEquals((long)rateLimit.getLimit(), expectedLimit); + } +} diff --git a/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java b/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java old mode 100644 new mode 100755 index d59bef8ac..5f6146c9d --- a/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/market/CandlestickDeserializerTest.java @@ -1,51 +1,51 @@ -package com.binance.api.domain.market; - -import com.binance.api.client.domain.market.Candlestick; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Tests the adequate deserialization of candlestick JSON information. - */ -public class CandlestickDeserializerTest { - - @Test - public void testCandlestickDeserializerTest() { - final String candlestickJson = "[\n" + - " 1499040000000,\n" + - " \"0.01634790\",\n" + - " \"0.80000000\",\n" + - " \"0.01575800\",\n" + - " \"0.01577100\",\n" + - " \"148976.11427815\",\n" + - " 1499644799999,\n" + - " \"2434.19055334\",\n" + - " 308,\n" + - " \"1756.87402397\",\n" + - " \"28.46694368\",\n" + - " \"17928899.62484339\"\n" + - " ]"; - ObjectMapper mapper = new ObjectMapper(); - try { - Candlestick candlestick = mapper.readValue(candlestickJson, Candlestick.class); - assertEquals((long)candlestick.getOpenTime(), 1499040000000L); - assertEquals(candlestick.getOpen(), "0.01634790"); - assertEquals(candlestick.getHigh(), "0.80000000"); - assertEquals(candlestick.getLow(), "0.01575800"); - assertEquals(candlestick.getClose(), "0.01577100"); - assertEquals(candlestick.getVolume(), "148976.11427815"); - assertEquals((long)candlestick.getCloseTime(), 1499644799999L); - assertEquals(candlestick.getQuoteAssetVolume(), "2434.19055334"); - assertEquals((long)candlestick.getNumberOfTrades(), 308L); - assertEquals(candlestick.getTakerBuyBaseAssetVolume(), "1756.87402397"); - assertEquals(candlestick.getTakerBuyQuoteAssetVolume(), "28.46694368"); - } catch (IOException e) { - fail(); - } - } -} +package com.binance.api.domain.market; + +import com.binance.api.client.domain.market.Candlestick; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Tests the adequate deserialization of candlestick JSON information. + */ +public class CandlestickDeserializerTest { + + @Test + public void testCandlestickDeserializerTest() { + final String candlestickJson = "[\n" + + " 1499040000000,\n" + + " \"0.01634790\",\n" + + " \"0.80000000\",\n" + + " \"0.01575800\",\n" + + " \"0.01577100\",\n" + + " \"148976.11427815\",\n" + + " 1499644799999,\n" + + " \"2434.19055334\",\n" + + " 308,\n" + + " \"1756.87402397\",\n" + + " \"28.46694368\",\n" + + " \"17928899.62484339\"\n" + + " ]"; + ObjectMapper mapper = new ObjectMapper(); + try { + Candlestick candlestick = mapper.readValue(candlestickJson, Candlestick.class); + assertEquals((long)candlestick.getOpenTime(), 1499040000000L); + assertEquals(candlestick.getOpen(), "0.01634790"); + assertEquals(candlestick.getHigh(), "0.80000000"); + assertEquals(candlestick.getLow(), "0.01575800"); + assertEquals(candlestick.getClose(), "0.01577100"); + assertEquals(candlestick.getVolume(), "148976.11427815"); + assertEquals((long)candlestick.getCloseTime(), 1499644799999L); + assertEquals(candlestick.getQuoteAssetVolume(), "2434.19055334"); + assertEquals((long)candlestick.getNumberOfTrades(), 308L); + assertEquals(candlestick.getTakerBuyBaseAssetVolume(), "1756.87402397"); + assertEquals(candlestick.getTakerBuyQuoteAssetVolume(), "28.46694368"); + } catch (IOException e) { + fail(); + } + } +} diff --git a/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java b/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java old mode 100644 new mode 100755 index 928655379..8fcd51118 --- a/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java +++ b/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java @@ -1,81 +1,81 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.AssetBalance; - -import java.util.Map; -import java.util.TreeMap; - -import static com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType.ACCOUNT_UPDATE; - -/** - * Illustrates how to use the user data event stream to create a local cache for the balance of an account. - */ -public class AccountBalanceCacheExample { - - private final BinanceApiClientFactory clientFactory; - - /** - * Key is the symbol, and the value is the balance of that symbol on the account. - */ - private Map accountBalanceCache; - - /** - * Listen key used to interact with the user data streaming API. - */ - private final String listenKey; - - public AccountBalanceCacheExample(String apiKey, String secret) { - this.clientFactory = BinanceApiClientFactory.newInstance(apiKey, secret); - this.listenKey = initializeAssetBalanceCacheAndStreamSession(); - startAccountBalanceEventStreaming(listenKey); - } - - /** - * Initializes the asset balance cache by using the REST API and starts a new user data streaming session. - * - * @return a listenKey that can be used with the user data streaming API. - */ - private String initializeAssetBalanceCacheAndStreamSession() { - BinanceApiRestClient client = clientFactory.newRestClient(); - Account account = client.getAccount(); - - this.accountBalanceCache = new TreeMap<>(); - for (AssetBalance assetBalance : account.getBalances()) { - accountBalanceCache.put(assetBalance.getAsset(), assetBalance); - } - - return client.startUserDataStream(); - } - - /** - * Begins streaming of agg trades events. - */ - private void startAccountBalanceEventStreaming(String listenKey) { - BinanceApiWebSocketClient client = clientFactory.newWebSocketClient(); - - client.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == ACCOUNT_UPDATE) { - // Override cached asset balances - for (AssetBalance assetBalance : response.getAccountUpdateEvent().getBalances()) { - accountBalanceCache.put(assetBalance.getAsset(), assetBalance); - } - System.out.println(accountBalanceCache); - } - }); - } - - /** - * @return an account balance cache, containing the balance for every asset in this account. - */ - public Map getAccountBalanceCache() { - return accountBalanceCache; - } - - public static void main(String[] args) { - new AccountBalanceCacheExample("YOUR_API_KEY", "YOUR_SECRET"); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.AssetBalance; + +import java.util.Map; +import java.util.TreeMap; + +import static com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType.ACCOUNT_UPDATE; + +/** + * Illustrates how to use the user data event stream to create a local cache for the balance of an account. + */ +public class AccountBalanceCacheExample { + + private final BinanceApiClientFactory clientFactory; + + /** + * Key is the symbol, and the value is the balance of that symbol on the account. + */ + private Map accountBalanceCache; + + /** + * Listen key used to interact with the user data streaming API. + */ + private final String listenKey; + + public AccountBalanceCacheExample(String apiKey, String secret) { + this.clientFactory = BinanceApiClientFactory.newInstance(apiKey, secret); + this.listenKey = initializeAssetBalanceCacheAndStreamSession(); + startAccountBalanceEventStreaming(listenKey); + } + + /** + * Initializes the asset balance cache by using the REST API and starts a new user data streaming session. + * + * @return a listenKey that can be used with the user data streaming API. + */ + private String initializeAssetBalanceCacheAndStreamSession() { + BinanceApiRestClient client = clientFactory.newRestClient(); + Account account = client.getAccount(); + + this.accountBalanceCache = new TreeMap<>(); + for (AssetBalance assetBalance : account.getBalances()) { + accountBalanceCache.put(assetBalance.getAsset(), assetBalance); + } + + return client.startUserDataStream(); + } + + /** + * Begins streaming of agg trades events. + */ + private void startAccountBalanceEventStreaming(String listenKey) { + BinanceApiWebSocketClient client = clientFactory.newWebSocketClient(); + + client.onUserDataUpdateEvent(listenKey, response -> { + if (response.getEventType() == ACCOUNT_UPDATE) { + // Override cached asset balances + for (AssetBalance assetBalance : response.getAccountUpdateEvent().getBalances()) { + accountBalanceCache.put(assetBalance.getAsset(), assetBalance); + } + System.out.println(accountBalanceCache); + } + }); + } + + /** + * @return an account balance cache, containing the balance for every asset in this account. + */ + public Map getAccountBalanceCache() { + return accountBalanceCache; + } + + public static void main(String[] args) { + new AccountBalanceCacheExample("YOUR_API_KEY", "YOUR_SECRET"); + } +} diff --git a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java old mode 100644 new mode 100755 index bd7d56364..72fc68c3d --- a/src/test/java/com/binance/api/examples/AccountEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExample.java @@ -1,40 +1,40 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.Trade; - -import java.util.List; - -/** - * Examples on how to get account information. - */ -public class AccountEndpointsExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiRestClient client = factory.newRestClient(); - - // Get account balances - Account account = client.getAccount(60_000L, System.currentTimeMillis()); - System.out.println(account.getBalances()); - System.out.println(account.getAssetBalance("ETH")); - - // Get list of trades - List myTrades = client.getMyTrades("NEOETH"); - System.out.println(myTrades); - - // Get withdraw history - System.out.println(client.getWithdrawHistory("ETH")); - - // Get deposit history - System.out.println(client.getDepositHistory("ETH")); - - // Get deposit address - System.out.println(client.getDepositAddress("ETH")); - - // Withdraw - client.withdraw("ETH", "0x123", "0.1", null, null); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.account.Account; +import com.binance.api.client.domain.account.Trade; + +import java.util.List; + +/** + * Examples on how to get account information. + */ +public class AccountEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiRestClient client = factory.newRestClient(); + + // Get account balances + Account account = client.getAccount(60_000L, System.currentTimeMillis()); + System.out.println(account.getBalances()); + System.out.println(account.getAssetBalance("ETH")); + + // Get list of trades + List myTrades = client.getMyTrades("NEOETH"); + System.out.println(myTrades); + + // Get withdraw history + System.out.println(client.getWithdrawHistory("ETH")); + + // Get deposit history + System.out.println(client.getDepositHistory("ETH")); + + // Get deposit address + System.out.println(client.getDepositAddress("ETH")); + + // Withdraw + client.withdraw("ETH", "0x123", "0.1", null, null); + } +} diff --git a/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java old mode 100644 new mode 100755 index 7e924fdf5..5ede0526b --- a/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/AccountEndpointsExampleAsync.java @@ -1,31 +1,31 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.account.Account; - -/** - * Examples on how to get account information. - */ -public class AccountEndpointsExampleAsync { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Get account balances (async) - client.getAccount((Account response) -> System.out.println(response.getAssetBalance("ETH"))); - - // Get list of trades (async) - client.getMyTrades("NEOETH", response -> System.out.println(response)); - - // Get withdraw history (async) - client.getWithdrawHistory("ETH", response -> System.out.println(response)); - - // Get deposit history (async) - client.getDepositHistory("ETH", response -> System.out.println(response)); - - // Withdraw (async) - client.withdraw("ETH", "0x123", "0.1", null, null, response -> {}); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.account.Account; + +/** + * Examples on how to get account information. + */ +public class AccountEndpointsExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Get account balances (async) + client.getAccount((Account response) -> System.out.println(response.getAssetBalance("ETH"))); + + // Get list of trades (async) + client.getMyTrades("NEOETH", response -> System.out.println(response)); + + // Get withdraw history (async) + client.getWithdrawHistory("ETH", response -> System.out.println(response)); + + // Get deposit history (async) + client.getDepositHistory("ETH", response -> System.out.println(response)); + + // Withdraw (async) + client.withdraw("ETH", "0x123", "0.1", null, null, response -> {}); + } +} diff --git a/src/test/java/com/binance/api/examples/AggTradesCacheExample.java b/src/test/java/com/binance/api/examples/AggTradesCacheExample.java old mode 100644 new mode 100755 index 8106ba34e..985ffe4ca --- a/src/test/java/com/binance/api/examples/AggTradesCacheExample.java +++ b/src/test/java/com/binance/api/examples/AggTradesCacheExample.java @@ -1,80 +1,80 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.market.AggTrade; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Illustrates how to use the aggTrades event stream to create a local cache of trades for a symbol. - */ -public class AggTradesCacheExample { - - /** - * Key is the aggregate trade id, and the value contains the aggregated trade data, which is - * automatically updated whenever a new agg data stream event arrives. - */ - private Map aggTradesCache; - - public AggTradesCacheExample(String symbol) { - initializeAggTradesCache(symbol); - startAggTradesEventStreaming(symbol); - } - - /** - * Initializes the aggTrades cache by using the REST API. - */ - private void initializeAggTradesCache(String symbol) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - List aggTrades = client.getAggTrades(symbol.toUpperCase()); - - this.aggTradesCache = new HashMap<>(); - for (AggTrade aggTrade : aggTrades) { - aggTradesCache.put(aggTrade.getAggregatedTradeId(), aggTrade); - } - } - - /** - * Begins streaming of agg trades events. - */ - private void startAggTradesEventStreaming(String symbol) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiWebSocketClient client = factory.newWebSocketClient(); - - client.onAggTradeEvent(symbol.toLowerCase(), response -> { - Long aggregatedTradeId = response.getAggregatedTradeId(); - AggTrade updateAggTrade = aggTradesCache.get(aggregatedTradeId); - if (updateAggTrade == null) { - // new agg trade - updateAggTrade = new AggTrade(); - } - updateAggTrade.setAggregatedTradeId(aggregatedTradeId); - updateAggTrade.setPrice(response.getPrice()); - updateAggTrade.setQuantity(response.getQuantity()); - updateAggTrade.setFirstBreakdownTradeId(response.getFirstBreakdownTradeId()); - updateAggTrade.setLastBreakdownTradeId(response.getLastBreakdownTradeId()); - updateAggTrade.setBuyerMaker(response.isBuyerMaker()); - - // Store the updated agg trade in the cache - aggTradesCache.put(aggregatedTradeId, updateAggTrade); - System.out.println(updateAggTrade); - }); - } - - /** - * @return an aggTrades cache, containing the aggregated trade id as the key, - * and the agg trade data as the value. - */ - public Map getAggTradesCache() { - return aggTradesCache; - } - - public static void main(String[] args) { - new AggTradesCacheExample("ETHBTC"); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.market.AggTrade; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Illustrates how to use the aggTrades event stream to create a local cache of trades for a symbol. + */ +public class AggTradesCacheExample { + + /** + * Key is the aggregate trade id, and the value contains the aggregated trade data, which is + * automatically updated whenever a new agg data stream event arrives. + */ + private Map aggTradesCache; + + public AggTradesCacheExample(String symbol) { + initializeAggTradesCache(symbol); + startAggTradesEventStreaming(symbol); + } + + /** + * Initializes the aggTrades cache by using the REST API. + */ + private void initializeAggTradesCache(String symbol) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + List aggTrades = client.getAggTrades(symbol.toUpperCase()); + + this.aggTradesCache = new HashMap<>(); + for (AggTrade aggTrade : aggTrades) { + aggTradesCache.put(aggTrade.getAggregatedTradeId(), aggTrade); + } + } + + /** + * Begins streaming of agg trades events. + */ + private void startAggTradesEventStreaming(String symbol) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiWebSocketClient client = factory.newWebSocketClient(); + + client.onAggTradeEvent(symbol.toLowerCase(), response -> { + Long aggregatedTradeId = response.getAggregatedTradeId(); + AggTrade updateAggTrade = aggTradesCache.get(aggregatedTradeId); + if (updateAggTrade == null) { + // new agg trade + updateAggTrade = new AggTrade(); + } + updateAggTrade.setAggregatedTradeId(aggregatedTradeId); + updateAggTrade.setPrice(response.getPrice()); + updateAggTrade.setQuantity(response.getQuantity()); + updateAggTrade.setFirstBreakdownTradeId(response.getFirstBreakdownTradeId()); + updateAggTrade.setLastBreakdownTradeId(response.getLastBreakdownTradeId()); + updateAggTrade.setBuyerMaker(response.isBuyerMaker()); + + // Store the updated agg trade in the cache + aggTradesCache.put(aggregatedTradeId, updateAggTrade); + System.out.println(updateAggTrade); + }); + } + + /** + * @return an aggTrades cache, containing the aggregated trade id as the key, + * and the agg trade data as the value. + */ + public Map getAggTradesCache() { + return aggTradesCache; + } + + public static void main(String[] args) { + new AggTradesCacheExample("ETHBTC"); + } +} diff --git a/src/test/java/com/binance/api/examples/AllMarketTickersExample.java b/src/test/java/com/binance/api/examples/AllMarketTickersExample.java old mode 100644 new mode 100755 index 94880a59e..4bee760ce --- a/src/test/java/com/binance/api/examples/AllMarketTickersExample.java +++ b/src/test/java/com/binance/api/examples/AllMarketTickersExample.java @@ -1,21 +1,21 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiWebSocketClient; - -/** - * All market tickers channel examples. - * - * It illustrates how to create a stream to obtain all market tickers. - */ -public class AllMarketTickersExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiWebSocketClient client = factory.newWebSocketClient(); - - client.onAllMarketTickersEvent(event -> { - System.out.println(event); - }); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiWebSocketClient; + +/** + * All market tickers channel examples. + * + * It illustrates how to create a stream to obtain all market tickers. + */ +public class AllMarketTickersExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiWebSocketClient client = factory.newWebSocketClient(); + + client.onAllMarketTickersEvent(event -> { + System.out.println(event); + }); + } +} diff --git a/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java b/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java old mode 100644 new mode 100755 index 1800be613..4b0be5217 --- a/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java +++ b/src/test/java/com/binance/api/examples/CandlesticksCacheExample.java @@ -1,86 +1,86 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; - -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Illustrates how to use the klines/candlesticks event stream to create a local cache of bids/asks for a symbol. - */ -public class CandlesticksCacheExample { - - /** - * Key is the start/open time of the candle, and the value contains candlestick date. - */ - private Map candlesticksCache; - - public CandlesticksCacheExample(String symbol, CandlestickInterval interval) { - initializeCandlestickCache(symbol, interval); - startCandlestickEventStreaming(symbol, interval); - } - - /** - * Initializes the candlestick cache by using the REST API. - */ - private void initializeCandlestickCache(String symbol, CandlestickInterval interval) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - List candlestickBars = client.getCandlestickBars(symbol.toUpperCase(), interval); - - this.candlesticksCache = new TreeMap<>(); - for (Candlestick candlestickBar : candlestickBars) { - candlesticksCache.put(candlestickBar.getOpenTime(), candlestickBar); - } - } - - /** - * Begins streaming of depth events. - */ - private void startCandlestickEventStreaming(String symbol, CandlestickInterval interval) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiWebSocketClient client = factory.newWebSocketClient(); - - client.onCandlestickEvent(symbol.toLowerCase(), interval, response -> { - Long openTime = response.getOpenTime(); - Candlestick updateCandlestick = candlesticksCache.get(openTime); - if (updateCandlestick == null) { - // new candlestick - updateCandlestick = new Candlestick(); - } - // update candlestick with the stream data - updateCandlestick.setOpenTime(response.getOpenTime()); - updateCandlestick.setOpen(response.getOpen()); - updateCandlestick.setLow(response.getLow()); - updateCandlestick.setHigh(response.getHigh()); - updateCandlestick.setClose(response.getClose()); - updateCandlestick.setCloseTime(response.getCloseTime()); - updateCandlestick.setVolume(response.getVolume()); - updateCandlestick.setNumberOfTrades(response.getNumberOfTrades()); - updateCandlestick.setQuoteAssetVolume(response.getQuoteAssetVolume()); - updateCandlestick.setTakerBuyQuoteAssetVolume(response.getTakerBuyQuoteAssetVolume()); - updateCandlestick.setTakerBuyBaseAssetVolume(response.getTakerBuyQuoteAssetVolume()); - - // Store the updated candlestick in the cache - candlesticksCache.put(openTime, updateCandlestick); - System.out.println(updateCandlestick); - }); - } - - /** - * @return a klines/candlestick cache, containing the open/start time of the candlestick as the key, - * and the candlestick data as the value. - */ - public Map getCandlesticksCache() { - return candlesticksCache; - } - - public static void main(String[] args) { - new CandlesticksCacheExample("ETHBTC", CandlestickInterval.ONE_MINUTE); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; + +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * Illustrates how to use the klines/candlesticks event stream to create a local cache of bids/asks for a symbol. + */ +public class CandlesticksCacheExample { + + /** + * Key is the start/open time of the candle, and the value contains candlestick date. + */ + private Map candlesticksCache; + + public CandlesticksCacheExample(String symbol, CandlestickInterval interval) { + initializeCandlestickCache(symbol, interval); + startCandlestickEventStreaming(symbol, interval); + } + + /** + * Initializes the candlestick cache by using the REST API. + */ + private void initializeCandlestickCache(String symbol, CandlestickInterval interval) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + List candlestickBars = client.getCandlestickBars(symbol.toUpperCase(), interval); + + this.candlesticksCache = new TreeMap<>(); + for (Candlestick candlestickBar : candlestickBars) { + candlesticksCache.put(candlestickBar.getOpenTime(), candlestickBar); + } + } + + /** + * Begins streaming of depth events. + */ + private void startCandlestickEventStreaming(String symbol, CandlestickInterval interval) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiWebSocketClient client = factory.newWebSocketClient(); + + client.onCandlestickEvent(symbol.toLowerCase(), interval, response -> { + Long openTime = response.getOpenTime(); + Candlestick updateCandlestick = candlesticksCache.get(openTime); + if (updateCandlestick == null) { + // new candlestick + updateCandlestick = new Candlestick(); + } + // update candlestick with the stream data + updateCandlestick.setOpenTime(response.getOpenTime()); + updateCandlestick.setOpen(response.getOpen()); + updateCandlestick.setLow(response.getLow()); + updateCandlestick.setHigh(response.getHigh()); + updateCandlestick.setClose(response.getClose()); + updateCandlestick.setCloseTime(response.getCloseTime()); + updateCandlestick.setVolume(response.getVolume()); + updateCandlestick.setNumberOfTrades(response.getNumberOfTrades()); + updateCandlestick.setQuoteAssetVolume(response.getQuoteAssetVolume()); + updateCandlestick.setTakerBuyQuoteAssetVolume(response.getTakerBuyQuoteAssetVolume()); + updateCandlestick.setTakerBuyBaseAssetVolume(response.getTakerBuyQuoteAssetVolume()); + + // Store the updated candlestick in the cache + candlesticksCache.put(openTime, updateCandlestick); + System.out.println(updateCandlestick); + }); + } + + /** + * @return a klines/candlestick cache, containing the open/start time of the candlestick as the key, + * and the candlestick data as the value. + */ + public Map getCandlesticksCache() { + return candlesticksCache; + } + + public static void main(String[] args) { + new CandlesticksCacheExample("ETHBTC", CandlestickInterval.ONE_MINUTE); + } +} diff --git a/src/test/java/com/binance/api/examples/DepthCacheExample.java b/src/test/java/com/binance/api/examples/DepthCacheExample.java old mode 100644 new mode 100755 index eb1975796..25adc8c55 --- a/src/test/java/com/binance/api/examples/DepthCacheExample.java +++ b/src/test/java/com/binance/api/examples/DepthCacheExample.java @@ -1,244 +1,244 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiCallback; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.OrderBookEntry; - -import java.io.Closeable; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.TreeMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - -/** - * Illustrates how to use the depth event stream to create a local cache of bids/asks for a symbol. - * - * Snapshots of the order book can be retrieved from the REST API. - * Delta changes to the book can be received by subscribing for updates via the web socket API. - * - * To ensure no updates are missed, it is important to subscribe for updates on the web socket API - * _before_ getting the snapshot from the REST API. Done the other way around it is possible to - * miss one or more updates on the web socket, leaving the local cache in an inconsistent state. - * - * Steps: - * 1. Subscribe to depth events and cache any events that are received. - * 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. - * 3. Apply any cache events that have a final updateId later than the snapshot's update id. - * 4. Start applying any newly received depth events to the depth cache. - * - * The example repeats these steps, on a new web socket, should the web socket connection be lost. - */ -public class DepthCacheExample { - - private static final String BIDS = "BIDS"; - private static final String ASKS = "ASKS"; - - private final String symbol; - private final BinanceApiRestClient restClient; - private final BinanceApiWebSocketClient wsClient; - private final WsCallback wsCallback = new WsCallback(); - private final Map> depthCache = new HashMap<>(); - - private long lastUpdateId = -1; - private volatile Closeable webSocket; - - public DepthCacheExample(String symbol) { - this.symbol = symbol; - - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - this.wsClient = factory.newWebSocketClient(); - this.restClient = factory.newRestClient(); - - initialize(); - } - - private void initialize() { - // 1. Subscribe to depth events and cache any events that are received. - final List pendingDeltas = startDepthEventStreaming(); - - // 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. - initializeDepthCache(); - - // 3. & 4. handled in here. - applyPendingDeltas(pendingDeltas); - } - - /** - * Begins streaming of depth events. - * - * Any events received are cached until the rest API is polled for an initial snapshot. - */ - private List startDepthEventStreaming() { - final List pendingDeltas = new CopyOnWriteArrayList<>(); - wsCallback.setHandler(pendingDeltas::add); - - this.webSocket = wsClient.onDepthEvent(symbol.toLowerCase(), wsCallback); - - return pendingDeltas; - } - - /** - * 2. Initializes the depth cache by getting a snapshot from the REST API. - */ - private void initializeDepthCache() { - OrderBook orderBook = restClient.getOrderBook(symbol.toUpperCase(), 10); - - this.lastUpdateId = orderBook.getLastUpdateId(); - - NavigableMap asks = new TreeMap<>(Comparator.reverseOrder()); - for (OrderBookEntry ask : orderBook.getAsks()) { - asks.put(new BigDecimal(ask.getPrice()), new BigDecimal(ask.getQty())); - } - depthCache.put(ASKS, asks); - - NavigableMap bids = new TreeMap<>(Comparator.reverseOrder()); - for (OrderBookEntry bid : orderBook.getBids()) { - bids.put(new BigDecimal(bid.getPrice()), new BigDecimal(bid.getQty())); - } - depthCache.put(BIDS, bids); - } - - /** - * Deal with any cached updates and switch to normal running. - */ - private void applyPendingDeltas(final List pendingDeltas) { - final Consumer updateOrderBook = newEvent -> { - if (newEvent.getFinalUpdateId() > lastUpdateId) { - System.out.println(newEvent); - lastUpdateId = newEvent.getFinalUpdateId(); - updateOrderBook(getAsks(), newEvent.getAsks()); - updateOrderBook(getBids(), newEvent.getBids()); - printDepthCache(); - } - }; - - final Consumer drainPending = newEvent -> { - pendingDeltas.add(newEvent); - - // 3. Apply any deltas received on the web socket that have an update-id indicating they come - // after the snapshot. - pendingDeltas.stream() - .filter( - e -> e.getFinalUpdateId() > lastUpdateId) // Ignore any updates before the snapshot - .forEach(updateOrderBook); - - // 4. Start applying any newly received depth events to the depth cache. - wsCallback.setHandler(updateOrderBook); - }; - - wsCallback.setHandler(drainPending); - } - - /** - * Updates an order book (bids or asks) with a delta received from the server. - * - * Whenever the qty specified is ZERO, it means the price should was removed from the order book. - */ - private void updateOrderBook(NavigableMap lastOrderBookEntries, - List orderBookDeltas) { - for (OrderBookEntry orderBookDelta : orderBookDeltas) { - BigDecimal price = new BigDecimal(orderBookDelta.getPrice()); - BigDecimal qty = new BigDecimal(orderBookDelta.getQty()); - if (qty.compareTo(BigDecimal.ZERO) == 0) { - // qty=0 means remove this level - lastOrderBookEntries.remove(price); - } else { - lastOrderBookEntries.put(price, qty); - } - } - } - - public NavigableMap getAsks() { - return depthCache.get(ASKS); - } - - public NavigableMap getBids() { - return depthCache.get(BIDS); - } - - /** - * @return the best ask in the order book - */ - private Map.Entry getBestAsk() { - return getAsks().lastEntry(); - } - - /** - * @return the best bid in the order book - */ - private Map.Entry getBestBid() { - return getBids().firstEntry(); - } - - /** - * @return a depth cache, containing two keys (ASKs and BIDs), and for each, an ordered list of book entries. - */ - public Map> getDepthCache() { - return depthCache; - } - - public void close() throws IOException { - webSocket.close(); - } - - /** - * Prints the cached order book / depth of a symbol as well as the best ask and bid price in the book. - */ - private void printDepthCache() { - System.out.println(depthCache); - System.out.println("ASKS:(" + getAsks().size() + ")"); - getAsks().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); - System.out.println("BIDS:(" + getBids().size() + ")"); - getBids().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); - System.out.println("BEST ASK: " + toDepthCacheEntryString(getBestAsk())); - System.out.println("BEST BID: " + toDepthCacheEntryString(getBestBid())); - } - - /** - * Pretty prints an order book entry in the format "price / quantity". - */ - private static String toDepthCacheEntryString(Map.Entry depthCacheEntry) { - return depthCacheEntry.getKey().toPlainString() + " / " + depthCacheEntry.getValue(); - } - - public static void main(String[] args) { - new DepthCacheExample("ETHBTC"); - } - - private final class WsCallback implements BinanceApiCallback { - - private final AtomicReference> handler = new AtomicReference<>(); - - @Override - public void onResponse(DepthEvent depthEvent) { - try { - handler.get().accept(depthEvent); - } catch (final Exception e) { - System.err.println("Exception caught processing depth event"); - e.printStackTrace(System.err); - } - } - - @Override - public void onFailure(Throwable cause) { - System.out.println("WS connection failed. Reconnecting. cause:" + cause.getMessage()); - - initialize(); - } - - private void setHandler(final Consumer handler) { - this.handler.set(handler); - } - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.event.DepthEvent; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.OrderBookEntry; + +import java.io.Closeable; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.NavigableMap; +import java.util.TreeMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +/** + * Illustrates how to use the depth event stream to create a local cache of bids/asks for a symbol. + * + * Snapshots of the order book can be retrieved from the REST API. + * Delta changes to the book can be received by subscribing for updates via the web socket API. + * + * To ensure no updates are missed, it is important to subscribe for updates on the web socket API + * _before_ getting the snapshot from the REST API. Done the other way around it is possible to + * miss one or more updates on the web socket, leaving the local cache in an inconsistent state. + * + * Steps: + * 1. Subscribe to depth events and cache any events that are received. + * 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. + * 3. Apply any cache events that have a final updateId later than the snapshot's update id. + * 4. Start applying any newly received depth events to the depth cache. + * + * The example repeats these steps, on a new web socket, should the web socket connection be lost. + */ +public class DepthCacheExample { + + private static final String BIDS = "BIDS"; + private static final String ASKS = "ASKS"; + + private final String symbol; + private final BinanceApiRestClient restClient; + private final BinanceApiWebSocketClient wsClient; + private final WsCallback wsCallback = new WsCallback(); + private final Map> depthCache = new HashMap<>(); + + private long lastUpdateId = -1; + private volatile Closeable webSocket; + + public DepthCacheExample(String symbol) { + this.symbol = symbol; + + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + this.wsClient = factory.newWebSocketClient(); + this.restClient = factory.newRestClient(); + + initialize(); + } + + private void initialize() { + // 1. Subscribe to depth events and cache any events that are received. + final List pendingDeltas = startDepthEventStreaming(); + + // 2. Get a snapshot from the rest endpoint and use it to build your initial depth cache. + initializeDepthCache(); + + // 3. & 4. handled in here. + applyPendingDeltas(pendingDeltas); + } + + /** + * Begins streaming of depth events. + * + * Any events received are cached until the rest API is polled for an initial snapshot. + */ + private List startDepthEventStreaming() { + final List pendingDeltas = new CopyOnWriteArrayList<>(); + wsCallback.setHandler(pendingDeltas::add); + + this.webSocket = wsClient.onDepthEvent(symbol.toLowerCase(), wsCallback); + + return pendingDeltas; + } + + /** + * 2. Initializes the depth cache by getting a snapshot from the REST API. + */ + private void initializeDepthCache() { + OrderBook orderBook = restClient.getOrderBook(symbol.toUpperCase(), 10); + + this.lastUpdateId = orderBook.getLastUpdateId(); + + NavigableMap asks = new TreeMap<>(Comparator.reverseOrder()); + for (OrderBookEntry ask : orderBook.getAsks()) { + asks.put(new BigDecimal(ask.getPrice()), new BigDecimal(ask.getQty())); + } + depthCache.put(ASKS, asks); + + NavigableMap bids = new TreeMap<>(Comparator.reverseOrder()); + for (OrderBookEntry bid : orderBook.getBids()) { + bids.put(new BigDecimal(bid.getPrice()), new BigDecimal(bid.getQty())); + } + depthCache.put(BIDS, bids); + } + + /** + * Deal with any cached updates and switch to normal running. + */ + private void applyPendingDeltas(final List pendingDeltas) { + final Consumer updateOrderBook = newEvent -> { + if (newEvent.getFinalUpdateId() > lastUpdateId) { + System.out.println(newEvent); + lastUpdateId = newEvent.getFinalUpdateId(); + updateOrderBook(getAsks(), newEvent.getAsks()); + updateOrderBook(getBids(), newEvent.getBids()); + printDepthCache(); + } + }; + + final Consumer drainPending = newEvent -> { + pendingDeltas.add(newEvent); + + // 3. Apply any deltas received on the web socket that have an update-id indicating they come + // after the snapshot. + pendingDeltas.stream() + .filter( + e -> e.getFinalUpdateId() > lastUpdateId) // Ignore any updates before the snapshot + .forEach(updateOrderBook); + + // 4. Start applying any newly received depth events to the depth cache. + wsCallback.setHandler(updateOrderBook); + }; + + wsCallback.setHandler(drainPending); + } + + /** + * Updates an order book (bids or asks) with a delta received from the server. + * + * Whenever the qty specified is ZERO, it means the price should was removed from the order book. + */ + private void updateOrderBook(NavigableMap lastOrderBookEntries, + List orderBookDeltas) { + for (OrderBookEntry orderBookDelta : orderBookDeltas) { + BigDecimal price = new BigDecimal(orderBookDelta.getPrice()); + BigDecimal qty = new BigDecimal(orderBookDelta.getQty()); + if (qty.compareTo(BigDecimal.ZERO) == 0) { + // qty=0 means remove this level + lastOrderBookEntries.remove(price); + } else { + lastOrderBookEntries.put(price, qty); + } + } + } + + public NavigableMap getAsks() { + return depthCache.get(ASKS); + } + + public NavigableMap getBids() { + return depthCache.get(BIDS); + } + + /** + * @return the best ask in the order book + */ + private Map.Entry getBestAsk() { + return getAsks().lastEntry(); + } + + /** + * @return the best bid in the order book + */ + private Map.Entry getBestBid() { + return getBids().firstEntry(); + } + + /** + * @return a depth cache, containing two keys (ASKs and BIDs), and for each, an ordered list of book entries. + */ + public Map> getDepthCache() { + return depthCache; + } + + public void close() throws IOException { + webSocket.close(); + } + + /** + * Prints the cached order book / depth of a symbol as well as the best ask and bid price in the book. + */ + private void printDepthCache() { + System.out.println(depthCache); + System.out.println("ASKS:(" + getAsks().size() + ")"); + getAsks().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); + System.out.println("BIDS:(" + getBids().size() + ")"); + getBids().entrySet().forEach(entry -> System.out.println(toDepthCacheEntryString(entry))); + System.out.println("BEST ASK: " + toDepthCacheEntryString(getBestAsk())); + System.out.println("BEST BID: " + toDepthCacheEntryString(getBestBid())); + } + + /** + * Pretty prints an order book entry in the format "price / quantity". + */ + private static String toDepthCacheEntryString(Map.Entry depthCacheEntry) { + return depthCacheEntry.getKey().toPlainString() + " / " + depthCacheEntry.getValue(); + } + + public static void main(String[] args) { + new DepthCacheExample("ETHBTC"); + } + + private final class WsCallback implements BinanceApiCallback { + + private final AtomicReference> handler = new AtomicReference<>(); + + @Override + public void onResponse(DepthEvent depthEvent) { + try { + handler.get().accept(depthEvent); + } catch (final Exception e) { + System.err.println("Exception caught processing depth event"); + e.printStackTrace(System.err); + } + } + + @Override + public void onFailure(Throwable cause) { + System.out.println("WS connection failed. Reconnecting. cause:" + cause.getMessage()); + + initialize(); + } + + private void setHandler(final Consumer handler) { + this.handler.set(handler); + } + } +} diff --git a/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java old mode 100644 new mode 100755 index 911cab374..760d6f26a --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExample.java @@ -1,46 +1,46 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.ExchangeInfo; -import com.binance.api.client.domain.general.FilterType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; - -import java.util.List; - -/** - * Examples on how to use the general endpoints. - */ -public class GeneralEndpointsExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - - // Test connectivity - client.ping(); - - // Check server time - long serverTime = client.getServerTime(); - System.out.println(serverTime); - - // Exchange info - ExchangeInfo exchangeInfo = client.getExchangeInfo(); - System.out.println(exchangeInfo.getTimezone()); - System.out.println(exchangeInfo.getSymbols()); - - // Obtain symbol information - SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); - System.out.println(symbolInfo.getStatus()); - - SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); - System.out.println(priceFilter.getMinPrice()); - System.out.println(priceFilter.getTickSize()); - - // Obtain asset information - List allAssets = client.getAllAssets(); - System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get()); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.ExchangeInfo; +import com.binance.api.client.domain.general.FilterType; +import com.binance.api.client.domain.general.SymbolFilter; +import com.binance.api.client.domain.general.SymbolInfo; + +import java.util.List; + +/** + * Examples on how to use the general endpoints. + */ +public class GeneralEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + + // Test connectivity + client.ping(); + + // Check server time + long serverTime = client.getServerTime(); + System.out.println(serverTime); + + // Exchange info + ExchangeInfo exchangeInfo = client.getExchangeInfo(); + System.out.println(exchangeInfo.getTimezone()); + System.out.println(exchangeInfo.getSymbols()); + + // Obtain symbol information + SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); + System.out.println(symbolInfo.getStatus()); + + SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); + System.out.println(priceFilter.getMinPrice()); + System.out.println(priceFilter.getTickSize()); + + // Obtain asset information + List allAssets = client.getAllAssets(); + System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get()); + } +} diff --git a/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java old mode 100644 new mode 100755 index 77bfd238e..96739a5c2 --- a/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/GeneralEndpointsExampleAsync.java @@ -1,45 +1,45 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.general.Asset; -import com.binance.api.client.domain.general.FilterType; -import com.binance.api.client.domain.general.SymbolFilter; -import com.binance.api.client.domain.general.SymbolInfo; - -import java.util.List; - -/** - * Examples on how to use the general endpoints. - */ -public class GeneralEndpointsExampleAsync { - - public static void main(String[] args) throws InterruptedException { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Test connectivity - client.ping(response -> System.out.println("Ping succeeded.")); - - // Check server time - client.getServerTime(response -> System.out.println(response.getServerTime())); - - // Exchange info - client.getExchangeInfo(exchangeInfo -> { - System.out.println(exchangeInfo.getTimezone()); - System.out.println(exchangeInfo.getSymbols()); - - // Obtain symbol information - SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); - System.out.println(symbolInfo.getStatus()); - - SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); - System.out.println(priceFilter.getMinPrice()); - System.out.println(priceFilter.getTickSize()); - }); - - // Obtain asset information - client.getAllAssets(allAssets -> - System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get())); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.general.Asset; +import com.binance.api.client.domain.general.FilterType; +import com.binance.api.client.domain.general.SymbolFilter; +import com.binance.api.client.domain.general.SymbolInfo; + +import java.util.List; + +/** + * Examples on how to use the general endpoints. + */ +public class GeneralEndpointsExampleAsync { + + public static void main(String[] args) throws InterruptedException { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Test connectivity + client.ping(response -> System.out.println("Ping succeeded.")); + + // Check server time + client.getServerTime(response -> System.out.println(response.getServerTime())); + + // Exchange info + client.getExchangeInfo(exchangeInfo -> { + System.out.println(exchangeInfo.getTimezone()); + System.out.println(exchangeInfo.getSymbols()); + + // Obtain symbol information + SymbolInfo symbolInfo = exchangeInfo.getSymbolInfo("ETHBTC"); + System.out.println(symbolInfo.getStatus()); + + SymbolFilter priceFilter = symbolInfo.getSymbolFilter(FilterType.PRICE_FILTER); + System.out.println(priceFilter.getMinPrice()); + System.out.println(priceFilter.getTickSize()); + }); + + // Obtain asset information + client.getAllAssets(allAssets -> + System.out.println(allAssets.stream().filter(asset -> asset.getAssetCode().equals("BNB")).findFirst().get())); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java new file mode 100755 index 000000000..0d204fac1 --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExample.java @@ -0,0 +1,41 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.MarginAccount; +import com.binance.api.client.domain.account.MarginTransaction; +import com.binance.api.client.domain.account.Trade; + +import java.util.List; + +/** + * Examples on how to get margin account information. + */ +public class MarginAccountEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + + // Get account balances + MarginAccount marginAccount = client.getAccount(); + System.out.println(marginAccount.getUserAssets()); + System.out.println(marginAccount.getAssetBalance("ETH")); + System.out.println(marginAccount.getMarginLevel()); + + // Get list of trades + List myTrades = client.getMyTrades("NEOETH"); + System.out.println(myTrades); + + // Transfer, borrow, repay + MarginTransaction spotToMargin = client.transfer("USDT", "1", TransferType.SPOT_TO_MARGIN); + System.out.println(spotToMargin.getTranId()); + MarginTransaction borrowed = client.borrow("USDT", "1"); + System.out.println(borrowed.getTranId()); + MarginTransaction repayed = client.repay("USDT", "1"); + System.out.println(repayed.getTranId()); + MarginTransaction marginToSpot = client.transfer("USDT", "1", TransferType.MARGIN_TO_SPOT); + System.out.println(marginToSpot.getTranId()); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java new file mode 100755 index 000000000..07c3507be --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsExampleAsync.java @@ -0,0 +1,36 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncMarginRestClient; +import com.binance.api.client.BinanceApiCallback; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.MarginTransaction; + +/** + * Examples on how to get margin account information asynchronously. + */ +public class MarginAccountEndpointsExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncMarginRestClient client = factory.newAsyncMarginRestClient(); + + // Get account balances + client.getAccount(marginAccount -> { + System.out.println(marginAccount.getUserAssets()); + System.out.println(marginAccount.getAssetBalance("ETH")); + System.out.println(marginAccount.getMarginLevel()); + }); + + // Get list of trades + client.getMyTrades("NEOETH", myTrades -> { + System.out.println(myTrades); + }); + + // Transfer, borrow, repay + client.transfer("USDT", "1", TransferType.SPOT_TO_MARGIN, transaction -> System.out.println(transaction.getTranId())); + client.borrow("USDT", "1", transaction -> System.out.println(transaction.getTranId())); + client.repay("USDT", "1", transaction -> System.out.println(transaction.getTranId())); + client.transfer("USDT", "1", TransferType.MARGIN_TO_SPOT, transaction -> System.out.println(transaction.getTranId())); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java new file mode 100755 index 000000000..b9456722f --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -0,0 +1,24 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.domain.TransferType; +import com.binance.api.client.domain.account.*; + +import java.util.List; + +/** + * Examples on how to get margin account information. + */ +public class MarginAccountEndpointsLoanQueryExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + MarginTransaction borrowed = client.borrow("USDT", "310"); + System.out.println(borrowed.getTranId()); + LoanQueryResult queryResult = client.queryLoan("USDT", borrowed.getTranId()); + Loan loan = queryResult.getRows().get(0); + System.out.println(loan.getStatus()); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExample.java b/src/test/java/com/binance/api/examples/MarginOrdersExample.java new file mode 100755 index 000000000..404274489 --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginOrdersExample.java @@ -0,0 +1,46 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.NewOrderResponseType; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.request.*; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class MarginOrdersExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + + // Getting list of open orders + List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); + System.out.println(openOrders); + + // Get status of a particular order + Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 751698L)); + System.out.println(order); + + // Canceling an order + try { + CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); + System.out.println(cancelOrderResponse); + } catch (BinanceApiException e) { + System.out.println(e.getError().getMsg()); + } + + // Placing a real LIMIT order + NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); + System.out.println(newOrderResponse); + } + +} diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java new file mode 100755 index 000000000..c80cdfc70 --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java @@ -0,0 +1,36 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncMarginRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class MarginOrdersExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncMarginRestClient client = factory.newAsyncMarginRestClient(); + + // Getting list of open orders + client.getOpenOrders(new OrderRequest("LINKETH"), response -> System.out.println(response)); + + // Get status of a particular order + client.getOrderStatus(new OrderStatusRequest("LINKETH", 745262L), + response -> System.out.println(response)); + + // Canceling an order + client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), + response -> System.out.println(response)); + + // Placing a real LIMIT order + client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println(response)); + } +} diff --git a/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java b/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java new file mode 100755 index 000000000..d6bab71fd --- /dev/null +++ b/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java @@ -0,0 +1,55 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiMarginRestClient; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.event.AccountUpdateEvent; +import com.binance.api.client.domain.event.OrderTradeUpdateEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; + +/** + * User data stream endpoints examples. + * + * It illustrates how to create a stream to obtain updates on a user account, + * as well as update on trades/orders on a user account. + */ +public class MarginUserDataStreamExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + + // First, we obtain a listenKey which is required to interact with the user data stream + String listenKey = client.startUserDataStream(); + + // Then, we open a new web socket client, and provide a callback that is called on every update + BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient(); + + // Listen for changes in the account + webSocketClient.onUserDataUpdateEvent(listenKey, response -> { + if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) { + AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent(); + // Print new balances of every available asset + System.out.println(accountUpdateEvent.getBalances()); + } else { + OrderTradeUpdateEvent orderTradeUpdateEvent = response.getOrderTradeUpdateEvent(); + // Print details about an order/trade + System.out.println(orderTradeUpdateEvent); + + // Print original quantity + System.out.println(orderTradeUpdateEvent.getOriginalQuantity()); + + // Or price + System.out.println(orderTradeUpdateEvent.getPrice()); + } + }); + System.out.println("Waiting for events..."); + + // We can keep alive the user data stream + // client.keepAliveUserDataStream(listenKey); + + // Or we can invalidate it, whenever it is no longer needed + // client.closeUserDataStream(listenKey); + } +} diff --git a/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java b/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java old mode 100644 new mode 100755 index 79a83b11f..592aba46a --- a/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java +++ b/src/test/java/com/binance/api/examples/MarketDataEndpointsExample.java @@ -1,57 +1,57 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.BookTicker; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; -import com.binance.api.client.exception.BinanceApiException; - -import java.util.List; - -/** - * Examples on how to get market data information such as the latest price of a symbol, etc. - */ -public class MarketDataEndpointsExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiRestClient client = factory.newRestClient(); - - // Getting depth of a symbol - OrderBook orderBook = client.getOrderBook("NEOETH", 10); - System.out.println(orderBook.getAsks()); - - // Getting latest price of a symbol - TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH"); - System.out.println(tickerStatistics); - - // Getting all latest prices - List allPrices = client.getAllPrices(); - System.out.println(allPrices); - - // Getting agg trades - List aggTrades = client.getAggTrades("NEOETH"); - System.out.println(aggTrades); - - // Weekly candlestick bars for a symbol - List candlesticks = client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY); - System.out.println(candlesticks); - - // Getting all book tickers - List allBookTickers = client.getBookTickers(); - System.out.println(allBookTickers); - - // Exception handling - try { - client.getOrderBook("UNKNOWN", 10); - } catch (BinanceApiException e) { - System.out.println(e.getError().getCode()); // -1121 - System.out.println(e.getError().getMsg()); // Invalid symbol - } - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.BookTicker; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +/** + * Examples on how to get market data information such as the latest price of a symbol, etc. + */ +public class MarketDataEndpointsExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiRestClient client = factory.newRestClient(); + + // Getting depth of a symbol + OrderBook orderBook = client.getOrderBook("NEOETH", 10); + System.out.println(orderBook.getAsks()); + + // Getting latest price of a symbol + TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH"); + System.out.println(tickerStatistics); + + // Getting all latest prices + List allPrices = client.getAllPrices(); + System.out.println(allPrices); + + // Getting agg trades + List aggTrades = client.getAggTrades("NEOETH"); + System.out.println(aggTrades); + + // Weekly candlestick bars for a symbol + List candlesticks = client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY); + System.out.println(candlesticks); + + // Getting all book tickers + List allBookTickers = client.getBookTickers(); + System.out.println(allBookTickers); + + // Exception handling + try { + client.getOrderBook("UNKNOWN", 10); + } catch (BinanceApiException e) { + System.out.println(e.getError().getCode()); // -1121 + System.out.println(e.getError().getMsg()); // Invalid symbol + } + } +} diff --git a/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java b/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java old mode 100644 new mode 100755 index c85330c2b..f27fab7ff --- a/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java +++ b/src/test/java/com/binance/api/examples/MarketDataEndpointsExampleAsync.java @@ -1,57 +1,57 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.market.AggTrade; -import com.binance.api.client.domain.market.Candlestick; -import com.binance.api.client.domain.market.CandlestickInterval; -import com.binance.api.client.domain.market.OrderBook; -import com.binance.api.client.domain.market.TickerPrice; -import com.binance.api.client.domain.market.TickerStatistics; -import com.binance.api.client.exception.BinanceApiException; - -import java.util.List; - -/** - * Examples on how to get market data information such as the latest price of a symbol, etc., in an async way. - */ -public class MarketDataEndpointsExampleAsync { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Getting depth of a symbol (async) - client.getOrderBook("NEOETH", 10, (OrderBook response) -> { - System.out.println(response.getBids()); - }); - - // Getting latest price of a symbol (async) - client.get24HrPriceStatistics("NEOETH", (TickerStatistics response) -> { - System.out.println(response); - }); - - // Getting all latest prices (async) - client.getAllPrices((List response) -> { - System.out.println(response); - }); - - // Getting agg trades (async) - client.getAggTrades("NEOETH", (List response) -> System.out.println(response)); - - // Weekly candlestick bars for a symbol - client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY, - (List response) -> System.out.println(response)); - - // Book tickers (async) - client.getBookTickers(response -> System.out.println(response)); - - // Exception handling - try { - client.getOrderBook("UNKNOWN", 10, response -> System.out.println(response)); - } catch (BinanceApiException e) { - System.out.println(e.getError().getCode()); // -1121 - System.out.println(e.getError().getMsg()); // Invalid symbol - } - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.market.AggTrade; +import com.binance.api.client.domain.market.Candlestick; +import com.binance.api.client.domain.market.CandlestickInterval; +import com.binance.api.client.domain.market.OrderBook; +import com.binance.api.client.domain.market.TickerPrice; +import com.binance.api.client.domain.market.TickerStatistics; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +/** + * Examples on how to get market data information such as the latest price of a symbol, etc., in an async way. + */ +public class MarketDataEndpointsExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Getting depth of a symbol (async) + client.getOrderBook("NEOETH", 10, (OrderBook response) -> { + System.out.println(response.getBids()); + }); + + // Getting latest price of a symbol (async) + client.get24HrPriceStatistics("NEOETH", (TickerStatistics response) -> { + System.out.println(response); + }); + + // Getting all latest prices (async) + client.getAllPrices((List response) -> { + System.out.println(response); + }); + + // Getting agg trades (async) + client.getAggTrades("NEOETH", (List response) -> System.out.println(response)); + + // Weekly candlestick bars for a symbol + client.getCandlestickBars("NEOETH", CandlestickInterval.WEEKLY, + (List response) -> System.out.println(response)); + + // Book tickers (async) + client.getBookTickers(response -> System.out.println(response)); + + // Exception handling + try { + client.getOrderBook("UNKNOWN", 10, response -> System.out.println(response)); + } catch (BinanceApiException e) { + System.out.println(e.getError().getCode()); // -1121 + System.out.println(e.getError().getMsg()); // Invalid symbol + } + } +} diff --git a/src/test/java/com/binance/api/examples/MarketDataStreamExample.java b/src/test/java/com/binance/api/examples/MarketDataStreamExample.java old mode 100644 new mode 100755 index f2b790510..898d49b10 --- a/src/test/java/com/binance/api/examples/MarketDataStreamExample.java +++ b/src/test/java/com/binance/api/examples/MarketDataStreamExample.java @@ -1,28 +1,28 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.market.CandlestickInterval; - -import java.io.IOException; - -/** - * Market data stream endpoints examples. - * - * It illustrates how to create a stream to obtain updates on market data such as executed trades. - */ -public class MarketDataStreamExample { - - public static void main(String[] args) throws InterruptedException, IOException { - BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient(); - - // Listen for aggregated trade events for ETH/BTC - client.onAggTradeEvent("ethbtc", response -> System.out.println(response)); - - // Listen for changes in the order book in ETH/BTC - client.onDepthEvent("ethbtc", response -> System.out.println(response)); - - // Obtain 1m candlesticks in real-time for ETH/BTC - client.onCandlestickEvent("ethbtc", CandlestickInterval.ONE_MINUTE, response -> System.out.println(response)); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.market.CandlestickInterval; + +import java.io.IOException; + +/** + * Market data stream endpoints examples. + * + * It illustrates how to create a stream to obtain updates on market data such as executed trades. + */ +public class MarketDataStreamExample { + + public static void main(String[] args) throws InterruptedException, IOException { + BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient(); + + // Listen for aggregated trade events for ETH/BTC + client.onAggTradeEvent("ethbtc", response -> System.out.println(response)); + + // Listen for changes in the order book in ETH/BTC + client.onDepthEvent("ethbtc", response -> System.out.println(response)); + + // Obtain 1m candlesticks in real-time for ETH/BTC + client.onCandlestickEvent("ethbtc", CandlestickInterval.ONE_MINUTE, response -> System.out.println(response)); + } +} diff --git a/src/test/java/com/binance/api/examples/OrdersExample.java b/src/test/java/com/binance/api/examples/OrdersExample.java old mode 100644 new mode 100755 index fc2185497..a1dd9d6cd --- a/src/test/java/com/binance/api/examples/OrdersExample.java +++ b/src/test/java/com/binance/api/examples/OrdersExample.java @@ -1,61 +1,61 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.NewOrderResponseType; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.CancelOrderResponse; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; -import com.binance.api.client.exception.BinanceApiException; - -import java.util.List; - -import static com.binance.api.client.domain.account.NewOrder.limitBuy; -import static com.binance.api.client.domain.account.NewOrder.marketBuy; - -/** - * Examples on how to place orders, cancel them, and query account information. - */ -public class OrdersExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiRestClient client = factory.newRestClient(); - - // Getting list of open orders - List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); - System.out.println(openOrders); - - // Getting list of all orders with a limit of 10 - List allOrders = client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10)); - System.out.println(allOrders); - - // Get status of a particular order - Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 751698L)); - System.out.println(order); - - // Canceling an order - try { - CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); - System.out.println(cancelOrderResponse); - } catch (BinanceApiException e) { - System.out.println(e.getError().getMsg()); - } - - // Placing a test LIMIT order - client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001")); - - // Placing a test MARKET order - client.newOrderTest(marketBuy("LINKETH", "1000")); - - // Placing a real LIMIT order - NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); - System.out.println(newOrderResponse); - } - -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.NewOrderResponseType; +import com.binance.api.client.domain.account.Order; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.CancelOrderResponse; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; +import com.binance.api.client.exception.BinanceApiException; + +import java.util.List; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; +import static com.binance.api.client.domain.account.NewOrder.marketBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class OrdersExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiRestClient client = factory.newRestClient(); + + // Getting list of open orders + List openOrders = client.getOpenOrders(new OrderRequest("LINKETH")); + System.out.println(openOrders); + + // Getting list of all orders with a limit of 10 + List allOrders = client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10)); + System.out.println(allOrders); + + // Get status of a particular order + Order order = client.getOrderStatus(new OrderStatusRequest("LINKETH", 751698L)); + System.out.println(order); + + // Canceling an order + try { + CancelOrderResponse cancelOrderResponse = client.cancelOrder(new CancelOrderRequest("LINKETH", 756762l)); + System.out.println(cancelOrderResponse); + } catch (BinanceApiException e) { + System.out.println(e.getError().getMsg()); + } + + // Placing a test LIMIT order + client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001")); + + // Placing a test MARKET order + client.newOrderTest(marketBuy("LINKETH", "1000")); + + // Placing a real LIMIT order + NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); + System.out.println(newOrderResponse); + } + +} diff --git a/src/test/java/com/binance/api/examples/OrdersExampleAsync.java b/src/test/java/com/binance/api/examples/OrdersExampleAsync.java old mode 100644 new mode 100755 index cadb53a58..776e694a6 --- a/src/test/java/com/binance/api/examples/OrdersExampleAsync.java +++ b/src/test/java/com/binance/api/examples/OrdersExampleAsync.java @@ -1,48 +1,48 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiAsyncRestClient; -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.request.AllOrdersRequest; -import com.binance.api.client.domain.account.request.CancelOrderRequest; -import com.binance.api.client.domain.account.request.OrderRequest; -import com.binance.api.client.domain.account.request.OrderStatusRequest; - -import static com.binance.api.client.domain.account.NewOrder.limitBuy; -import static com.binance.api.client.domain.account.NewOrder.marketBuy; - -/** - * Examples on how to place orders, cancel them, and query account information. - */ -public class OrdersExampleAsync { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); - - // Getting list of open orders - client.getOpenOrders(new OrderRequest("LINKETH"), response -> System.out.println(response)); - - // Get status of a particular order - client.getOrderStatus(new OrderStatusRequest("LINKETH", 745262L), - response -> System.out.println(response)); - - // Getting list of all orders with a limit of 10 - client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10), response -> System.out.println(response)); - - // Canceling an order - client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), - response -> System.out.println(response)); - - // Placing a test LIMIT order - client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), - response -> System.out.println("Test order has succeeded.")); - - // Placing a test MARKET order - client.newOrderTest(marketBuy("LINKETH", "1000"), response -> System.out.println("Test order has succeeded.")); - - // Placing a real LIMIT order - client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), - response -> System.out.println(response)); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiAsyncRestClient; +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.domain.TimeInForce; +import com.binance.api.client.domain.account.request.AllOrdersRequest; +import com.binance.api.client.domain.account.request.CancelOrderRequest; +import com.binance.api.client.domain.account.request.OrderRequest; +import com.binance.api.client.domain.account.request.OrderStatusRequest; + +import static com.binance.api.client.domain.account.NewOrder.limitBuy; +import static com.binance.api.client.domain.account.NewOrder.marketBuy; + +/** + * Examples on how to place orders, cancel them, and query account information. + */ +public class OrdersExampleAsync { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiAsyncRestClient client = factory.newAsyncRestClient(); + + // Getting list of open orders + client.getOpenOrders(new OrderRequest("LINKETH"), response -> System.out.println(response)); + + // Get status of a particular order + client.getOrderStatus(new OrderStatusRequest("LINKETH", 745262L), + response -> System.out.println(response)); + + // Getting list of all orders with a limit of 10 + client.getAllOrders(new AllOrdersRequest("LINKETH").limit(10), response -> System.out.println(response)); + + // Canceling an order + client.cancelOrder(new CancelOrderRequest("LINKETH", 756703L), + response -> System.out.println(response)); + + // Placing a test LIMIT order + client.newOrderTest(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println("Test order has succeeded.")); + + // Placing a test MARKET order + client.newOrderTest(marketBuy("LINKETH", "1000"), response -> System.out.println("Test order has succeeded.")); + + // Placing a real LIMIT order + client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println(response)); + } +} diff --git a/src/test/java/com/binance/api/examples/UserDataStreamExample.java b/src/test/java/com/binance/api/examples/UserDataStreamExample.java old mode 100644 new mode 100755 index 8ea5f309a..180f5d7b7 --- a/src/test/java/com/binance/api/examples/UserDataStreamExample.java +++ b/src/test/java/com/binance/api/examples/UserDataStreamExample.java @@ -1,54 +1,54 @@ -package com.binance.api.examples; - -import com.binance.api.client.BinanceApiClientFactory; -import com.binance.api.client.BinanceApiRestClient; -import com.binance.api.client.BinanceApiWebSocketClient; -import com.binance.api.client.domain.event.AccountUpdateEvent; -import com.binance.api.client.domain.event.OrderTradeUpdateEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; - -/** - * User data stream endpoints examples. - * - * It illustrates how to create a stream to obtain updates on a user account, - * as well as update on trades/orders on a user account. - */ -public class UserDataStreamExample { - - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiRestClient client = factory.newRestClient(); - - // First, we obtain a listenKey which is required to interact with the user data stream - String listenKey = client.startUserDataStream(); - - // Then, we open a new web socket client, and provide a callback that is called on every update - BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient(); - - // Listen for changes in the account - webSocketClient.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) { - AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent(); - // Print new balances of every available asset - System.out.println(accountUpdateEvent.getBalances()); - } else { - OrderTradeUpdateEvent orderTradeUpdateEvent = response.getOrderTradeUpdateEvent(); - // Print details about an order/trade - System.out.println(orderTradeUpdateEvent); - - // Print original quantity - System.out.println(orderTradeUpdateEvent.getOriginalQuantity()); - - // Or price - System.out.println(orderTradeUpdateEvent.getPrice()); - } - }); - System.out.println("Waiting for events..."); - - // We can keep alive the user data stream - // client.keepAliveUserDataStream(listenKey); - - // Or we can invalidate it, whenever it is no longer needed - // client.closeUserDataStream(listenKey); - } -} +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiRestClient; +import com.binance.api.client.BinanceApiWebSocketClient; +import com.binance.api.client.domain.event.AccountUpdateEvent; +import com.binance.api.client.domain.event.OrderTradeUpdateEvent; +import com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType; + +/** + * User data stream endpoints examples. + * + * It illustrates how to create a stream to obtain updates on a user account, + * as well as update on trades/orders on a user account. + */ +public class UserDataStreamExample { + + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiRestClient client = factory.newRestClient(); + + // First, we obtain a listenKey which is required to interact with the user data stream + String listenKey = client.startUserDataStream(); + + // Then, we open a new web socket client, and provide a callback that is called on every update + BinanceApiWebSocketClient webSocketClient = factory.newWebSocketClient(); + + // Listen for changes in the account + webSocketClient.onUserDataUpdateEvent(listenKey, response -> { + if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) { + AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent(); + // Print new balances of every available asset + System.out.println(accountUpdateEvent.getBalances()); + } else { + OrderTradeUpdateEvent orderTradeUpdateEvent = response.getOrderTradeUpdateEvent(); + // Print details about an order/trade + System.out.println(orderTradeUpdateEvent); + + // Print original quantity + System.out.println(orderTradeUpdateEvent.getOriginalQuantity()); + + // Or price + System.out.println(orderTradeUpdateEvent.getPrice()); + } + }); + System.out.println("Waiting for events..."); + + // We can keep alive the user data stream + // client.keepAliveUserDataStream(listenKey); + + // Or we can invalidate it, whenever it is no longer needed + // client.closeUserDataStream(listenKey); + } +} From f3e35be0deb136f64632746ab790de322d4c39c3 Mon Sep 17 00:00:00 2001 From: Truong Ha Date: Thu, 30 Apr 2020 14:15:36 +0700 Subject: [PATCH 50/83] Updated constants and services for margin endpoints --- .../client/constant/BinanceApiConstants.java | 5 ++ .../api/client/impl/BinanceApiService.java | 69 ++++++++++++++++--- 2 files changed, 64 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java index 4e3a9de27..8e84256d7 100755 --- a/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java +++ b/src/main/java/com/binance/api/client/constant/BinanceApiConstants.java @@ -29,6 +29,11 @@ public class BinanceApiConstants { */ public static final long DEFAULT_RECEIVING_WINDOW = 60_000L; + /** + * Default margin receiving window. + */ + public static final long DEFAULT_MARGIN_RECEIVING_WINDOW = 5_000L; + /** * Default ToStringStyle used by toString methods. * Override this to change the output format of the overridden toString methods. diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 6f6c293db..3a4220317 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -4,16 +4,7 @@ import com.binance.api.client.domain.OrderSide; import com.binance.api.client.domain.OrderType; import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.NewOrderResponseType; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.*; import com.binance.api.client.domain.account.request.CancelOrderResponse; import com.binance.api.client.domain.event.ListenKey; import com.binance.api.client.domain.general.Asset; @@ -177,4 +168,62 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) @DELETE("/api/v1/userDataStream") Call closeAliveUserDataStream(@Query("listenKey") String listenKey); + + // Margin Account endpoints + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/transfer") + Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/loan") + Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/loan") + Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/repay") + Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/account") + Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/openOrders") + Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/margin/order") + Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/sapi/v1/margin/order") + Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/order") + Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/myTrades") + Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/sapi/v1/userDataStream") + Call startMarginUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/sapi/v1/userDataStream") + Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); } From 229060c2dfaab1613981187471a0defdbdc10d02 Mon Sep 17 00:00:00 2001 From: Truong Ha Date: Fri, 1 May 2020 12:45:43 +0700 Subject: [PATCH 51/83] Fixed issue with repay --- .../client/BinanceApiMarginRestClient.java | 17 ++++ .../api/client/domain/account/Loan.java | 3 - .../api/client/domain/account/Repay.java | 85 +++++++++++++++++++ .../domain/account/RepayQueryResult.java | 41 +++++++++ .../impl/BinanceApiMarginRestClientImpl.java | 12 +++ .../api/client/impl/BinanceApiService.java | 8 ++ ...arginAccountEndpointsLoanQueryExample.java | 25 +++--- 7 files changed, 175 insertions(+), 16 deletions(-) create mode 100755 src/main/java/com/binance/api/client/domain/account/Repay.java create mode 100755 src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java index 3e146ee39..527073b96 100755 --- a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -85,6 +85,21 @@ public interface BinanceApiMarginRestClient { */ MarginTransaction borrow(String asset, String amount); + /** + * Query loan record + * @param asset asset to query + * @return loan records + */ + RepayQueryResult queryRepay(String asset, long startTime); + + /** + * Query loan record + * @param asset asset to query + * @param txId the tranId in POST /sapi/v1/margin/repay + * @return loan records + */ + RepayQueryResult queryRepay(String asset, String txId); + /** * Repay loan for margin account * @param asset asset to repay @@ -100,4 +115,6 @@ public interface BinanceApiMarginRestClient { * @return loan records */ LoanQueryResult queryLoan(String asset, String txId); + + } diff --git a/src/main/java/com/binance/api/client/domain/account/Loan.java b/src/main/java/com/binance/api/client/domain/account/Loan.java index 5424c9b17..96389c269 100755 --- a/src/main/java/com/binance/api/client/domain/account/Loan.java +++ b/src/main/java/com/binance/api/client/domain/account/Loan.java @@ -1,10 +1,7 @@ package com.binance.api.client.domain.account; -import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.LoanStatus; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.builder.ToStringBuilder; /** * Represents an executed trade history item. diff --git a/src/main/java/com/binance/api/client/domain/account/Repay.java b/src/main/java/com/binance/api/client/domain/account/Repay.java new file mode 100755 index 000000000..22f3e7b0e --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Repay.java @@ -0,0 +1,85 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.domain.LoanStatus; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Repay { + + private String amount; + private String asset; + private String interest; + private String principal; + LoanStatus status; + private long timestamp; + private String txId; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + public String getAsset() { + return asset; + } + + public void setAsset(String asset) { + this.asset = asset; + } + + public String getInterest() { + return interest; + } + + public void setInterest(String interest) { + this.interest = interest; + } + + public String getPrincipal() { + return principal; + } + + public void setPrincipal(String principal) { + this.principal = principal; + } + + public LoanStatus getStatus() { + return status; + } + + public void setStatus(LoanStatus status) { + this.status = status; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getTxId() { + return txId; + } + + public void setTxId(String txId) { + this.txId = txId; + } + + @Override + public String toString() { + return "Repay{" + + "amount='" + amount + '\'' + + ", asset='" + asset + '\'' + + ", interest='" + interest + '\'' + + ", principal='" + principal + '\'' + + ", status=" + status + + ", timestamp=" + timestamp + + ", txId='" + txId + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java b/src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java new file mode 100755 index 000000000..4221e9df5 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/RepayQueryResult.java @@ -0,0 +1,41 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * History of account withdrawals. + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class RepayQueryResult { + + private int total; + private List rows; + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + public List getRows() { + return rows; + } + + public void setRows(List rows) { + this.rows = rows; + } + + @Override + public String toString() { + return "RepayQueryResult{" + + "total=" + total + + ", rows=" + rows + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java index 93bf3244d..5e88373e5 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -93,6 +93,18 @@ public LoanQueryResult queryLoan(String asset, String txId) { return executeSync(binanceApiService.queryLoan(asset, txId, timestamp)); } + @Override + public RepayQueryResult queryRepay(String asset, String txId) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryRepay(asset, txId, timestamp)); + } + + @Override + public RepayQueryResult queryRepay(String asset, long startTime) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryRepay(asset, startTime, timestamp)); + } + @Override public MarginTransaction repay(String asset, String amount) { long timestamp = System.currentTimeMillis(); diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 3a4220317..1640f90d7 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -182,6 +182,14 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @GET("/sapi/v1/margin/loan") Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) @POST("/sapi/v1/margin/repay") Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java index b9456722f..81d342212 100755 --- a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -2,23 +2,22 @@ import com.binance.api.client.BinanceApiClientFactory; import com.binance.api.client.BinanceApiMarginRestClient; -import com.binance.api.client.domain.TransferType; -import com.binance.api.client.domain.account.*; - -import java.util.List; +import com.binance.api.client.domain.account.MarginTransaction; +import com.binance.api.client.domain.account.RepayQueryResult; /** * Examples on how to get margin account information. */ public class MarginAccountEndpointsLoanQueryExample { - public static void main(String[] args) { - BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); - BinanceApiMarginRestClient client = factory.newMarginRestClient(); - MarginTransaction borrowed = client.borrow("USDT", "310"); - System.out.println(borrowed.getTranId()); - LoanQueryResult queryResult = client.queryLoan("USDT", borrowed.getTranId()); - Loan loan = queryResult.getRows().get(0); - System.out.println(loan.getStatus()); - } + public static void main(String[] args) { + BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); + BinanceApiMarginRestClient client = factory.newMarginRestClient(); + MarginTransaction borrowed = client.borrow("USDT", "310"); + System.out.println(borrowed.getTranId()); + MarginTransaction repaid = client.repay("USDT", "310"); + System.out.println(repaid); + RepayQueryResult repayQueryResult = client.queryRepay("BNB", System.currentTimeMillis() - 1000); + System.out.println(repayQueryResult); + } } From 6b1a42f5ec7b1f7d209a65bbbccd029f4573276b Mon Sep 17 00:00:00 2001 From: Truong Ha Date: Fri, 1 May 2020 13:33:17 +0700 Subject: [PATCH 52/83] Added endpoint to get max borrowable --- .../client/BinanceApiMarginRestClient.java | 9 +++++- .../account/MaxBorrowableQueryResult.java | 31 +++++++++++++++++++ .../impl/BinanceApiMarginRestClientImpl.java | 6 ++++ .../api/client/impl/BinanceApiService.java | 4 +++ ...arginAccountEndpointsLoanQueryExample.java | 5 +++ 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100755 src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java index 527073b96..681a8db96 100755 --- a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -88,10 +88,17 @@ public interface BinanceApiMarginRestClient { /** * Query loan record * @param asset asset to query - * @return loan records + * @return repay records */ RepayQueryResult queryRepay(String asset, long startTime); + /** + * Query max borrowable + * @param asset asset to query + * @return max borrowable + */ + MaxBorrowableQueryResult queryMaxBorrowable(String asset); + /** * Query loan record * @param asset asset to query diff --git a/src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java b/src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java new file mode 100755 index 000000000..8a50fdea4 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/MaxBorrowableQueryResult.java @@ -0,0 +1,31 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** + * Max Borrow Query Result + * + * @see Withdraw + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public class MaxBorrowableQueryResult { + + private String amount; + + public String getAmount() { + return amount; + } + + public void setAmount(String amount) { + this.amount = amount; + } + + @Override + public String toString() { + return "MaxBorrowQueryResult{" + + "amount='" + amount + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java index 5e88373e5..b4322fd70 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -105,6 +105,12 @@ public RepayQueryResult queryRepay(String asset, long startTime) { return executeSync(binanceApiService.queryRepay(asset, startTime, timestamp)); } + @Override + public MaxBorrowableQueryResult queryMaxBorrowable(String asset) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.queryMaxBorrowable(asset, timestamp)); + } + @Override public MarginTransaction repay(String asset, String amount) { long timestamp = System.currentTimeMillis(); diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 1640f90d7..60ca96488 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -186,6 +186,10 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @GET("/sapi/v1/margin/repay") Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/maxBorrowable") + Call queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp); + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) @GET("/sapi/v1/margin/repay") Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); diff --git a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java index 81d342212..4cc4bf01f 100755 --- a/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java +++ b/src/test/java/com/binance/api/examples/MarginAccountEndpointsLoanQueryExample.java @@ -3,6 +3,7 @@ import com.binance.api.client.BinanceApiClientFactory; import com.binance.api.client.BinanceApiMarginRestClient; import com.binance.api.client.domain.account.MarginTransaction; +import com.binance.api.client.domain.account.MaxBorrowableQueryResult; import com.binance.api.client.domain.account.RepayQueryResult; /** @@ -13,6 +14,10 @@ public class MarginAccountEndpointsLoanQueryExample { public static void main(String[] args) { BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance("YOUR_API_KEY", "YOUR_SECRET"); BinanceApiMarginRestClient client = factory.newMarginRestClient(); + MaxBorrowableQueryResult usdt = client.queryMaxBorrowable("USDT"); + System.out.println(usdt.getAmount()); + MaxBorrowableQueryResult bnb = client.queryMaxBorrowable("BNB"); + System.out.println(bnb.getAmount()); MarginTransaction borrowed = client.borrow("USDT", "310"); System.out.println(borrowed.getTranId()); MarginTransaction repaid = client.repay("USDT", "310"); From 2b6eaf10c49564c0a1a1732ce64e60c8c46c5b54 Mon Sep 17 00:00:00 2001 From: Jose Miguel Resendiz Date: Sat, 2 May 2020 13:12:03 -0500 Subject: [PATCH 53/83] Add WebSocket BookTickerEvent --- .../api/client/BinanceApiWebSocketClient.java | 15 ++- .../client/domain/event/BookTickerEvent.java | 113 ++++++++++++++++++ .../impl/BinanceApiWebSocketClientImpl.java | 15 ++- 3 files changed, 133 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java index 1e8421e79..cf8a34fde 100644 --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -1,10 +1,6 @@ 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; @@ -60,6 +56,15 @@ public interface BinanceApiWebSocketClient extends Closeable { */ 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); + /** * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. */ 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 100644 index 000000000..326d29e9a --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java @@ -0,0 +1,113 @@ +package com.binance.api.client.domain.event; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +import com.binance.api.client.constant.BinanceApiConstants; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 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/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index e9be1f690..1ca78716e 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -4,11 +4,7 @@ import com.binance.api.client.BinanceApiWebSocketClient; import com.binance.api.client.config.BinanceApiConfig; import com.binance.api.client.constant.BinanceApiConstants; -import com.binance.api.client.domain.event.AggTradeEvent; -import com.binance.api.client.domain.event.AllMarketTickersEvent; -import com.binance.api.client.domain.event.CandlestickEvent; -import com.binance.api.client.domain.event.DepthEvent; -import com.binance.api.client.domain.event.UserDataUpdateEvent; +import com.binance.api.client.domain.event.*; import com.binance.api.client.domain.market.CandlestickInterval; import com.fasterxml.jackson.core.type.TypeReference; @@ -67,6 +63,15 @@ public Closeable onAllMarketTickersEvent(BinanceApiCallback(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)); + } + /** * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. */ From 53d81ca8b6643331456a5e88496e950508ab211a Mon Sep 17 00:00:00 2001 From: Yani Ferhaoui Date: Fri, 31 Jul 2020 15:50:46 +0200 Subject: [PATCH 54/83] Add Method --- .../api/client/BinanceApiRestClient.java | 2 + .../client/impl/BinanceApiRestClientImpl.java | 426 +++++++++--------- 2 files changed, 224 insertions(+), 204 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index f05cc0268..99b1e3488 100644 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -238,6 +238,8 @@ public interface BinanceApiRestClient { * @return a list of trades */ List getMyTrades(String symbol); + + List getMyTrades(String symbol, Long fromId); /** * Submit a withdraw request. diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index c1cd07f62..31cd4130e 100644 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -16,211 +16,229 @@ 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()); - } - - @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 Account getAccount(Long recvWindow, Long timestamp) { - return executeSync(binanceApiService.getAccount(recvWindow, timestamp)); - } - - @Override - public Account getAccount() { - return getAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public List getMyTrades(String symbol, Integer limit, Long fromId, Long recvWindow, Long timestamp) { - return executeSync(binanceApiService.getMyTrades(symbol, limit, fromId, recvWindow, timestamp)); - } - - @Override - public List getMyTrades(String symbol, Integer limit) { - return getMyTrades(symbol, limit, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public List getMyTrades(String symbol) { - return getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()); - } - - @Override - public WithdrawResult withdraw(String asset, String address, String amount, String name, String addressTag) { - return executeSync(binanceApiService.withdraw(asset, address, amount, name, addressTag, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public DepositHistory getDepositHistory(String asset) { - return executeSync(binanceApiService.getDepositHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public WithdrawHistory getWithdrawHistory(String asset) { - return executeSync(binanceApiService.getWithdrawHistory(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - @Override - public DepositAddress getDepositAddress(String asset) { - return executeSync(binanceApiService.getDepositAddress(asset, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - // User stream endpoints - - @Override - public String startUserDataStream() { - return executeSync(binanceApiService.startUserDataStream()).toString(); - } - - @Override - public void keepAliveUserDataStream(String listenKey) { - executeSync(binanceApiService.keepAliveUserDataStream(listenKey)); - } - - @Override - public void closeUserDataStream(String listenKey) { - executeSync(binanceApiService.closeAliveUserDataStream(listenKey)); - } + 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 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 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)); + } } From c0867fb0b91b8f274dda8fceeeac814894c39fce Mon Sep 17 00:00:00 2001 From: Yani Ferhaoui Date: Thu, 3 Sep 2020 10:51:55 +0200 Subject: [PATCH 55/83] add MAX_POSITION in FilterType --- .../com/binance/api/client/domain/general/FilterType.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 1959f8ec5..a8a3ea55c 100644 --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -21,5 +21,8 @@ public enum FilterType { // Exchange EXCHANGE_MAX_NUM_ORDERS, - EXCHANGE_MAX_ALGO_ORDERS + EXCHANGE_MAX_ALGO_ORDERS, + + // Other + MAX_POSITION } From 8dea1864e2cdcc54766cd83e47ed88fcd1154c9e Mon Sep 17 00:00:00 2001 From: Fenix Date: Thu, 3 Sep 2020 20:28:41 +0700 Subject: [PATCH 56/83] Add filter MAX_POSITIION --- .../java/com/binance/api/client/domain/general/FilterType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/binance/api/client/domain/general/FilterType.java b/src/main/java/com/binance/api/client/domain/general/FilterType.java index 8dd26c46a..72ad3b41e 100755 --- a/src/main/java/com/binance/api/client/domain/general/FilterType.java +++ b/src/main/java/com/binance/api/client/domain/general/FilterType.java @@ -18,6 +18,7 @@ public enum FilterType { PERCENT_PRICE, MARKET_LOT_SIZE, MAX_NUM_ICEBERG_ORDERS, + MAX_POSITION, // Exchange EXCHANGE_MAX_NUM_ORDERS, From a7189e2547a43980dce0d0766733007ed7e74fd0 Mon Sep 17 00:00:00 2001 From: Ha Truong Date: Sun, 27 Sep 2020 11:08:39 +0700 Subject: [PATCH 57/83] Binance Liquid Swap endpoints --- .../api/client/BinanceApiClientFactory.java | 7 + .../api/client/BinanceApiSwapRestClient.java | 94 ++++ .../api/client/domain/SwapOperationType.java | 8 + .../api/client/domain/SwapRemoveType.java | 8 + .../api/client/domain/account/Liquidity.java | 102 +++++ .../account/LiquidityOperationRecord.java | 83 ++++ .../api/client/domain/account/Pool.java | 43 ++ .../client/domain/account/SwapHistory.java | 101 +++++ .../api/client/domain/account/SwapQuote.java | 81 ++++ .../api/client/domain/account/SwapRecord.java | 21 + .../api/client/domain/account/SwapStatus.java | 18 + .../api/client/impl/BinanceApiService.java | 422 ++++++++++-------- .../impl/BinanceApiServiceGenerator.java | 2 - .../impl/BinanceApiSwapRestClientImpl.java | 115 +++++ .../api/examples/SwapEndpointExample.java | 32 ++ 15 files changed, 960 insertions(+), 177 deletions(-) create mode 100755 src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java create mode 100644 src/main/java/com/binance/api/client/domain/SwapOperationType.java create mode 100644 src/main/java/com/binance/api/client/domain/SwapRemoveType.java create mode 100644 src/main/java/com/binance/api/client/domain/account/Liquidity.java create mode 100644 src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java create mode 100644 src/main/java/com/binance/api/client/domain/account/Pool.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapHistory.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapQuote.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapRecord.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SwapStatus.java create mode 100755 src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java create mode 100644 src/test/java/com/binance/api/examples/SwapEndpointExample.java diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java index a529e237c..842ad20d5 100755 --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -85,4 +85,11 @@ public BinanceApiMarginRestClient newMarginRestClient() { public BinanceApiWebSocketClient newWebSocketClient() { return new BinanceApiWebSocketClientImpl(getSharedClient()); } + + /** + * Creates a new synchronous/blocking Swap REST client. + */ + public BinanceApiSwapRestClient newSwapRestClient() { + return new BinanceApiSwapRestClientImpl(apiKey, secret); + } } diff --git a/src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java b/src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java new file mode 100755 index 000000000..f7baf2c2e --- /dev/null +++ b/src/main/java/com/binance/api/client/BinanceApiSwapRestClient.java @@ -0,0 +1,94 @@ +package com.binance.api.client; + +import com.binance.api.client.domain.SwapRemoveType; +import com.binance.api.client.domain.account.*; +import retrofit2.Call; +import retrofit2.http.Query; + +import java.util.List; + +public interface BinanceApiSwapRestClient { + + /** + * Get metadata about all swap pools. + * + * @return + */ + List listAllSwapPools(); + + /** + * Get liquidity information and user share of a pool. + * + * @param poolId + * @return + */ + Liquidity getPoolLiquidityInfo(String poolId); + + /** + * Add liquidity to a pool. + * + * @param poolId + * @param asset + * @param quantity + * @return + */ + LiquidityOperationRecord addLiquidity(String poolId, + String asset, + String quantity); + + /** + * Remove liquidity from a pool, type include SINGLE and COMBINATION, asset is mandatory for single asset removal + * + * @param poolId + * @param type + * @param asset + * @param shareAmount + * @return + */ + LiquidityOperationRecord removeLiquidity(String poolId, SwapRemoveType type, List asset, String shareAmount); + + /** + * Get liquidity operation (add/remove) records of a pool + * + * @param poolId + * @param limit + * @return + */ + List getPoolLiquidityOperationRecords( + String poolId, + Integer limit); + + /** + * Get liquidity operation (add/remove) record. + * + * @param operationId + * @return + */ + LiquidityOperationRecord getLiquidityOperationRecord(String operationId); + + /** + * Request a quote for swap quote asset (selling asset) for base asset (buying asset), essentially price/exchange rates. + * + * @param quoteAsset + * @param baseAsset + * @param quoteQty + * @return + */ + SwapQuote requestQuote(String quoteAsset, + String baseAsset, + String quoteQty); + + /** + * Swap quoteAsset for baseAsset + * + * @param quoteAsset + * @param baseAsset + * @param quoteQty + * @return + */ + SwapRecord swap(String quoteAsset, + String baseAsset, + String quoteQty); + + SwapHistory getSwapHistory(String swapId); +} diff --git a/src/main/java/com/binance/api/client/domain/SwapOperationType.java b/src/main/java/com/binance/api/client/domain/SwapOperationType.java new file mode 100644 index 000000000..3561e5209 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/SwapOperationType.java @@ -0,0 +1,8 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SwapOperationType { + ADD, REMOVE +} diff --git a/src/main/java/com/binance/api/client/domain/SwapRemoveType.java b/src/main/java/com/binance/api/client/domain/SwapRemoveType.java new file mode 100644 index 000000000..64db76453 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/SwapRemoveType.java @@ -0,0 +1,8 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SwapRemoveType { + SINGLE, COMBINATION +} diff --git a/src/main/java/com/binance/api/client/domain/account/Liquidity.java b/src/main/java/com/binance/api/client/domain/account/Liquidity.java new file mode 100644 index 000000000..83eee88a3 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Liquidity.java @@ -0,0 +1,102 @@ +package com.binance.api.client.domain.account; + +import java.util.Map; + +public class Liquidity { + + private String poolId; + private String poolName; + private Long updateTime; + private Map liquidity; + private Share share; + + public String getPoolId() { + return poolId; + } + + public void setPoolId(String poolId) { + this.poolId = poolId; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + public Long getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Long updateTime) { + this.updateTime = updateTime; + } + + public Map getLiquidity() { + return liquidity; + } + + public void setLiquidity(Map liquidity) { + this.liquidity = liquidity; + } + + public Share getShare() { + return share; + } + + public void setShare(Share share) { + this.share = share; + } + + public static class Share { + private double shareAmount; + private double sharePercentage; + private Map asset; + + public double getShareAmount() { + return shareAmount; + } + + public void setShareAmount(double shareAmount) { + this.shareAmount = shareAmount; + } + + public double getSharePercentage() { + return sharePercentage; + } + + public void setSharePercentage(double sharePercentage) { + this.sharePercentage = sharePercentage; + } + + public Map getAsset() { + return asset; + } + + public void setAsset(Map asset) { + this.asset = asset; + } + + @Override + public String toString() { + return "Share{" + + "shareAmount=" + shareAmount + + ", sharePercentage=" + sharePercentage + + ", asset=" + asset + + '}'; + } + } + + @Override + public String toString() { + return "Liquidity{" + + "poolId=" + poolId + + ", poolName='" + poolName + '\'' + + ", updateTime=" + updateTime + + ", liquidity=" + liquidity + + ", share=" + share + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java new file mode 100644 index 000000000..65b68cf84 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java @@ -0,0 +1,83 @@ +package com.binance.api.client.domain.account; + +import com.binance.api.client.domain.SwapOperationType; + +public class LiquidityOperationRecord { + + private String poolId; + private String operationId; + private String updateTime; + private String operation; + private String shareAmount; + private String poolName; + private SwapOperationType status; + + public String getPoolId() { + return poolId; + } + + public void setPoolId(String poolId) { + this.poolId = poolId; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getShareAmount() { + return shareAmount; + } + + public void setShareAmount(String shareAmount) { + this.shareAmount = shareAmount; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + public SwapOperationType getStatus() { + return status; + } + + public void setStatus(SwapOperationType status) { + this.status = status; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + @Override + public String toString() { + return "LiquidityOperationRecord{" + + "poolId='" + poolId + '\'' + + ", operationId='" + operationId + '\'' + + ", updateTime='" + updateTime + '\'' + + ", operation='" + operation + '\'' + + ", shareAmount='" + shareAmount + '\'' + + ", poolName='" + poolName + '\'' + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/Pool.java b/src/main/java/com/binance/api/client/domain/account/Pool.java new file mode 100644 index 000000000..413d301f2 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/Pool.java @@ -0,0 +1,43 @@ +package com.binance.api.client.domain.account; + +import java.util.List; + +public class Pool { + + private String poolId; + private String poolName; + private List assets; + + public String getPoolId() { + return poolId; + } + + public void setPoolId(String poolId) { + this.poolId = poolId; + } + + public List getAssets() { + return assets; + } + + public void setAssets(List assets) { + this.assets = assets; + } + + public String getPoolName() { + return poolName; + } + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + @Override + public String toString() { + return "Pool{" + + "poolId='" + poolId + '\'' + + ", poolName='" + poolName + '\'' + + ", assets=" + assets + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/SwapHistory.java b/src/main/java/com/binance/api/client/domain/account/SwapHistory.java new file mode 100644 index 000000000..b4c7c785c --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapHistory.java @@ -0,0 +1,101 @@ +package com.binance.api.client.domain.account; + +public class SwapHistory { + + private String quoteQty; + private Long swapTime; + private String swapId; + private String price; + private String fee; + private String baseQty; + private String baseAsset; + private String quoteAsset; + private SwapStatus status; + + public String getQuoteQty() { + return quoteQty; + } + + public void setQuoteQty(String quoteQty) { + this.quoteQty = quoteQty; + } + + public Long getSwapTime() { + return swapTime; + } + + public void setSwapTime(Long swapTime) { + this.swapTime = swapTime; + } + + public String getSwapId() { + return swapId; + } + + public void setSwapId(String swapId) { + this.swapId = swapId; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getFee() { + return fee; + } + + public void setFee(String fee) { + this.fee = fee; + } + + public String getBaseQty() { + return baseQty; + } + + public void setBaseQty(String baseQty) { + this.baseQty = baseQty; + } + + public String getBaseAsset() { + return baseAsset; + } + + public void setBaseAsset(String baseAsset) { + this.baseAsset = baseAsset; + } + + public String getQuoteAsset() { + return quoteAsset; + } + + public void setQuoteAsset(String quoteAsset) { + this.quoteAsset = quoteAsset; + } + + public SwapStatus getStatus() { + return status; + } + + public void setStatus(SwapStatus status) { + this.status = status; + } + + @Override + public String toString() { + return "SwapHistory{" + + "quoteQty='" + quoteQty + '\'' + + ", swapTime=" + swapTime + + ", swapId='" + swapId + '\'' + + ", price='" + price + '\'' + + ", fee='" + fee + '\'' + + ", baseQty='" + baseQty + '\'' + + ", baseAsset='" + baseAsset + '\'' + + ", quoteAsset='" + quoteAsset + '\'' + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/SwapQuote.java b/src/main/java/com/binance/api/client/domain/account/SwapQuote.java new file mode 100644 index 000000000..c776750f8 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapQuote.java @@ -0,0 +1,81 @@ +package com.binance.api.client.domain.account; + +public class SwapQuote { + private String quoteQty; + private String price; + private String fee; + private String baseQty; + private String baseAsset; + private String slippage; + private String quoteAsset; + + public String getQuoteQty() { + return quoteQty; + } + + public void setQuoteQty(String quoteQty) { + this.quoteQty = quoteQty; + } + + public String getPrice() { + return price; + } + + public void setPrice(String price) { + this.price = price; + } + + public String getFee() { + return fee; + } + + public void setFee(String fee) { + this.fee = fee; + } + + public String getBaseQty() { + return baseQty; + } + + public void setBaseQty(String baseQty) { + this.baseQty = baseQty; + } + + public String getBaseAsset() { + return baseAsset; + } + + public void setBaseAsset(String baseAsset) { + this.baseAsset = baseAsset; + } + + public String getSlippage() { + return slippage; + } + + public void setSlippage(String slippage) { + this.slippage = slippage; + } + + public String getQuoteAsset() { + return quoteAsset; + } + + public void setQuoteAsset(String quoteAsset) { + this.quoteAsset = quoteAsset; + } + + @Override + public String toString() { + return "SwapQuote{" + + "quoteQty='" + quoteQty + '\'' + + ", price='" + price + '\'' + + ", fee='" + fee + '\'' + + ", baseQty='" + baseQty + '\'' + + ", baseAsset='" + baseAsset + '\'' + + ", slippage='" + slippage + '\'' + + ", quoteAsset='" + quoteAsset + '\'' + + '}'; + } +} + diff --git a/src/main/java/com/binance/api/client/domain/account/SwapRecord.java b/src/main/java/com/binance/api/client/domain/account/SwapRecord.java new file mode 100644 index 000000000..085af3068 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapRecord.java @@ -0,0 +1,21 @@ +package com.binance.api.client.domain.account; + +public class SwapRecord { + + private String swapId; + + public String getSwapId() { + return swapId; + } + + public void setSwapId(String swapId) { + this.swapId = swapId; + } + + @Override + public String toString() { + return "SwapRecord{" + + "swapId='" + swapId + '\'' + + '}'; + } +} diff --git a/src/main/java/com/binance/api/client/domain/account/SwapStatus.java b/src/main/java/com/binance/api/client/domain/account/SwapStatus.java new file mode 100644 index 000000000..b1a0dc9eb --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SwapStatus.java @@ -0,0 +1,18 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonValue; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum SwapStatus { + PENDING, + SUCCESS, + FAILED; + + @JsonValue + public int toValue() { + return ordinal(); + } +} + + diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 60ca96488..c940a370c 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -3,6 +3,7 @@ import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.OrderSide; import com.binance.api.client.domain.OrderType; +import com.binance.api.client.domain.SwapRemoveType; import com.binance.api.client.domain.TimeInForce; import com.binance.api.client.domain.account.*; import com.binance.api.client.domain.account.request.CancelOrderResponse; @@ -32,210 +33,281 @@ */ public interface BinanceApiService { - // General endpoints + // General endpoints - @GET("/api/v1/ping") - Call ping(); + @GET("/api/v1/ping") + Call ping(); - @GET("/api/v1/time") - Call getServerTime(); + @GET("/api/v1/time") + Call getServerTime(); - @GET("/api/v1/exchangeInfo") - Call getExchangeInfo(); + @GET("/api/v1/exchangeInfo") + Call getExchangeInfo(); - @GET - Call> getAllAssets(@Url String url); + @GET + Call> getAllAssets(@Url String url); - // Market data endpoints + // Market data endpoints - @GET("/api/v1/depth") - Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); + @GET("/api/v1/depth") + Call getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit); - @GET("/api/v1/trades") - Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); + @GET("/api/v1/trades") + Call> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @GET("/api/v1/historicalTrades") - Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @GET("/api/v1/historicalTrades") + Call> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId); - @GET("/api/v1/aggTrades") - Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); + @GET("/api/v1/aggTrades") + Call> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); - @GET("/api/v1/klines") - Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, - @Query("startTime") Long startTime, @Query("endTime") Long endTime); + @GET("/api/v1/klines") + Call> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit, + @Query("startTime") Long startTime, @Query("endTime") Long endTime); - @GET("/api/v1/ticker/24hr") - Call get24HrPriceStatistics(@Query("symbol") String symbol); + @GET("/api/v1/ticker/24hr") + Call get24HrPriceStatistics(@Query("symbol") String symbol); - @GET("/api/v1/ticker/24hr") - Call> getAll24HrPriceStatistics(); + @GET("/api/v1/ticker/24hr") + Call> getAll24HrPriceStatistics(); - @GET("/api/v1/ticker/allPrices") - Call> getLatestPrices(); + @GET("/api/v1/ticker/allPrices") + Call> getLatestPrices(); - @GET("/api/v3/ticker/price") - Call getLatestPrice(@Query("symbol") String symbol); + @GET("/api/v3/ticker/price") + Call getLatestPrice(@Query("symbol") String symbol); - @GET("/api/v1/ticker/allBookTickers") - Call> getBookTickers(); + @GET("/api/v1/ticker/allBookTickers") + Call> getBookTickers(); - // Account endpoints + // Account endpoints - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order") - Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order") - Call newOrderQuoteQty(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quoteOrderQty") String quoteOrderQty, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/api/v3/order/test") - Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/order") - Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, - @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @DELETE("/api/v3/order") - Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/openOrders") - Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/allOrders") - Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/account") - Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/api/v3/myTrades") - Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/wapi/v3/withdraw.html") - Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order") + Call newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order") + Call newOrderQuoteQty(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quoteOrderQty") String quoteOrderQty, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositHistory.html") - Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/api/v3/order/test") + Call newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/withdrawHistory.html") - Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/order") + Call getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/wapi/v3/depositAddress.html") - Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/api/v3/order") + Call cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - // User stream endpoints + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/openOrders") + Call> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @POST("/api/v1/userDataStream") - Call startUserDataStream(); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/allOrders") + Call> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @PUT("/api/v1/userDataStream") - Call keepAliveUserDataStream(@Query("listenKey") String listenKey); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/account") + Call getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @DELETE("/api/v1/userDataStream") - Call closeAliveUserDataStream(@Query("listenKey") String listenKey); - - // Margin Account endpoints - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @POST("/sapi/v1/margin/transfer") - Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @POST("/sapi/v1/margin/loan") - Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/loan") - Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/repay") - Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); - - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/maxBorrowable") - Call queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/api/v3/myTrades") + Call> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/repay") - Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/wapi/v3/withdraw.html") + Call withdraw(@Query("asset") String asset, @Query("address") String address, @Query("amount") String amount, @Query("name") String name, @Query("addressTag") String addressTag, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @POST("/sapi/v1/margin/repay") - Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/account") - Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositHistory.html") + Call getDepositHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/withdrawHistory.html") + Call getWithdrawHistory(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/wapi/v3/depositAddress.html") + Call getDepositAddress(@Query("asset") String asset, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + // User stream endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/api/v1/userDataStream") + Call startUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/api/v1/userDataStream") + Call keepAliveUserDataStream(@Query("listenKey") String listenKey); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @DELETE("/api/v1/userDataStream") + Call closeAliveUserDataStream(@Query("listenKey") String listenKey); + + // Margin Account endpoints + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/transfer") + Call transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/loan") + Call borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/loan") + Call queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/maxBorrowable") + Call queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/repay") + Call queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/margin/repay") + Call repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/account") + Call getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/margin/openOrders") + Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @POST("/sapi/v1/margin/order") + Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, + @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, + @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, + @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @DELETE("/sapi/v1/margin/order") + Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/order") + Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, + @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) + @GET("/sapi/v1/margin/myTrades") + Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, + @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) - @GET("/sapi/v1/margin/openOrders") - Call> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @POST("/sapi/v1/userDataStream") + Call startMarginUserDataStream(); + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @PUT("/sapi/v1/userDataStream") + Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); + + // Binance Liquidity Swap Pool endpoints + + @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) + @GET("/sapi/v1/bswap/pools") + Call> listAllSwapPools(); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/liquidity") + Call> getPoolLiquidityInfo(@Query("poolId") String poolId, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/bswap/liquidityAdd") + Call addLiquidity(@Query("poolId") String poolId, + @Query("asset") String asset, + @Query("quantity") String quantity, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/bswap/liquidityRemove") + Call removeLiquidity(@Query("poolId") String poolId, + @Query("type") SwapRemoveType type, + @Query("asset") List asset, + @Query("shareAmount") String shareAmount, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/liquidityOps") + Call> getPoolLiquidityOperationRecords( + @Query("poolId") String poolId, + @Query("limit") Integer limit, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/liquidityOps") + Call> getLiquidityOperationRecord( + @Query("operationId") String operationId, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/quote") + Call requestQuote( + @Query("quoteAsset") String quoteAsset, + @Query("baseAsset") String baseAsset, + @Query("quoteQty") String quoteQty, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @POST("/sapi/v1/bswap/swap") + Call swap( + @Query("quoteAsset") String quoteAsset, + @Query("baseAsset") String baseAsset, + @Query("quoteQty") String quoteQty, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); + + @Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER}) + @GET("/sapi/v1/bswap/swap") + Call> getSwapHistory( + @Query("swapId") String swapId, + @Query("recvWindow") Long recvWindow, + @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @POST("/sapi/v1/margin/order") - Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @DELETE("/sapi/v1/margin/order") - Call cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/sapi/v1/margin/order") - Call getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId, - @Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow, - @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) - @GET("/sapi/v1/margin/myTrades") - Call> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @POST("/sapi/v1/userDataStream") - Call startMarginUserDataStream(); - - @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) - @PUT("/sapi/v1/userDataStream") - Call keepAliveMarginUserDataStream(@Query("listenKey") String listenKey); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 7bab3ad1e..1bd11a9e2 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -2,12 +2,10 @@ import com.binance.api.client.BinanceApiError; import com.binance.api.client.config.BinanceApiConfig; -import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.exception.BinanceApiException; import com.binance.api.client.security.AuthenticationInterceptor; import okhttp3.Dispatcher; import okhttp3.OkHttpClient; -import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.apache.commons.lang3.StringUtils; import retrofit2.Call; diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java new file mode 100755 index 000000000..4f1a18bc4 --- /dev/null +++ b/src/main/java/com/binance/api/client/impl/BinanceApiSwapRestClientImpl.java @@ -0,0 +1,115 @@ +package com.binance.api.client.impl; + +import com.binance.api.client.BinanceApiSwapRestClient; +import com.binance.api.client.constant.BinanceApiConstants; +import com.binance.api.client.domain.SwapRemoveType; +import com.binance.api.client.domain.account.*; + +import java.util.List; + +import static com.binance.api.client.impl.BinanceApiServiceGenerator.createService; +import static com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync; + +/** + * Implementation of Binance's SWAP REST API using Retrofit method calls. + */ +public class BinanceApiSwapRestClientImpl implements BinanceApiSwapRestClient { + + private final BinanceApiService binanceApiService; + + public BinanceApiSwapRestClientImpl(String apiKey, String secret) { + binanceApiService = createService(BinanceApiService.class, apiKey, secret); + } + + @Override + public List listAllSwapPools() { + return executeSync(binanceApiService.listAllSwapPools()); + } + + @Override + public Liquidity getPoolLiquidityInfo(String poolId) { + long timestamp = System.currentTimeMillis(); + List liquidities = executeSync(binanceApiService.getPoolLiquidityInfo(poolId, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + if (liquidities != null && !liquidities.isEmpty()) { + return liquidities.get(0); + } + return null; + } + + @Override + public LiquidityOperationRecord addLiquidity(String poolId, String asset, String quantity) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.addLiquidity(poolId, + asset, + quantity, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public LiquidityOperationRecord removeLiquidity(String poolId, SwapRemoveType type, List asset, String shareAmount) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.removeLiquidity(poolId, + type, + asset, + shareAmount, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public List getPoolLiquidityOperationRecords(String poolId, Integer limit) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.getPoolLiquidityOperationRecords( + poolId, + limit, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + + } + + @Override + public LiquidityOperationRecord getLiquidityOperationRecord(String operationId) { + long timestamp = System.currentTimeMillis(); + List records = executeSync(binanceApiService.getLiquidityOperationRecord( + operationId, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + if (records != null && !records.isEmpty()) { + return records.get(0); + } + return null; + } + + @Override + public SwapQuote requestQuote(String quoteAsset, + String baseAsset, + String quoteQty) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.requestQuote(quoteAsset, baseAsset, quoteQty, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public SwapRecord swap(String quoteAsset, String baseAsset, String quoteQty) { + long timestamp = System.currentTimeMillis(); + return executeSync(binanceApiService.swap(quoteAsset, baseAsset, quoteQty, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + } + + @Override + public SwapHistory getSwapHistory(String swapId) { + long timestamp = System.currentTimeMillis(); + List history = executeSync(binanceApiService.getSwapHistory(swapId, + BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, + timestamp)); + if (history != null && !history.isEmpty()) { + return history.get(0); + } + return null; + } +} \ No newline at end of file diff --git a/src/test/java/com/binance/api/examples/SwapEndpointExample.java b/src/test/java/com/binance/api/examples/SwapEndpointExample.java new file mode 100644 index 000000000..c4c32d98d --- /dev/null +++ b/src/test/java/com/binance/api/examples/SwapEndpointExample.java @@ -0,0 +1,32 @@ +package com.binance.api.examples; + +import com.binance.api.client.BinanceApiClientFactory; +import com.binance.api.client.BinanceApiSwapRestClient; +import com.binance.api.client.domain.account.*; + +import java.util.List; + +public class SwapEndpointExample { + + public static String API_KEY = "api-key"; + public static String SECRET_KEY = "secret-key"; + + public static void main(String[] args) { + + BinanceApiClientFactory binanceApiClientFactory = BinanceApiClientFactory.newInstance(API_KEY, SECRET_KEY); + BinanceApiSwapRestClient swapClient = binanceApiClientFactory.newSwapRestClient(); + List pools = swapClient.listAllSwapPools(); + for(Pool pool:pools) { + System.out.println(pool); + Liquidity poolLiquidityInfo = swapClient.getPoolLiquidityInfo(pool.getPoolId()); + System.out.println(poolLiquidityInfo); + } + SwapQuote swapQuote = swapClient.requestQuote("USDT", "USDC", "10"); + System.out.println(swapQuote); + SwapRecord swapRecord = swapClient.swap("USDT", "USDC", "10"); + SwapHistory swapHistory = swapClient.getSwapHistory(swapRecord.getSwapId()); + System.out.println(swapHistory); + } + + +} From 8524e77dd48bb3ba87fbb95326a232a67d8a3469 Mon Sep 17 00:00:00 2001 From: Fenix Date: Sun, 27 Sep 2020 21:49:31 +0700 Subject: [PATCH 58/83] Fixed issue with status value --- .../domain/LiquidityOperationRecordStatus.java | 16 ++++++++++++++++ .../api/client/domain/SwapOperationType.java | 8 -------- .../domain/account/LiquidityOperationRecord.java | 8 ++++---- 3 files changed, 20 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java delete mode 100644 src/main/java/com/binance/api/client/domain/SwapOperationType.java diff --git a/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java b/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java new file mode 100644 index 000000000..2574a38e3 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java @@ -0,0 +1,16 @@ +package com.binance.api.client.domain; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonValue; + +@JsonIgnoreProperties(ignoreUnknown = true) +public enum LiquidityOperationRecordStatus { + PENDING, + SUCCESS, + FAILED; + + @JsonValue + public int toValue() { + return ordinal(); + } +} diff --git a/src/main/java/com/binance/api/client/domain/SwapOperationType.java b/src/main/java/com/binance/api/client/domain/SwapOperationType.java deleted file mode 100644 index 3561e5209..000000000 --- a/src/main/java/com/binance/api/client/domain/SwapOperationType.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.binance.api.client.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public enum SwapOperationType { - ADD, REMOVE -} diff --git a/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java index 65b68cf84..2ce393f1c 100644 --- a/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java +++ b/src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java @@ -1,6 +1,6 @@ package com.binance.api.client.domain.account; -import com.binance.api.client.domain.SwapOperationType; +import com.binance.api.client.domain.LiquidityOperationRecordStatus; public class LiquidityOperationRecord { @@ -10,7 +10,7 @@ public class LiquidityOperationRecord { private String operation; private String shareAmount; private String poolName; - private SwapOperationType status; + private LiquidityOperationRecordStatus status; public String getPoolId() { return poolId; @@ -52,11 +52,11 @@ public void setPoolName(String poolName) { this.poolName = poolName; } - public SwapOperationType getStatus() { + public LiquidityOperationRecordStatus getStatus() { return status; } - public void setStatus(SwapOperationType status) { + public void setStatus(LiquidityOperationRecordStatus status) { this.status = status; } From c9ff0d997f2e6a375551aefb89ecb2a942b27cff Mon Sep 17 00:00:00 2001 From: Fenix Date: Sat, 3 Oct 2020 10:47:29 +0700 Subject: [PATCH 59/83] no message --- .../domain/account/CrossMarginAssets.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java diff --git a/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java b/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java new file mode 100644 index 000000000..33c5fd906 --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java @@ -0,0 +1,74 @@ +package com.binance.api.client.domain.account; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CrossMarginAssets { + + public String assetFullName; + public String assetName; + public boolean isBorrowable; + public boolean isMortgageable; + public String userMinBorrow; + public String userMinRepay; + + public String getAssetFullName() { + return assetFullName; + } + + public void setAssetFullName(String assetFullName) { + this.assetFullName = assetFullName; + } + + public String getAssetName() { + return assetName; + } + + public void setAssetName(String assetName) { + this.assetName = assetName; + } + + public boolean isBorrowable() { + return isBorrowable; + } + + public void setBorrowable(boolean borrowable) { + isBorrowable = borrowable; + } + + public boolean isMortgageable() { + return isMortgageable; + } + + public void setMortgageable(boolean mortgageable) { + isMortgageable = mortgageable; + } + + public String getUserMinBorrow() { + return userMinBorrow; + } + + public void setUserMinBorrow(String userMinBorrow) { + this.userMinBorrow = userMinBorrow; + } + + public String getUserMinRepay() { + return userMinRepay; + } + + public void setUserMinRepay(String userMinRepay) { + this.userMinRepay = userMinRepay; + } + + @Override + public String toString() { + return "CrossMarginAssets{" + + "assetFullName='" + assetFullName + '\'' + + ", assetName='" + assetName + '\'' + + ", isBorrowable=" + isBorrowable + + ", isMortgageable=" + isMortgageable + + ", userMinBorrow='" + userMinBorrow + '\'' + + ", userMinRepay='" + userMinRepay + '\'' + + '}'; + } +} From a3c0625e8581999bf09bb8e9852b72598d078369 Mon Sep 17 00:00:00 2001 From: Eugen Podaru Date: Fri, 13 Nov 2020 00:34:19 +0100 Subject: [PATCH 60/83] Add ws allBookTickersEvent and tickerEvent --- .../api/client/BinanceApiWebSocketClient.java | 39 ++- .../domain/event/AllMarketTickersEvent.java | 294 ----------------- .../client/domain/event/BookTickerEvent.java | 3 +- .../api/client/domain/event/TickerEvent.java | 295 ++++++++++++++++++ .../impl/BinanceApiWebSocketClientImpl.java | 25 +- 5 files changed, 344 insertions(+), 312 deletions(-) delete mode 100755 src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java create mode 100644 src/main/java/com/binance/api/client/domain/event/TickerEvent.java diff --git a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java index cf8a34fde..bc048d464 100755 --- a/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiWebSocketClient.java @@ -14,8 +14,8 @@ public interface BinanceApiWebSocketClient extends Closeable { /** * Open a new web socket to receive {@link DepthEvent depthEvents} on a callback. * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param callback the callback to call on new events + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param callback the callback to call on new events * @return a {@link Closeable} that allows the underlying web socket to be closed. */ Closeable onDepthEvent(String symbols, BinanceApiCallback callback); @@ -23,9 +23,9 @@ public interface BinanceApiWebSocketClient extends Closeable { /** * Open a new web socket to receive {@link CandlestickEvent candlestickEvents} on a callback. * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param interval the interval of the candles tick events required - * @param callback the callback to call on new events + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param interval the interval of the candles tick events required + * @param callback the callback to call on new events * @return a {@link Closeable} that allows the underlying web socket to be closed. */ Closeable onCandlestickEvent(String symbols, CandlestickInterval interval, BinanceApiCallback callback); @@ -33,8 +33,8 @@ public interface BinanceApiWebSocketClient extends Closeable { /** * Open a new web socket to receive {@link AggTradeEvent aggTradeEvents} on a callback. * - * @param symbols market (one or coma-separated) symbol(s) to subscribe to - * @param callback the callback to call on new events + * @param symbols market (one or coma-separated) symbol(s) to subscribe to + * @param callback the callback to call on new events * @return a {@link Closeable} that allows the underlying web socket to be closed. */ Closeable onAggTradeEvent(String symbols, BinanceApiCallback callback); @@ -49,22 +49,39 @@ 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 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); + 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 + * @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. */ 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 100755 index 459157a8b..000000000 --- a/src/main/java/com/binance/api/client/domain/event/AllMarketTickersEvent.java +++ /dev/null @@ -1,294 +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 String priceChange; - - @JsonProperty("P") - private String priceChangePercent; - - @JsonProperty("w") - private String weightedAveragePrice; - - @JsonProperty("x") - private String previousDaysClosePrice; - - @JsonProperty("c") - private String currentDaysClosePrice; - - @JsonProperty("Q") - private String closeTradesQuantity; - - @JsonProperty("b") - private String bestBidPrice; - - @JsonProperty("B") - private String bestBidQuantity; - - @JsonProperty("a") - private String bestAskPrice; - - @JsonProperty("A") - private String bestAskQuantity; - - @JsonProperty("o") - private String openPrice; - - @JsonProperty("h") - private String highPrice; - - @JsonProperty("l") - private String lowPrice; - - @JsonProperty("v") - private String totalTradedBaseAssetVolume; - - @JsonProperty("q") - private String totalTradedQuoteAssetVolume; - - @JsonProperty("O") - private long statisticesOpenTime; - - @JsonProperty("C") - private long statisticesCloseTime; - - @JsonProperty("F") - private long firstTradeId; - - @JsonProperty("L") - private long lastTradeId; - - @JsonProperty("n") - private long totalNumberOfTrades; - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public long getEventTime() { - return eventTime; - } - - public void setEventTime(long eventTime) { - this.eventTime = eventTime; - } - - public String getSymbol() { - return symbol; - } - - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - public String getPriceChange() { - return priceChange; - } - - public void setPriceChange(String priceChange) { - this.priceChange = priceChange; - } - - public String getPriceChangePercent() { - return priceChangePercent; - } - - public void setPriceChangePercent(String priceChangePercent) { - this.priceChangePercent = priceChangePercent; - } - - public String getWeightedAveragePrice() { - return weightedAveragePrice; - } - - public void setWeightedAveragePrice(String weightedAveragePrice) { - this.weightedAveragePrice = weightedAveragePrice; - } - - public String getPreviousDaysClosePrice() { - return previousDaysClosePrice; - } - - public void setPreviousDaysClosePrice(String previousDaysClosePrice) { - this.previousDaysClosePrice = previousDaysClosePrice; - } - - public String getCurrentDaysClosePrice() { - return currentDaysClosePrice; - } - - public void setCurrentDaysClosePrice(String currentDaysClosePrice) { - this.currentDaysClosePrice = currentDaysClosePrice; - } - - public String getCloseTradesQuantity() { - return closeTradesQuantity; - } - - public void setCloseTradesQuantity(String closeTradesQuantity) { - this.closeTradesQuantity = closeTradesQuantity; - } - - public String getBestBidPrice() { - return bestBidPrice; - } - - public void setBestBidPrice(String bestBidPrice) { - this.bestBidPrice = bestBidPrice; - } - - public String getBestBidQuantity() { - return bestBidQuantity; - } - - public void setBestBidQuantity(String bestBidQuantity) { - this.bestBidQuantity = bestBidQuantity; - } - - public String getBestAskPrice() { - return bestAskPrice; - } - - public void setBestAskPrice(String bestAskPrice) { - this.bestAskPrice = bestAskPrice; - } - - public String getBestAskQuantity() { - return bestAskQuantity; - } - - public void setBestAskQuantity(String bestAskQuantity) { - this.bestAskQuantity = bestAskQuantity; - } - - public String getOpenPrice() { - return openPrice; - } - - public void setOpenPrice(String openPrice) { - this.openPrice = openPrice; - } - - public String getHighPrice() { - return highPrice; - } - - public void setHighPrice(String highPrice) { - this.highPrice = highPrice; - } - - public String getLowPrice() { - return lowPrice; - } - - public void setLowPrice(String lowPrice) { - this.lowPrice = lowPrice; - } - - public String getTotalTradedBaseAssetVolume() { - return totalTradedBaseAssetVolume; - } - - public void setTotalTradedBaseAssetVolume(String totalTradedBaseAssetVolume) { - this.totalTradedBaseAssetVolume = totalTradedBaseAssetVolume; - } - - public String getTotalTradedQuoteAssetVolume() { - return totalTradedQuoteAssetVolume; - } - - public void setTotalTradedQuoteAssetVolume(String totalTradedQuoteAssetVolume) { - this.totalTradedQuoteAssetVolume = totalTradedQuoteAssetVolume; - } - - public long getStatisticesOpenTime() { - return statisticesOpenTime; - } - - public void setStatisticesOpenTime(long statisticesOpenTime) { - this.statisticesOpenTime = statisticesOpenTime; - } - - public long getStatisticesCloseTime() { - return statisticesCloseTime; - } - - public void setStatisticesCloseTime(long statisticesCloseTime) { - this.statisticesCloseTime = statisticesCloseTime; - } - - public long getFirstTradeId() { - return firstTradeId; - } - - public void setFirstTradeId(long firstTradeId) { - this.firstTradeId = firstTradeId; - } - - public long getLastTradeId() { - return lastTradeId; - } - - public void setLastTradeId(long lastTradeId) { - this.lastTradeId = lastTradeId; - } - - public long getTotalNumberOfTrades() { - return totalNumberOfTrades; - } - - public void setTotalNumberOfTrades(long totalNumberOfTrades) { - this.totalNumberOfTrades = totalNumberOfTrades; - } - - @Override - public String toString() { - return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) - .append("eventType", eventType) - .append("eventTime", eventTime) - .append("symbol", symbol) - .append("priceChange", priceChange) - .append("priceChangePercent", priceChangePercent) - .append("weightedAveragePrice", weightedAveragePrice) - .append("previousDaysClosePrice", previousDaysClosePrice) - .append("currentDaysClosePrice", currentDaysClosePrice) - .append("closeTradesQuantity", closeTradesQuantity) - .append("bestBidPrice", bestBidPrice) - .append("bestBidQuantity", bestBidQuantity) - .append("bestAskPrice", bestAskPrice) - .append("bestAskQuantity", bestAskQuantity) - .append("openPrice", openPrice) - .append("highPrice", highPrice) - .append("lowPrice", lowPrice) - .append("totalTradedBaseAssetVolume", totalTradedBaseAssetVolume) - .append("totalTradedQuoteAssetVolume", totalTradedQuoteAssetVolume) - .append("statisticesOpenTime", statisticesOpenTime) - .append("statisticesCloseTime", statisticesCloseTime) - .append("firstTradeId", firstTradeId) - .append("lastTradeId", lastTradeId) - .append("totalNumberOfTrades", totalNumberOfTrades) - .toString(); - } -} diff --git a/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java b/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java index 326d29e9a..d3612194f 100644 --- a/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java @@ -1,10 +1,9 @@ package com.binance.api.client.domain.event; -import org.apache.commons.lang3.builder.ToStringBuilder; - 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 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 100644 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/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index 1ca78716e..ca50bd323 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -3,11 +3,9 @@ import com.binance.api.client.BinanceApiCallback; import com.binance.api.client.BinanceApiWebSocketClient; import com.binance.api.client.config.BinanceApiConfig; -import com.binance.api.client.constant.BinanceApiConstants; import com.binance.api.client.domain.event.*; import com.binance.api.client.domain.market.CandlestickInterval; import com.fasterxml.jackson.core.type.TypeReference; - import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.WebSocket; @@ -58,9 +56,19 @@ 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, new TypeReference>() {})); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference>() { + })); } @Override @@ -72,11 +80,18 @@ public Closeable onBookTickerEvent(String symbols, BinanceApiCallback(callback, BookTickerEvent.class)); } + public Closeable onAllBookTickersEvent(BinanceApiCallback callback) { + final String channel = "!bookTicker"; + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference() { + })); + } + /** * @deprecated This method is no longer functional. Please use the returned {@link Closeable} from any of the other methods to close the web socket. */ @Override - public void close() { } + public void close() { + } private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { String streamingUrl = String.format("%s/%s", BinanceApiConfig.getStreamApiBaseUrl(), channel); From 26638f22d621230dd57632e1508823aa65b90bdf Mon Sep 17 00:00:00 2001 From: Eugen Podaru Date: Fri, 13 Nov 2020 00:38:21 +0100 Subject: [PATCH 61/83] Fix onAllBookTickersEvent --- .../binance/api/client/impl/BinanceApiWebSocketClientImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index ca50bd323..be0dcf518 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -82,8 +82,7 @@ public Closeable onBookTickerEvent(String symbols, BinanceApiCallback callback) { final String channel = "!bookTicker"; - return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, new TypeReference() { - })); + return createNewWebSocket(channel, new BinanceApiWebSocketListener<>(callback, BookTickerEvent.class)); } /** From 22dc5e5f7606854304d69fa252e04f151ba8b44b Mon Sep 17 00:00:00 2001 From: Eugen Podaru Date: Sat, 14 Nov 2020 15:05:02 +0100 Subject: [PATCH 62/83] Add side-effect type to the margin new order --- .../BinanceApiAsyncMarginRestClient.java | 2 +- .../client/BinanceApiMarginRestClient.java | 2 +- .../client/domain/account/MarginNewOrder.java | 289 ++++++++++++++++++ .../account/MarginNewOrderResponse.java | 210 +++++++++++++ .../client/domain/account/SideEffectType.java | 17 ++ .../BinanceApiAsyncMarginRestClientImpl.java | 160 +++++----- .../impl/BinanceApiMarginRestClientImpl.java | 194 ++++++------ .../api/client/impl/BinanceApiService.java | 25 +- .../api/examples/MarginOrdersExample.java | 55 ++-- .../examples/MarginOrdersExampleAsync.java | 32 +- 10 files changed, 747 insertions(+), 239 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/account/MarginNewOrder.java create mode 100644 src/main/java/com/binance/api/client/domain/account/MarginNewOrderResponse.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SideEffectType.java diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java index cbab0781c..8d1d8486f 100755 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java @@ -41,7 +41,7 @@ public interface BinanceApiAsyncMarginRestClient { * @param order the new order to submit. * @return a response containing details about the newly placed order. */ - void newOrder(NewOrder order, BinanceApiCallback callback); + void newOrder(MarginNewOrder order, BinanceApiCallback callback); /** * Cancel an active margin order (async). diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java index 681a8db96..6f100a365 100755 --- a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -28,7 +28,7 @@ public interface BinanceApiMarginRestClient { * @param order the new order to submit. * @return a response containing details about the newly placed order. */ - NewOrderResponse newOrder(NewOrder order); + MarginNewOrderResponse newOrder(MarginNewOrder order); /** * Cancel an active margin order. 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 100644 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 100644 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/SideEffectType.java b/src/main/java/com/binance/api/client/domain/account/SideEffectType.java new file mode 100644 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/impl/BinanceApiAsyncMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java index 4514bd314..d3e5c22f6 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java @@ -20,84 +20,84 @@ */ public class BinanceApiAsyncMarginRestClientImpl implements BinanceApiAsyncMarginRestClient { - private final BinanceApiService binanceApiService; - - public BinanceApiAsyncMarginRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - // Margin Account endpoints - - @Override - public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { - binanceApiService.getMarginAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAccount(BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { - binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), - orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void newOrder(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { - binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { - binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getMyTrades(String symbol, BinanceApiCallback> callback) { - binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // user stream endpoints - - @Override - public void startUserDataStream(BinanceApiCallback callback) { - binanceApiService.startMarginUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { - binanceApiService.keepAliveMarginUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void transfer(String asset, String amount, TransferType type, BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void borrow(String asset, String amount, BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void repay(String asset, String amount, BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.repay(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } + 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/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java index b4322fd70..959fa2a5f 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -19,101 +19,101 @@ */ public class BinanceApiMarginRestClientImpl implements BinanceApiMarginRestClient { - private final BinanceApiService binanceApiService; - - public BinanceApiMarginRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - @Override - public MarginAccount getAccount() { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); - } - - @Override - public List getOpenOrders(OrderRequest orderRequest) { - return executeSync(binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), - orderRequest.getTimestamp())); - } - - @Override - public NewOrderResponse newOrder(NewOrder order) { - return executeSync(binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); - } - - @Override - public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { - return executeSync(binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); - } - - @Override - public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { - return executeSync(binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); - } - - @Override - public List getMyTrades(String symbol) { - return executeSync(binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - // user stream endpoints - - @Override - public String startUserDataStream() { - return executeSync(binanceApiService.startMarginUserDataStream()).toString(); - } - - @Override - public void keepAliveUserDataStream(String listenKey) { - executeSync(binanceApiService.keepAliveMarginUserDataStream(listenKey)); - } - - @Override - public MarginTransaction transfer(String asset, String amount, TransferType type) { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); - } - - @Override - public MarginTransaction borrow(String asset, String amount) { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); - } - - @Override - public LoanQueryResult queryLoan(String asset, String txId) { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.queryLoan(asset, txId, timestamp)); - } - - @Override - public 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)); - } + 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/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index c940a370c..ede340457 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -11,20 +11,9 @@ 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.Url; +import retrofit2.http.*; import java.util.List; @@ -209,11 +198,11 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) @POST("/sapi/v1/margin/order") - Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + 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") diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExample.java b/src/test/java/com/binance/api/examples/MarginOrdersExample.java index 404274489..969ca784f 100755 --- a/src/test/java/com/binance/api/examples/MarginOrdersExample.java +++ b/src/test/java/com/binance/api/examples/MarginOrdersExample.java @@ -3,44 +3,47 @@ import com.binance.api.client.BinanceApiClientFactory; import com.binance.api.client.BinanceApiMarginRestClient; import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.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.*; +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.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()); + 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); } - // Placing a real LIMIT order - NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); - System.out.println(newOrderResponse); - } - } diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java index c80cdfc70..b07a01792 100755 --- a/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java +++ b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java @@ -7,30 +7,30 @@ 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.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(); + 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)); + // 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)); + // 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)); + // 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)); - } + // Placing a real LIMIT order + client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println(response)); + } } From 86b16b885bfd43e96de92615c93bb09d012f24c5 Mon Sep 17 00:00:00 2001 From: Eugen Podaru Date: Sat, 14 Nov 2020 15:05:02 +0100 Subject: [PATCH 63/83] Add side-effect type to the margin new order --- .../BinanceApiAsyncMarginRestClient.java | 2 +- .../client/BinanceApiMarginRestClient.java | 2 +- .../client/domain/account/MarginNewOrder.java | 289 ++++++++++++++++++ .../account/MarginNewOrderResponse.java | 210 +++++++++++++ .../client/domain/account/SideEffectType.java | 17 ++ .../BinanceApiAsyncMarginRestClientImpl.java | 160 +++++----- .../impl/BinanceApiMarginRestClientImpl.java | 194 ++++++------ .../api/client/impl/BinanceApiService.java | 25 +- .../api/examples/MarginOrdersExample.java | 55 ++-- .../examples/MarginOrdersExampleAsync.java | 32 +- 10 files changed, 747 insertions(+), 239 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/account/MarginNewOrder.java create mode 100644 src/main/java/com/binance/api/client/domain/account/MarginNewOrderResponse.java create mode 100644 src/main/java/com/binance/api/client/domain/account/SideEffectType.java diff --git a/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java index cbab0781c..8d1d8486f 100755 --- a/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiAsyncMarginRestClient.java @@ -41,7 +41,7 @@ public interface BinanceApiAsyncMarginRestClient { * @param order the new order to submit. * @return a response containing details about the newly placed order. */ - void newOrder(NewOrder order, BinanceApiCallback callback); + void newOrder(MarginNewOrder order, BinanceApiCallback callback); /** * Cancel an active margin order (async). diff --git a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java index 681a8db96..6f100a365 100755 --- a/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiMarginRestClient.java @@ -28,7 +28,7 @@ public interface BinanceApiMarginRestClient { * @param order the new order to submit. * @return a response containing details about the newly placed order. */ - NewOrderResponse newOrder(NewOrder order); + MarginNewOrderResponse newOrder(MarginNewOrder order); /** * Cancel an active margin order. 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 100644 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 100644 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/SideEffectType.java b/src/main/java/com/binance/api/client/domain/account/SideEffectType.java new file mode 100644 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/impl/BinanceApiAsyncMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java index 4514bd314..d3e5c22f6 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiAsyncMarginRestClientImpl.java @@ -20,84 +20,84 @@ */ public class BinanceApiAsyncMarginRestClientImpl implements BinanceApiAsyncMarginRestClient { - private final BinanceApiService binanceApiService; - - public BinanceApiAsyncMarginRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - // Margin Account endpoints - - @Override - public void getAccount(Long recvWindow, Long timestamp, BinanceApiCallback callback) { - binanceApiService.getMarginAccount(recvWindow, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getAccount(BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getOpenOrders(OrderRequest orderRequest, BinanceApiCallback> callback) { - binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), - orderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void newOrder(NewOrder order, BinanceApiCallback callback) { - binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void cancelOrder(CancelOrderRequest cancelOrderRequest, BinanceApiCallback callback) { - binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getOrderStatus(OrderStatusRequest orderStatusRequest, BinanceApiCallback callback) { - binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void getMyTrades(String symbol, BinanceApiCallback> callback) { - binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis()).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - // user stream endpoints - - @Override - public void startUserDataStream(BinanceApiCallback callback) { - binanceApiService.startMarginUserDataStream().enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void keepAliveUserDataStream(String listenKey, BinanceApiCallback callback) { - binanceApiService.keepAliveMarginUserDataStream(listenKey).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void transfer(String asset, String amount, TransferType type, BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void borrow(String asset, String amount, BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } - - @Override - public void repay(String asset, String amount, BinanceApiCallback callback) { - long timestamp = System.currentTimeMillis(); - binanceApiService.repay(asset, amount, BinanceApiConstants.DEFAULT_MARGIN_RECEIVING_WINDOW, timestamp).enqueue(new BinanceApiCallbackAdapter<>(callback)); - } + 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/BinanceApiMarginRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java index b4322fd70..959fa2a5f 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiMarginRestClientImpl.java @@ -19,101 +19,101 @@ */ public class BinanceApiMarginRestClientImpl implements BinanceApiMarginRestClient { - private final BinanceApiService binanceApiService; - - public BinanceApiMarginRestClientImpl(String apiKey, String secret) { - binanceApiService = createService(BinanceApiService.class, apiKey, secret); - } - - @Override - public MarginAccount getAccount() { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.getMarginAccount(BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); - } - - @Override - public List getOpenOrders(OrderRequest orderRequest) { - return executeSync(binanceApiService.getOpenMarginOrders(orderRequest.getSymbol(), orderRequest.getRecvWindow(), - orderRequest.getTimestamp())); - } - - @Override - public NewOrderResponse newOrder(NewOrder order) { - return executeSync(binanceApiService.newMarginOrder(order.getSymbol(), order.getSide(), order.getType(), - order.getTimeInForce(), order.getQuantity(), order.getPrice(), order.getNewClientOrderId(), order.getStopPrice(), - order.getIcebergQty(), order.getNewOrderRespType(), order.getRecvWindow(), order.getTimestamp())); - } - - @Override - public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) { - return executeSync(binanceApiService.cancelMarginOrder(cancelOrderRequest.getSymbol(), - cancelOrderRequest.getOrderId(), cancelOrderRequest.getOrigClientOrderId(), cancelOrderRequest.getNewClientOrderId(), - cancelOrderRequest.getRecvWindow(), cancelOrderRequest.getTimestamp())); - } - - @Override - public Order getOrderStatus(OrderStatusRequest orderStatusRequest) { - return executeSync(binanceApiService.getMarginOrderStatus(orderStatusRequest.getSymbol(), - orderStatusRequest.getOrderId(), orderStatusRequest.getOrigClientOrderId(), - orderStatusRequest.getRecvWindow(), orderStatusRequest.getTimestamp())); - } - - @Override - public List getMyTrades(String symbol) { - return executeSync(binanceApiService.getMyTrades(symbol, null, null, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, System.currentTimeMillis())); - } - - // user stream endpoints - - @Override - public String startUserDataStream() { - return executeSync(binanceApiService.startMarginUserDataStream()).toString(); - } - - @Override - public void keepAliveUserDataStream(String listenKey) { - executeSync(binanceApiService.keepAliveMarginUserDataStream(listenKey)); - } - - @Override - public MarginTransaction transfer(String asset, String amount, TransferType type) { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.transfer(asset, amount, type.getValue(), BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); - } - - @Override - public MarginTransaction borrow(String asset, String amount) { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.borrow(asset, amount, BinanceApiConstants.DEFAULT_RECEIVING_WINDOW, timestamp)); - } - - @Override - public LoanQueryResult queryLoan(String asset, String txId) { - long timestamp = System.currentTimeMillis(); - return executeSync(binanceApiService.queryLoan(asset, txId, timestamp)); - } - - @Override - public 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)); - } + 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/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index c940a370c..ede340457 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -11,20 +11,9 @@ 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.Url; +import retrofit2.http.*; import java.util.List; @@ -209,11 +198,11 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER) @POST("/sapi/v1/margin/order") - Call newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type, - @Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price, - @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice, - @Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType, - @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp); + 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") diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExample.java b/src/test/java/com/binance/api/examples/MarginOrdersExample.java index 404274489..969ca784f 100755 --- a/src/test/java/com/binance/api/examples/MarginOrdersExample.java +++ b/src/test/java/com/binance/api/examples/MarginOrdersExample.java @@ -3,44 +3,47 @@ import com.binance.api.client.BinanceApiClientFactory; import com.binance.api.client.BinanceApiMarginRestClient; import com.binance.api.client.domain.TimeInForce; -import com.binance.api.client.domain.account.NewOrderResponse; +import com.binance.api.client.domain.account.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.*; +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.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()); + 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); } - // Placing a real LIMIT order - NewOrderResponse newOrderResponse = client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001").newOrderRespType(NewOrderResponseType.FULL)); - System.out.println(newOrderResponse); - } - } diff --git a/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java index c80cdfc70..b07a01792 100755 --- a/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java +++ b/src/test/java/com/binance/api/examples/MarginOrdersExampleAsync.java @@ -7,30 +7,30 @@ 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.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(); + 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)); + // 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)); + // 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)); + // 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)); - } + // Placing a real LIMIT order + client.newOrder(limitBuy("LINKETH", TimeInForce.GTC, "1000", "0.0001"), + response -> System.out.println(response)); + } } From 20f58b5849f5dfd35c8aee737df656716c95a874 Mon Sep 17 00:00:00 2001 From: Yani Ferhaoui Date: Sat, 9 Jan 2021 16:07:58 +0100 Subject: [PATCH 64/83] Add GET getSubAccountTransfers request --- .../api/client/BinanceApiRestClient.java | 18 ++- .../domain/account/SubAccountTransfer.java | 131 ++++++++++++++++++ .../client/impl/BinanceApiRestClientImpl.java | 5 + .../api/client/impl/BinanceApiService.java | 4 + 4 files changed, 148 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index 99b1e3488..bfc4797c4 100755 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -1,15 +1,6 @@ package com.binance.api.client; -import com.binance.api.client.domain.account.Account; -import com.binance.api.client.domain.account.DepositAddress; -import com.binance.api.client.domain.account.DepositHistory; -import com.binance.api.client.domain.account.NewOrder; -import com.binance.api.client.domain.account.NewOrderResponse; -import com.binance.api.client.domain.account.Order; -import com.binance.api.client.domain.account.Trade; -import com.binance.api.client.domain.account.TradeHistoryItem; -import com.binance.api.client.domain.account.WithdrawHistory; -import com.binance.api.client.domain.account.WithdrawResult; +import com.binance.api.client.domain.account.*; 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; @@ -268,6 +259,13 @@ public interface BinanceApiRestClient { */ WithdrawHistory getWithdrawHistory(String asset); + /** + * Fetch sub-account transfer history. + * + * @return sub-account transfers + */ + List getSubAccountTransfers(); + /** * Fetch deposit address. * 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 100644 index 000000000..b248ac8cd --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java @@ -0,0 +1,131 @@ +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; + + /** + * 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 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 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("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/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index 31cd4130e..dd647166d 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -219,6 +219,11 @@ public WithdrawHistory getWithdrawHistory(String asset) { 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, diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index ede340457..e949e340f 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -145,6 +145,10 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @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) + @GET("/sapi/v1/sub-account/transfer/subUserHistory") + Call> getSubAccountTransfers(@Query("timestamp") Long timestamp); + // User stream endpoints @Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER) From e3ad8efa2a1a8988a3dd2963556a2a1c1a28219d Mon Sep 17 00:00:00 2001 From: SanektTNT Date: Fri, 15 Jan 2021 12:25:36 +0200 Subject: [PATCH 65/83] fix UnrecognizedPropertyException for loan/repay/transfer endpoints --- .../binance/api/client/domain/account/MarginTransaction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 116439379..f08995f1d 100755 --- a/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java +++ b/src/main/java/com/binance/api/client/domain/account/MarginTransaction.java @@ -7,7 +7,7 @@ /** * MarginTransaction information. */ -@JsonIgnoreProperties +@JsonIgnoreProperties(ignoreUnknown = true) public class MarginTransaction { private String tranId; From 2ae2a3bfab7c59b6ebf475ba32b876f5112dfcb0 Mon Sep 17 00:00:00 2001 From: yaniferhaoui Date: Wed, 24 Feb 2021 10:41:48 +0100 Subject: [PATCH 66/83] Add SymbolInfo attributs --- .gitignore | 0 LICENSE | 0 README.md | 0 pom.xml | 0 .../api/client/config/BinanceApiConfig.java | 0 .../com/binance/api/client/constant/Util.java | 0 .../LiquidityOperationRecordStatus.java | 0 .../api/client/domain/SwapRemoveType.java | 0 .../domain/account/CrossMarginAssets.java | 0 .../api/client/domain/account/Liquidity.java | 0 .../account/LiquidityOperationRecord.java | 0 .../client/domain/account/MarginNewOrder.java | 0 .../account/MarginNewOrderResponse.java | 0 .../api/client/domain/account/Pool.java | 0 .../client/domain/account/SideEffectType.java | 0 .../domain/account/SubAccountTransfer.java | 0 .../client/domain/account/SwapHistory.java | 0 .../api/client/domain/account/SwapQuote.java | 0 .../api/client/domain/account/SwapRecord.java | 0 .../api/client/domain/account/SwapStatus.java | 0 .../domain/event/BalanceUpdateEvent.java | 0 .../client/domain/event/BookTickerEvent.java | 0 .../api/client/domain/event/TickerEvent.java | 0 .../client/domain/event/TopOrdersEvent.java | 0 .../api/client/domain/general/FilterType.java | 0 .../api/client/domain/general/SymbolInfo.java | 40 +++++++++++++++++++ .../exception/UnsupportedEventException.java | 0 .../api/examples/SwapEndpointExample.java | 0 .../examples/TotalAccountBalanceExample.java | 0 29 files changed, 40 insertions(+) mode change 100644 => 100755 .gitignore mode change 100644 => 100755 LICENSE mode change 100644 => 100755 README.md mode change 100644 => 100755 pom.xml mode change 100644 => 100755 src/main/java/com/binance/api/client/config/BinanceApiConfig.java mode change 100644 => 100755 src/main/java/com/binance/api/client/constant/Util.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/SwapRemoveType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/CrossMarginAssets.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Liquidity.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/LiquidityOperationRecord.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/MarginNewOrder.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/MarginNewOrderResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/Pool.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/SideEffectType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/SwapHistory.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/SwapQuote.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/SwapRecord.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/SwapStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/BalanceUpdateEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/BookTickerEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/TickerEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/event/TopOrdersEvent.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/general/FilterType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/exception/UnsupportedEventException.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/SwapEndpointExample.java mode change 100644 => 100755 src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java 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 diff --git a/pom.xml b/pom.xml old mode 100644 new mode 100755 diff --git a/src/main/java/com/binance/api/client/config/BinanceApiConfig.java b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/binance/api/client/constant/Util.java b/src/main/java/com/binance/api/client/constant/Util.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java b/src/main/java/com/binance/api/client/domain/LiquidityOperationRecordStatus.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/binance/api/client/domain/SwapRemoveType.java b/src/main/java/com/binance/api/client/domain/SwapRemoveType.java old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 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 index 72bca07e3..709a0c901 100755 --- a/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java @@ -29,6 +29,14 @@ public class SymbolInfo { private boolean icebergAllowed; + private boolean ocoAllowed; + + private boolean quoteOrderQtyMarketAllowed; + + private boolean isSpotTradingAllowed; + + private boolean isMarginTradingAllowed; + private List filters; public String getSymbol() { @@ -95,6 +103,38 @@ 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 setSpotTradingAllowed(boolean isSpotTradingAllowed) { + this.isSpotTradingAllowed = isSpotTradingAllowed; + } + + public boolean isMarginTradingAllowed() { + return isMarginTradingAllowed; + } + + public void setMarginTradingAllowed(boolean isMarginTradingAllowed) { + this.isMarginTradingAllowed = isMarginTradingAllowed; + } + public List getFilters() { return filters; } diff --git a/src/main/java/com/binance/api/client/exception/UnsupportedEventException.java b/src/main/java/com/binance/api/client/exception/UnsupportedEventException.java old mode 100644 new mode 100755 diff --git a/src/test/java/com/binance/api/examples/SwapEndpointExample.java b/src/test/java/com/binance/api/examples/SwapEndpointExample.java old mode 100644 new mode 100755 diff --git a/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java b/src/test/java/com/binance/api/examples/TotalAccountBalanceExample.java old mode 100644 new mode 100755 From b8b9f6f7a932ca83446c3f65159e9dc02f554ac3 Mon Sep 17 00:00:00 2001 From: yaniferhaoui Date: Wed, 24 Feb 2021 12:11:15 +0100 Subject: [PATCH 67/83] Add SymbolInfo attributs --- .../com/binance/api/client/domain/general/SymbolInfo.java | 4 ++-- .../java/com/binance/api/client/impl/BinanceApiService.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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 index 709a0c901..ca2723235 100755 --- a/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java +++ b/src/main/java/com/binance/api/client/domain/general/SymbolInfo.java @@ -123,7 +123,7 @@ public boolean isSpotTradingAllowed() { return isSpotTradingAllowed; } - public void setSpotTradingAllowed(boolean isSpotTradingAllowed) { + public void setIsSpotTradingAllowed(boolean isSpotTradingAllowed) { this.isSpotTradingAllowed = isSpotTradingAllowed; } @@ -131,7 +131,7 @@ public boolean isMarginTradingAllowed() { return isMarginTradingAllowed; } - public void setMarginTradingAllowed(boolean isMarginTradingAllowed) { + public void setIsMarginTradingAllowed(boolean isMarginTradingAllowed) { this.isMarginTradingAllowed = isMarginTradingAllowed; } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index e949e340f..35e21de0c 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -30,7 +30,7 @@ public interface BinanceApiService { @GET("/api/v1/time") Call getServerTime(); - @GET("/api/v1/exchangeInfo") + @GET("/api/v3/exchangeInfo") Call getExchangeInfo(); @GET From ef91aab3d9f4889f43b149942c7661cf3edc1306 Mon Sep 17 00:00:00 2001 From: yaniferhaoui Date: Sun, 21 Mar 2021 20:48:47 +0100 Subject: [PATCH 68/83] Add stopLimitPrice --- .../java/com/binance/api/client/domain/account/NewOrder.java | 5 +++++ .../java/com/binance/api/client/domain/account/Order.java | 5 +++++ 2 files changed, 10 insertions(+) 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 index b3ebd8bee..30b684dc4 100755 --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -58,6 +58,11 @@ public class NewOrder { */ private String stopPrice; + /** + * Used with stop orders. + */ + private String stopLimitPrice; + /** * Used with iceberg orders. */ 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 index c2ba19457..0b34d5130 100755 --- a/src/main/java/com/binance/api/client/domain/account/Order.java +++ b/src/main/java/com/binance/api/client/domain/account/Order.java @@ -70,6 +70,11 @@ public class Order { */ private String stopPrice; + /** + * Used with stop orders. + */ + private String stopLimitPrice; + /** * Used with iceberg orders. */ From 3d47c864eeedfac8c592164ed80edf9fb7ade985 Mon Sep 17 00:00:00 2001 From: yaniferhaoui Date: Sun, 21 Mar 2021 20:53:50 +0100 Subject: [PATCH 69/83] Add stopLimitPrice --- .../api/client/domain/account/NewOrder.java | 38 ++++++++++------ .../api/client/domain/account/Order.java | 45 +++++++++++-------- 2 files changed, 51 insertions(+), 32 deletions(-) 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 index 30b684dc4..6c592219a 100755 --- a/src/main/java/com/binance/api/client/domain/account/NewOrder.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOrder.java @@ -186,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; } @@ -261,19 +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("quoteOrderQty", quoteOrderQty) - .append("price", price) - .append("newClientOrderId", newClientOrderId) - .append("stopPrice", stopPrice) - .append("icebergQty", icebergQty) - .append("newOrderRespType", newOrderRespType) - .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/Order.java b/src/main/java/com/binance/api/client/domain/account/Order.java index 0b34d5130..881efd6dc 100755 --- a/src/main/java/com/binance/api/client/domain/account/Order.java +++ b/src/main/java/com/binance/api/client/domain/account/Order.java @@ -194,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; } @@ -245,23 +253,24 @@ public void setOrigQuoteOrderQty(String 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) - .append("cummulativeQuoteQty", cummulativeQuoteQty) - .append("updateTime", updateTime) - .append("isWorking", working) - .append("origQuoteOrderQty", origQuoteOrderQty) - .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(); } } From 1633433613f0b5d4190f563fc308347ae6af0133 Mon Sep 17 00:00:00 2001 From: yaniferhaoui Date: Thu, 25 Mar 2021 15:17:58 +0100 Subject: [PATCH 70/83] Implementation of OCO order --- .../api/client/BinanceApiRestClient.java | 44 +++- .../api/client/domain/ContingencyType.java | 8 + .../api/client/domain/OCOOrderStatus.java | 10 + .../binance/api/client/domain/OCOStatus.java | 10 + .../domain/account/DustTransferResponse.java | 52 ++++ .../api/client/domain/account/NewOCO.java | 241 ++++++++++++++++++ .../client/domain/account/NewOCOResponse.java | 20 ++ .../api/client/domain/account/OrderList.java | 113 ++++++++ .../client/domain/account/OrderReport.java | 172 +++++++++++++ .../client/domain/account/TransferResult.java | 91 +++++++ .../account/request/AllOrderListRequest.java | 77 ++++++ .../request/CancelOrderListRequest.java | 83 ++++++ .../request/CancelOrderListResponse.java | 9 + .../account/request/CancelOrderResponse.java | 34 ++- .../request/OrderListStatusRequest.java | 55 ++++ .../client/impl/BinanceApiRestClientImpl.java | 32 +++ .../api/client/impl/BinanceApiService.java | 28 ++ 17 files changed, 1063 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/binance/api/client/domain/ContingencyType.java create mode 100644 src/main/java/com/binance/api/client/domain/OCOOrderStatus.java create mode 100644 src/main/java/com/binance/api/client/domain/OCOStatus.java create mode 100644 src/main/java/com/binance/api/client/domain/account/DustTransferResponse.java create mode 100644 src/main/java/com/binance/api/client/domain/account/NewOCO.java create mode 100644 src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java create mode 100644 src/main/java/com/binance/api/client/domain/account/OrderList.java create mode 100644 src/main/java/com/binance/api/client/domain/account/OrderReport.java create mode 100644 src/main/java/com/binance/api/client/domain/account/TransferResult.java create mode 100644 src/main/java/com/binance/api/client/domain/account/request/AllOrderListRequest.java create mode 100644 src/main/java/com/binance/api/client/domain/account/request/CancelOrderListRequest.java create mode 100644 src/main/java/com/binance/api/client/domain/account/request/CancelOrderListResponse.java create mode 100644 src/main/java/com/binance/api/client/domain/account/request/OrderListStatusRequest.java diff --git a/src/main/java/com/binance/api/client/BinanceApiRestClient.java b/src/main/java/com/binance/api/client/BinanceApiRestClient.java index bfc4797c4..ebe0b9667 100755 --- a/src/main/java/com/binance/api/client/BinanceApiRestClient.java +++ b/src/main/java/com/binance/api/client/BinanceApiRestClient.java @@ -1,11 +1,7 @@ package com.binance.api.client; import com.binance.api.client.domain.account.*; -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.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; @@ -193,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. */ @@ -245,6 +273,12 @@ public interface BinanceApiRestClient { */ 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 + */ + DustTransferResponse dustTranfer(List asset); + /** * Fetch account deposit history. * 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 100644 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/OCOOrderStatus.java b/src/main/java/com/binance/api/client/domain/OCOOrderStatus.java new file mode 100644 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 100644 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/account/DustTransferResponse.java b/src/main/java/com/binance/api/client/domain/account/DustTransferResponse.java new file mode 100644 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/NewOCO.java b/src/main/java/com/binance/api/client/domain/account/NewOCO.java new file mode 100644 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 100644 index 000000000..2d5c273ce --- /dev/null +++ b/src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java @@ -0,0 +1,20 @@ +package com.binance.api.client.domain.account; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class NewOCOResponse extends OrderList { + + private List orderReports; + + public List getOrderReports() { + return orderReports; + } + + public void setOrderReports(List orderReports) { + this.orderReports = orderReports; + } + +} 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 100644 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 100644 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/TransferResult.java b/src/main/java/com/binance/api/client/domain/account/TransferResult.java new file mode 100644 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/request/AllOrderListRequest.java b/src/main/java/com/binance/api/client/domain/account/request/AllOrderListRequest.java new file mode 100644 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/CancelOrderListRequest.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderListRequest.java new file mode 100644 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 100644 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/CancelOrderResponse.java b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java index 0399aea2b..20fc07912 100755 --- a/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/request/CancelOrderResponse.java @@ -1,6 +1,7 @@ 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; @@ -16,11 +17,12 @@ public class CancelOrderResponse { private String origClientOrderId; - private String orderId; + private Long orderId; private String clientOrderId; - private String status; + private OrderStatus status; + private String executedQty; public String getSymbol() { @@ -41,17 +43,27 @@ public CancelOrderResponse setOrigClientOrderId(String origClientOrderId) { return this; } - public String getStatus() { + 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 String getOrderId() { + public Long getOrderId() { return orderId; } - public CancelOrderResponse setOrderId(String orderId) { + + public CancelOrderResponse setOrderId(Long orderId) { this.orderId = orderId; return this; } @@ -68,10 +80,10 @@ public CancelOrderResponse setClientOrderId(String clientOrderId) { @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(); + .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 100644 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/impl/BinanceApiRestClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java index dd647166d..c80c7a06d 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiRestClientImpl.java @@ -168,6 +168,33 @@ public List getAllOrders(AllOrdersRequest orderRequest) { 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)); @@ -207,6 +234,11 @@ public WithdrawResult withdraw(String asset, String address, String amount, Stri 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, diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiService.java b/src/main/java/com/binance/api/client/impl/BinanceApiService.java index 35e21de0c..5825f9844 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiService.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiService.java @@ -6,6 +6,7 @@ import com.binance.api.client.domain.SwapRemoveType; import com.binance.api.client.domain.TimeInForce; import com.binance.api.client.domain.account.*; +import com.binance.api.client.domain.account.request.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; @@ -118,6 +119,29 @@ Call cancelOrder(@Query("symbol") String symbol, @Query("or 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); @@ -145,6 +169,10 @@ Call withdraw(@Query("asset") String asset, @Query("address") St @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); From 825c39fa43d7c8ad7ca40800454530905d4ddfcc Mon Sep 17 00:00:00 2001 From: yaniferhaoui Date: Fri, 26 Mar 2021 00:03:20 +0100 Subject: [PATCH 71/83] Implementation of OCO order --- .../client/domain/account/NewOCOResponse.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) 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 index 2d5c273ce..b22580827 100644 --- a/src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java +++ b/src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java @@ -2,17 +2,85 @@ 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; } From 32cea2cd134fdae459d907164f1496c82b175913 Mon Sep 17 00:00:00 2001 From: george soler Date: Thu, 25 Mar 2021 19:15:38 -0700 Subject: [PATCH 72/83] Add connectivity to Binance Exchange Spot Test Network endpoints. --- .../api/client/BinanceApiClientFactory.java | 233 +++++++++++------- .../api/client/config/BinanceApiConfig.java | 30 +++ .../impl/BinanceApiServiceGenerator.java | 19 +- 3 files changed, 186 insertions(+), 96 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java index 842ad20d5..d5648eabc 100755 --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -1,95 +1,138 @@ -package com.binance.api.client; - -import com.binance.api.client.impl.*; - -import static com.binance.api.client.impl.BinanceApiServiceGenerator.getSharedClient; - -/** - * A factory for creating BinanceApi client objects. - */ -public class BinanceApiClientFactory { - - /** - * API Key - */ - private String apiKey; - - /** - * Secret. - */ - private String secret; - - /** - * Instantiates a new binance api client factory. - * - * @param apiKey the API key - * @param secret the Secret - */ - private BinanceApiClientFactory(String apiKey, String secret) { - this.apiKey = apiKey; - this.secret = secret; - } - - /** - * New instance. - * - * @param apiKey the API key - * @param secret the Secret - * - * @return the binance api client factory - */ - public static BinanceApiClientFactory newInstance(String apiKey, String secret) { - return new BinanceApiClientFactory(apiKey, secret); - } - - /** - * New instance without authentication. - * - * @return the binance api client factory - */ - public static BinanceApiClientFactory newInstance() { - return new BinanceApiClientFactory(null, null); - } - - /** - * Creates a new synchronous/blocking REST client. - */ - public BinanceApiRestClient newRestClient() { - return new BinanceApiRestClientImpl(apiKey, secret); - } - - /** - * Creates a new asynchronous/non-blocking REST client. - */ - public BinanceApiAsyncRestClient newAsyncRestClient() { - return new BinanceApiAsyncRestClientImpl(apiKey, secret); - } - - /** - * Creates a new asynchronous/non-blocking Margin REST client. - */ - public BinanceApiAsyncMarginRestClient newAsyncMarginRestClient() { - return new BinanceApiAsyncMarginRestClientImpl(apiKey, secret); - } - - /** - * Creates a new synchronous/blocking Margin REST client. - */ - public BinanceApiMarginRestClient newMarginRestClient() { - return new BinanceApiMarginRestClientImpl(apiKey, secret); - } - - /** - * Creates a new web socket client used for handling data streams. - */ - public BinanceApiWebSocketClient newWebSocketClient() { - return new BinanceApiWebSocketClientImpl(getSharedClient()); - } - - /** - * Creates a new synchronous/blocking Swap REST client. - */ - public BinanceApiSwapRestClient newSwapRestClient() { - return new BinanceApiSwapRestClientImpl(apiKey, secret); - } -} +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/config/BinanceApiConfig.java b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java index d05538efb..276d94838 100755 --- a/src/main/java/com/binance/api/client/config/BinanceApiConfig.java +++ b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java @@ -10,6 +10,23 @@ public class BinanceApiConfig { */ 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). * @@ -49,4 +66,17 @@ 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", TESTNET_DOMAIN); + } } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 1bd11a9e2..7d28ff877 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -45,9 +45,26 @@ 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) { + String baseUrl = null; + if (!BinanceApiConfig.useTestnet) { baseUrl = BinanceApiConfig.getApiBaseUrl(); } + else { + baseUrl = BinanceApiConfig.useTestnetStreaming ? + BinanceApiConfig.getStreamTestNetBaseUrl() : + BinanceApiConfig.getTestNetBaseUrl(); + } + Retrofit.Builder retrofitBuilder = new Retrofit.Builder() - .baseUrl(BinanceApiConfig.getApiBaseUrl()) + .baseUrl(baseUrl) .addConverterFactory(converterFactory); if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) { From c9d52afc8529d202c6cc06c07872d58f4b696b74 Mon Sep 17 00:00:00 2001 From: george soler Date: Mon, 12 Apr 2021 10:56:25 -0700 Subject: [PATCH 73/83] Convert file from UNIX format to DOS for compatibility with master branch. --- .../api/client/BinanceApiClientFactory.java | 276 +++++++++--------- 1 file changed, 138 insertions(+), 138 deletions(-) diff --git a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java index d5648eabc..7ba5551bb 100755 --- a/src/main/java/com/binance/api/client/BinanceApiClientFactory.java +++ b/src/main/java/com/binance/api/client/BinanceApiClientFactory.java @@ -1,138 +1,138 @@ -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); - } -} +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); + } +} From e37c287bfb6857cdd77221e9400880c42ad21b10 Mon Sep 17 00:00:00 2001 From: erenmeren Date: Tue, 13 Apr 2021 09:36:10 +0100 Subject: [PATCH 74/83] FIxed to FIAT_CURRENCY list --- src/main/java/com/binance/api/client/constant/Util.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/binance/api/client/constant/Util.java b/src/main/java/com/binance/api/client/constant/Util.java index 6e459c037..dae7916f1 100755 --- a/src/main/java/com/binance/api/client/constant/Util.java +++ b/src/main/java/com/binance/api/client/constant/Util.java @@ -13,7 +13,7 @@ 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 List FIAT_CURRENCY = Collections.unmodifiableList(Arrays.asList("USDT", "BUSD", "PAX", "TUSD", "USDC", "NGN", "RUB", "USDS", "TRY")); public static final String BTC_TICKER = "BTC"; From 7d0a20b5a75ff6429cae961bc6247adb27062017 Mon Sep 17 00:00:00 2001 From: Yani Ferhaoui Date: Thu, 22 Apr 2021 15:43:56 +0200 Subject: [PATCH 75/83] Implementation of OCO order --- src/main/java/com/binance/api/client/domain/ContingencyType.java | 0 src/main/java/com/binance/api/client/domain/OCOOrderStatus.java | 0 src/main/java/com/binance/api/client/domain/OCOStatus.java | 0 .../binance/api/client/domain/account/DustTransferResponse.java | 0 src/main/java/com/binance/api/client/domain/account/NewOCO.java | 0 .../com/binance/api/client/domain/account/NewOCOResponse.java | 0 .../java/com/binance/api/client/domain/account/OrderList.java | 0 .../java/com/binance/api/client/domain/account/OrderReport.java | 0 .../com/binance/api/client/domain/account/TransferResult.java | 0 .../api/client/domain/account/request/AllOrderListRequest.java | 0 .../api/client/domain/account/request/CancelOrderListRequest.java | 0 .../client/domain/account/request/CancelOrderListResponse.java | 0 .../api/client/domain/account/request/OrderListStatusRequest.java | 0 13 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/ContingencyType.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OCOOrderStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/OCOStatus.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/DustTransferResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOCO.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/NewOCOResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/OrderList.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/OrderReport.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/TransferResult.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/AllOrderListRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/CancelOrderListRequest.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/CancelOrderListResponse.java mode change 100644 => 100755 src/main/java/com/binance/api/client/domain/account/request/OrderListStatusRequest.java diff --git a/src/main/java/com/binance/api/client/domain/ContingencyType.java b/src/main/java/com/binance/api/client/domain/ContingencyType.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/binance/api/client/domain/OCOOrderStatus.java b/src/main/java/com/binance/api/client/domain/OCOOrderStatus.java old mode 100644 new mode 100755 diff --git a/src/main/java/com/binance/api/client/domain/OCOStatus.java b/src/main/java/com/binance/api/client/domain/OCOStatus.java old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 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 old mode 100644 new mode 100755 From d63938b6d19d3731ad8214ef6ee2da94b42f4cdc Mon Sep 17 00:00:00 2001 From: Yani Ferhaoui Date: Sat, 24 Apr 2021 11:52:00 +0200 Subject: [PATCH 76/83] Implementation of OCO order --- .../domain/account/SubAccountTransfer.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) 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 index b248ac8cd..69b7d70cf 100755 --- a/src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java +++ b/src/main/java/com/binance/api/client/domain/account/SubAccountTransfer.java @@ -33,6 +33,16 @@ public class SubAccountTransfer { */ private String qty; + /** + * Type of from account + */ + private String fromAccountType; + + /** + * Type of to account + */ + private String toAccountType; + /** * Transfer status */ @@ -69,6 +79,10 @@ 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; } @@ -102,6 +116,10 @@ public String getQty() { return this.qty; } + public String getFromAccountType() { return this.fromAccountType; } + + public String getToAccountType() { return this.toAccountType; } + public String getStatus() { return this.status; } @@ -122,6 +140,8 @@ public String toString() { .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) From 9337694d27b56ffb5f8b2ee24a3f0331babab18f Mon Sep 17 00:00:00 2001 From: Aldo Alexandro Vargas Meza Date: Sun, 2 May 2021 22:09:37 -0500 Subject: [PATCH 77/83] Update README.md Update the url of the Binance Api Reference --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf74d5d02..e90c3ed4c 100755 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Java Binance API -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. +binance-java-api is a lightweight Java library for interacting with the [Binance API](https://developers.binance.com/docs/api/scopes), providing complete API coverage, and supporting synchronous and asynchronous requests, as well as event streaming using WebSockets. ## 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. From c8d9e7d9456d8363e45a9fc1896a2d81d137f03a Mon Sep 17 00:00:00 2001 From: jim Date: Fri, 11 Jun 2021 21:43:57 +0800 Subject: [PATCH 78/83] latest --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 863f5c234..67e7af532 100755 --- a/pom.xml +++ b/pom.xml @@ -32,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 From d3262e19b84a2a0f53fd78f50896b36a1e692d91 Mon Sep 17 00:00:00 2001 From: jim Date: Sat, 19 Jun 2021 20:24:46 +0800 Subject: [PATCH 79/83] attempting to improve testnet streaming --- .../java/com/binance/api/client/config/BinanceApiConfig.java | 2 +- .../binance/api/client/impl/BinanceApiServiceGenerator.java | 4 ++-- .../api/client/impl/BinanceApiWebSocketClientImpl.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/binance/api/client/config/BinanceApiConfig.java b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java index 276d94838..f4875297b 100755 --- a/src/main/java/com/binance/api/client/config/BinanceApiConfig.java +++ b/src/main/java/com/binance/api/client/config/BinanceApiConfig.java @@ -77,6 +77,6 @@ public static String getTestNetBaseUrl() { * Streaming Spot Test Network base URL. */ public static String getStreamTestNetBaseUrl() { - return String.format("wss://%s", TESTNET_DOMAIN); + return String.format("wss://%s/ws", TESTNET_DOMAIN); } } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java index 7d28ff877..dec8d3047 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiServiceGenerator.java @@ -58,8 +58,8 @@ public static S createService(Class serviceClass, String apiKey, String s String baseUrl = null; if (!BinanceApiConfig.useTestnet) { baseUrl = BinanceApiConfig.getApiBaseUrl(); } else { - baseUrl = BinanceApiConfig.useTestnetStreaming ? - BinanceApiConfig.getStreamTestNetBaseUrl() : + baseUrl = /*BinanceApiConfig.useTestnetStreaming ? + BinanceApiConfig.getStreamTestNetBaseUrl() :*/ BinanceApiConfig.getTestNetBaseUrl(); } diff --git a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java index be0dcf518..4d68fb436 100755 --- a/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java +++ b/src/main/java/com/binance/api/client/impl/BinanceApiWebSocketClientImpl.java @@ -93,7 +93,7 @@ public void close() { } private Closeable createNewWebSocket(String channel, BinanceApiWebSocketListener listener) { - String streamingUrl = String.format("%s/%s", BinanceApiConfig.getStreamApiBaseUrl(), 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 () -> { From 00f6d72ab4ff0f5a5798cf3e2b27acdad90b6003 Mon Sep 17 00:00:00 2001 From: Oleksii Logvin Date: Thu, 24 Jun 2021 15:19:29 +0300 Subject: [PATCH 80/83] Fix deserialization issue for RateLimitType * Cannot deserialize value of type `com.binance.api.client.domain.general.RateLimitType` from String "RAW_REQUESTS": not one of the values accepted for Enum class: [REQUEST_WEIGHT, ORDERS] --- .../com/binance/api/client/domain/general/RateLimitType.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 25775dab5..fb5ee0e89 100755 --- a/src/main/java/com/binance/api/client/domain/general/RateLimitType.java +++ b/src/main/java/com/binance/api/client/domain/general/RateLimitType.java @@ -8,5 +8,6 @@ @JsonIgnoreProperties(ignoreUnknown = true) public enum RateLimitType { REQUEST_WEIGHT, - ORDERS + ORDERS, + RAW_REQUESTS } From 49eef34abc48d2447f4de97daf8d03fa482565ab Mon Sep 17 00:00:00 2001 From: Martijn Courteaux Date: Thu, 24 Jun 2021 19:16:06 +0200 Subject: [PATCH 81/83] Fix non-existent 'outboundAccountInfo' event. Replaced by 'outboundAccountPosition'. --- .../api/client/domain/event/UserDataUpdateEvent.java | 9 ++------- .../domain/event/UserDataUpdateEventDeserializer.java | 3 +-- .../event/UserDataUpdateEventDeserializerTest.java | 4 ++-- 3 files changed, 5 insertions(+), 11 deletions(-) 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 index d95662df1..a9bab3f68 100755 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java @@ -75,9 +75,7 @@ public String toString() { ToStringBuilder sb = new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE) .append("eventType", eventType) .append("eventTime", eventTime); - if (eventType == UserDataUpdateEventType.ACCOUNT_UPDATE) { - sb.append("accountUpdateEvent", accountUpdateEvent); - } else if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { sb.append("accountPositionUpdateEvent", accountUpdateEvent); } else if (eventType == UserDataUpdateEventType.BALANCE_UPDATE) { sb.append("balanceUpdateEvent", balanceUpdateEvent); @@ -88,7 +86,6 @@ public String toString() { } public enum UserDataUpdateEventType { - ACCOUNT_UPDATE("outboundAccountInfo"), ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), BALANCE_UPDATE("balanceUpdate"), ORDER_TRADE_UPDATE("executionReport"), @@ -105,9 +102,7 @@ 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; 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 index 8888bb624..e495b9dff 100755 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java @@ -39,8 +39,7 @@ public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx userDataUpdateEvent.setEventType(userDataUpdateEventType); userDataUpdateEvent.setEventTime(eventTime); - if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_UPDATE || - userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); } else if (userDataUpdateEventType == UserDataUpdateEventType.BALANCE_UPDATE) { diff --git a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java index a50d31221..03ce3e00d 100755 --- a/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java +++ b/src/test/java/com/binance/api/domain/event/UserDataUpdateEventDeserializerTest.java @@ -26,11 +26,11 @@ 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\"}]}"; + 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(), "outboundAccountInfo"); + assertEquals(userDataUpdateEvent.getEventType().getEventTypeId(), "outboundAccountPosition"); assertEquals(userDataUpdateEvent.getEventTime(), 1L); AccountUpdateEvent accountUpdateEvent = userDataUpdateEvent.getAccountUpdateEvent(); for (AssetBalance assetBalance : accountUpdateEvent.getBalances()) { From 8aa6fb51ada60ee31ec36be022a9e50a56fe439c Mon Sep 17 00:00:00 2001 From: Martijn Courteaux Date: Fri, 25 Jun 2021 22:51:32 +0200 Subject: [PATCH 82/83] Fix examples now too. Deprecated the usage of the old naming. The enum itself is left in place for backwards compatibility. --- .../domain/event/UserDataUpdateEvent.java | 21 ++++++++++++++----- .../UserDataUpdateEventDeserializer.java | 2 +- .../examples/AccountBalanceCacheExample.java | 6 +++--- .../examples/MarginUserDataStreamExample.java | 4 ++-- .../api/examples/UserDataStreamExample.java | 4 ++-- 5 files changed, 24 insertions(+), 13 deletions(-) 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 index a9bab3f68..062565790 100755 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEvent.java @@ -24,7 +24,7 @@ public class UserDataUpdateEvent { private long eventTime; - private AccountUpdateEvent accountUpdateEvent; + private AccountUpdateEvent outboundAccountPositionUpdateEvent; private BalanceUpdateEvent balanceUpdateEvent; @@ -46,12 +46,20 @@ 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 void setAccountUpdateEvent(AccountUpdateEvent accountUpdateEvent) { - this.accountUpdateEvent = accountUpdateEvent; + public AccountUpdateEvent getOutboundAccountPositionUpdateEvent() { + return outboundAccountPositionUpdateEvent; + } + + public void setOutboundAccountPositionUpdateEvent(AccountUpdateEvent accountUpdateEvent) { + this.outboundAccountPositionUpdateEvent = accountUpdateEvent; } public BalanceUpdateEvent getBalanceUpdateEvent() { @@ -76,7 +84,7 @@ public String toString() { .append("eventType", eventType) .append("eventTime", eventTime); if (eventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { - sb.append("accountPositionUpdateEvent", accountUpdateEvent); + sb.append("outboundAccountPositionUpdateEvent", outboundAccountPositionUpdateEvent); } else if (eventType == UserDataUpdateEventType.BALANCE_UPDATE) { sb.append("balanceUpdateEvent", balanceUpdateEvent); } else { @@ -86,8 +94,11 @@ public String toString() { } public enum UserDataUpdateEventType { + /** Corresponds to "outboundAccountPosition" events. */ ACCOUNT_POSITION_UPDATE("outboundAccountPosition"), + /** Corresponds to "balanceUpdate" events. */ BALANCE_UPDATE("balanceUpdate"), + /** Corresponds to "executionReport" events. */ ORDER_TRADE_UPDATE("executionReport"), ; 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 index e495b9dff..9e0031efc 100755 --- a/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java +++ b/src/main/java/com/binance/api/client/domain/event/UserDataUpdateEventDeserializer.java @@ -41,7 +41,7 @@ public UserDataUpdateEvent deserialize(JsonParser jp, DeserializationContext ctx if (userDataUpdateEventType == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { AccountUpdateEvent accountUpdateEvent = getUserDataUpdateEventDetail(json, AccountUpdateEvent.class, mapper); - userDataUpdateEvent.setAccountUpdateEvent(accountUpdateEvent); + userDataUpdateEvent.setOutboundAccountPositionUpdateEvent(accountUpdateEvent); } else if (userDataUpdateEventType == UserDataUpdateEventType.BALANCE_UPDATE) { BalanceUpdateEvent balanceUpdateEvent = getUserDataUpdateEventDetail(json, BalanceUpdateEvent.class, mapper); userDataUpdateEvent.setBalanceUpdateEvent(balanceUpdateEvent); diff --git a/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java b/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java index 8fcd51118..59978bb93 100755 --- a/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java +++ b/src/test/java/com/binance/api/examples/AccountBalanceCacheExample.java @@ -9,7 +9,7 @@ import java.util.Map; import java.util.TreeMap; -import static com.binance.api.client.domain.event.UserDataUpdateEvent.UserDataUpdateEventType.ACCOUNT_UPDATE; +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. @@ -58,9 +58,9 @@ private void startAccountBalanceEventStreaming(String listenKey) { BinanceApiWebSocketClient client = clientFactory.newWebSocketClient(); client.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == ACCOUNT_UPDATE) { + if (response.getEventType() == ACCOUNT_POSITION_UPDATE) { // Override cached asset balances - for (AssetBalance assetBalance : response.getAccountUpdateEvent().getBalances()) { + for (AssetBalance assetBalance : response.getOutboundAccountPositionUpdateEvent().getBalances()) { accountBalanceCache.put(assetBalance.getAsset(), assetBalance); } System.out.println(accountBalanceCache); diff --git a/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java b/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java index d6bab71fd..6a27a5fa4 100755 --- a/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java +++ b/src/test/java/com/binance/api/examples/MarginUserDataStreamExample.java @@ -28,8 +28,8 @@ public static void main(String[] args) { // Listen for changes in the account webSocketClient.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) { - AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent(); + if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + AccountUpdateEvent accountUpdateEvent = response.getOutboundAccountPositionUpdateEvent(); // Print new balances of every available asset System.out.println(accountUpdateEvent.getBalances()); } else { diff --git a/src/test/java/com/binance/api/examples/UserDataStreamExample.java b/src/test/java/com/binance/api/examples/UserDataStreamExample.java index 180f5d7b7..b74eed727 100755 --- a/src/test/java/com/binance/api/examples/UserDataStreamExample.java +++ b/src/test/java/com/binance/api/examples/UserDataStreamExample.java @@ -27,8 +27,8 @@ public static void main(String[] args) { // Listen for changes in the account webSocketClient.onUserDataUpdateEvent(listenKey, response -> { - if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_UPDATE) { - AccountUpdateEvent accountUpdateEvent = response.getAccountUpdateEvent(); + if (response.getEventType() == UserDataUpdateEventType.ACCOUNT_POSITION_UPDATE) { + AccountUpdateEvent accountUpdateEvent = response.getOutboundAccountPositionUpdateEvent(); // Print new balances of every available asset System.out.println(accountUpdateEvent.getBalances()); } else { From 2c9d28419a8706e8f2218b10405c795cd854105c Mon Sep 17 00:00:00 2001 From: Liang Shi <365354+2pd@users.noreply.github.com> Date: Fri, 27 Oct 2023 18:16:23 +1100 Subject: [PATCH 83/83] update readme --- README.md | 524 +----------------------------------------------------- 1 file changed, 3 insertions(+), 521 deletions(-) diff --git a/README.md b/README.md index e90c3ed4c..ef8668215 100755 --- a/README.md +++ b/README.md @@ -1,523 +1,5 @@ -# Java Binance API +# Discontinue this Library -binance-java-api is a lightweight Java library for interacting with the [Binance API](https://developers.binance.com/docs/api/scopes), 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").orderRespType(OrderResponseType.FULL)); -List fills = newOrderResponse.getFills(); -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(); -``` - -User needs to be aware that REST symbols which are `upper case` differ from WebSocket symbols which must be `lower case`. -In scenario of subscription with upper case styled symbol, server will return no error and subscribe to given channel - however, no events will be pushed. - -#### 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()); - } -}); -``` - -#### Multi-channel subscription -Client provides a way for user to subscribe to multiple channels using same websocket - to achieve that user needs to coma-separate symbols as it is in following examples. - -````java -client.onAggTradeEvent("ethbtc,ethusdt", (AggTradeEvent response) -> { - if (Objects.equals(response.getSymbol(),"ethbtc")) { - // handle ethbtc event - } else if(Objects.equals(response.getSymbol()),"ethusdt")) { - // handle ethusdt event - } -}); -```` -````java -client.onDepthEvent("ethbtc,ethusdt", (DepthEvent response) -> { - if (Objects.equals(response.getSymbol(),"ethbtc")) { - // handle ethbtc event - } else if(Objects.equals(response.getSymbol()),"ethusdt")) { - // handle ethusdt event - } -}); -```` -````java -client.onCandlestickEvent("ethbtc,ethusdt", CandlestickInterval.ONE_MINUTE, (CandlestickEvent response) -> { - if (Objects.equals(response.getSymbol(),"ethbtc")) { - // handle ethbtc event - } else if(Objects.equals(response.getSymbol()),"ethusdt")) { - // handle ethusdt event - } -}); -```` - -### 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