From e69dccb5cedf4a84af8eca19de9167766ee2f4f9 Mon Sep 17 00:00:00 2001 From: Tim Molter Date: Mon, 14 Oct 2024 20:47:03 +0200 Subject: [PATCH] format code with fmt-maven-plugin --- pom.xml | 6 +- .../bibox/service/BiboxTradeService.java | 1 - .../xchange/binance/BinanceAdapters.java | 11 +- .../xchange/binance/BinanceAuthenticated.java | 2 - .../xchange/binance/BinanceExchange.java | 80 ++-- .../knowm/xchange/binance/BinanceFutures.java | 3 +- .../xchange/binance/dto/ExchangeType.java | 1 - .../dto/account/BinanceCurrencyInfo.java | 2 - .../binance/dto/marketdata/BinancePrice.java | 1 - .../dto/marketdata/BinancePriceQuantity.java | 1 - .../dto/marketdata/BinanceTicker24h.java | 1 - .../binance/dto/meta/BinanceSystemStatus.java | 7 +- .../service/BinanceAccountService.java | 28 +- .../service/BinanceAccountServiceRaw.java | 6 +- .../binance/service/BinanceBaseService.java | 52 +- .../service/BinanceMarketDataService.java | 8 +- .../service/BinanceMarketDataServiceRaw.java | 7 +- .../binance/AbstractResilienceTest.java | 3 +- .../BinanceExchangeTypeIntegration.java | 8 +- .../xchange/binance/BinanceFutureTest.java | 3 +- .../binance/ExchangeMetaDataIntegration.java | 21 +- .../account/AccountServiceIntegration.java | 2 - .../MarketDataServiceIntegration.java | 30 +- .../java/org/knowm/xchange/bitget/Bitget.java | 9 +- .../knowm/xchange/bitget/BitgetAdapters.java | 98 ++-- .../xchange/bitget/BitgetAuthenticated.java | 4 - .../knowm/xchange/bitget/BitgetExchange.java | 23 +- .../deserializer/FeeDetailDeserializer.java | 2 +- .../xchange/bitget/dto/BitgetException.java | 1 - .../xchange/bitget/dto/BitgetResponse.java | 27 +- .../bitget/dto/account/BitgetBalanceDto.java | 27 +- .../bitget/dto/marketdata/BitgetChainDto.java | 75 ++- .../bitget/dto/marketdata/BitgetCoinDto.java | 25 +- .../dto/marketdata/BitgetMarketDepthDto.java | 1 - .../dto/marketdata/BitgetServerTime.java | 1 - .../dto/marketdata/BitgetSymbolDto.java | 94 ++-- .../dto/marketdata/BitgetTickerDto.java | 65 ++- .../bitget/dto/trade/BitgetOrderInfoDto.java | 183 ++++--- .../bitget/dto/trade/BitgetPlaceOrderDto.java | 125 +++-- .../bitget/service/BitgetAccountService.java | 2 - .../service/BitgetAccountServiceRaw.java | 5 +- .../bitget/service/BitgetBaseService.java | 24 +- .../xchange/bitget/service/BitgetDigest.java | 2 - .../service/BitgetMarketDataService.java | 9 +- .../service/BitgetMarketDataServiceRaw.java | 8 - .../bitget/service/BitgetTradeService.java | 11 +- .../bitget/service/BitgetTradeServiceRaw.java | 17 +- .../bitget/BitgetExchangeIntegration.java | 7 +- .../bitget/BitgetExchangeWiremock.java | 2 +- .../bitget/BitgetIntegrationTestParent.java | 5 +- .../BitgetAccountServiceIntegration.java | 6 +- .../bitget/service/BitgetDigestTest.java | 8 +- .../BitgetMarketDataServiceIntegration.java | 59 +-- ...BitgetMarketDataServiceRawIntegration.java | 57 ++- .../service/BitgetTradeServiceTest.java | 23 +- .../bitstamp/BitstampAuthenticatedV2.java | 2 +- .../xchange/bitstamp/BitstampExchange.java | 3 +- .../dto/account/WithdrawalRequest.java | 1 + .../dto/trade/BitstampOrderFlags.java | 11 +- .../service/BitstampAccountServiceRaw.java | 53 +-- .../service/BitstampTradeService.java | 6 +- .../service/BitstampTradeServiceRaw.java | 8 +- .../dto/account/WithdrawalFeesJSONTest.java | 3 +- .../service/BlockchainMarketDataService.java | 2 - .../java/org/knowm/xchange/bybit/Bybit.java | 8 +- .../knowm/xchange/bybit/BybitAdapters.java | 85 ++-- .../xchange/bybit/BybitAuthenticated.java | 13 +- .../knowm/xchange/bybit/BybitExchange.java | 6 +- .../dto/trade/BybitAmendOrderPayload.java | 20 +- .../dto/trade/BybitCancelOrderPayload.java | 5 +- .../dto/trade/BybitPlaceOrderPayload.java | 17 +- .../bybit/service/BybitMarketDataService.java | 24 +- .../bybit/service/BybitTradeService.java | 38 +- .../bybit/service/BybitTradeServiceRaw.java | 111 +++-- .../xchange/bybit/BybitAdaptersTest.java | 7 +- .../org/knowm/xchange/bybit/TradeExample.java | 110 +++-- .../java/org/knowm/xchange/coinex/Coinex.java | 19 +- .../knowm/xchange/coinex/CoinexAdapters.java | 85 ++-- .../xchange/coinex/CoinexAuthenticated.java | 2 - .../knowm/xchange/coinex/CoinexExchange.java | 27 +- .../CurrencyPairToStringConverter.java | 4 +- .../converter/OrderTypeToStringConverter.java | 4 +- .../StringToOrderStatusConverter.java | 4 +- .../converter/StringToOrderTypeConverter.java | 4 +- .../xchange/coinex/dto/CoinexException.java | 1 - .../xchange/coinex/dto/CoinexResponse.java | 1 - .../coinex/dto/account/CoinexBalanceInfo.java | 1 - .../coinex/dto/account/CoinexMarketType.java | 2 - .../coinex/dto/account/CoinexOrder.java | 1 - .../CoinexAllMarketStatisticsV1.java | 1 - .../dto/marketdata/CoinexChainInfo.java | 39 +- .../marketdata/CoinexCurrencyPairInfo.java | 2 - .../dto/marketdata/CoinexMarketDepth.java | 1 - .../CoinexSingleMarketStatisticsV1.java | 1 - .../service/CoinexAccountServiceRaw.java | 4 +- .../coinex/service/CoinexBaseService.java | 24 +- .../service/CoinexMarketDataService.java | 46 +- .../service/CoinexMarketDataServiceRaw.java | 23 +- .../coinex/service/CoinexTradeService.java | 10 +- .../coinex/service/CoinexTradeServiceRaw.java | 12 +- .../coinex/service/CoinexV2Digest.java | 5 +- .../service/params/CoinexOrderBookParams.java | 1 - .../coinex/CoinexExchangeIntegration.java | 8 +- .../CoinexAccountServiceIntegration.java | 4 +- .../CoinexMarketDataServiceIntegration.java | 50 +- ...CoinexMarketDataServiceRawIntegration.java | 17 +- .../coinex/service/CoinexV2DigestTest.java | 8 +- .../coingi/service/CoingiAccountService.java | 1 - .../dto/account/TransferHistoryOrder.java | 3 +- .../trade/CoinmateTransferHistoryEntry.java | 7 +- .../service/CoinmateAccountService.java | 30 +- .../service/CoinmateAccountServiceRaw.java | 33 +- .../xchange/dto/account/OpenPosition.java | 1 - .../xchange/dto/marketdata/OrderBook.java | 14 +- .../xchange/dto/meta/ExchangeHealth.java | 4 +- .../dto/marketdata/ConcurrencyTest.java | 125 +++-- .../xchange/dto/marketdata/OrderBookOld.java | 449 +++++++++--------- .../marketdata/BinanceMarketDataDemo.java | 4 +- .../java/org/knowm/xchange/gateio/Gateio.java | 22 +- .../knowm/xchange/gateio/GateioAdapters.java | 111 +++-- .../xchange/gateio/GateioErrorAdapter.java | 6 +- .../knowm/xchange/gateio/GateioExchange.java | 15 +- .../xchange/gateio/GateioV4Authenticated.java | 71 ++- .../knowm/xchange/gateio/config/Config.java | 1 - .../CurrencyPairToStringConverter.java | 4 +- .../converter/DoubleToInstantConverter.java | 4 +- .../converter/OrderTypeToStringConverter.java | 4 +- .../converter/StringToBooleanConverter.java | 4 +- .../converter/StringToCurrencyConverter.java | 4 +- .../StringToCurrencyPairConverter.java | 4 +- .../converter/StringToOrderTypeConverter.java | 4 +- .../TimestampSecondsToInstantConverter.java | 4 +- .../xchange/gateio/dto/GateioException.java | 1 - .../dto/account/GateioAccountBookRecord.java | 3 - .../dto/account/GateioAddressRecord.java | 1 - .../dto/account/GateioCurrencyBalance.java | 1 - .../dto/account/GateioDepositAddress.java | 4 - .../dto/account/GateioDepositRecord.java | 3 - .../gateio/dto/account/GateioOrder.java | 1 - .../dto/account/GateioSubAccountTransfer.java | 1 - .../dto/account/GateioWithdrawStatus.java | 5 +- .../dto/account/GateioWithdrawalRecord.java | 3 - .../dto/account/GateioWithdrawalRequest.java | 1 - .../GateioSubAccountTransfersParams.java | 1 - .../dto/marketdata/GateioCurrencyChain.java | 2 - .../dto/marketdata/GateioCurrencyInfo.java | 3 - .../marketdata/GateioCurrencyPairDetails.java | 1 - .../dto/marketdata/GateioOrderBook.java | 3 - .../dto/marketdata/GateioServerTime.java | 1 - .../gateio/dto/marketdata/GateioTicker.java | 1 - .../gateio/dto/trade/GateioUserTrade.java | 50 +- .../gateio/dto/trade/GateioUserTradeRaw.java | 1 - .../knowm/xchange/gateio/dto/trade/Role.java | 5 +- .../gateio/service/GateioAccountService.java | 34 +- .../service/GateioAccountServiceRaw.java | 118 +++-- .../gateio/service/GateioBaseService.java | 37 +- .../service/GateioMarketDataService.java | 30 +- .../service/GateioMarketDataServiceRaw.java | 14 +- .../gateio/service/GateioTradeService.java | 36 +- .../gateio/service/GateioTradeServiceRaw.java | 107 +++-- .../gateio/service/GateioV4Digest.java | 6 +- .../service/params/GateioDepositsParams.java | 1 - .../params/GateioFundingHistoryParams.java | 4 +- .../params/GateioTradeHistoryParams.java | 9 +- .../params/GateioWithdrawFundsParams.java | 1 - .../params/GateioWithdrawalsParams.java | 1 - .../xchange/gateio/GateioExchangeTest.java | 23 +- .../gateio/GateioExchangeWiremock.java | 18 +- .../marketdata/GateioCurrencyChainTest.java | 2 +- .../marketdata/GateioCurrencyInfoTest.java | 3 +- .../service/GateioAccountServiceRawTest.java | 254 +++++----- .../service/GateioAccountServiceTest.java | 117 +++-- .../gateio/service/GateioBaseServiceTest.java | 13 +- .../GateioMarketDataServiceIntegration.java | 52 +- .../GateioMarketDataServiceRawTest.java | 161 +++---- .../service/GateioMarketDataServiceTest.java | 54 +-- .../service/GateioTradeServiceRawTest.java | 175 ++++--- .../service/GateioTradeServiceTest.java | 154 +++--- .../gateio/service/GateioV4DigestTest.java | 9 +- .../BodyLoggingRestInvocationHandler.java | 25 +- .../rescu/CustomRestProxyFactoryImpl.java | 11 +- .../service/GateioMarketDataServiceTest.java | 2 +- .../service/GlobitexAccountService.java | 1 - .../KrakenMarketDataServiceIntegration.java | 51 +- .../KucoinMarketDataServiceIntegration.java | 21 +- .../lykke/service/LykkeAccountService.java | 1 - .../service/OkCoinFuturesAccountService.java | 1 - .../java/org/knowm/xchange/okex/Okex.java | 6 +- .../org/knowm/xchange/okex/OkexAdapters.java | 28 +- .../knowm/xchange/okex/dto/OkexInstType.java | 8 +- .../okex/service/OkexMarketDataService.java | 5 +- .../service/OkexMarketDataServiceRaw.java | 34 +- .../okex/OkexPublicDataIntegration.java | 8 +- .../BinanceStreamingMarketDataService.java | 7 +- .../BinanceUserDataStreamingService.java | 1 - .../BinanceFuturesPublicStreamsTest.java | 3 +- .../binance/BinanceManualExample.java | 3 +- .../BinanceStreamExchangeTypeIntegration.java | 43 +- .../xchangestream/bitmex/BitmexTest.java | 6 +- ...stampStreamingMarketDataServiceV2Test.java | 6 +- .../BTCMarketsStreamingAdapters.java | 1 - .../main/java/dto/BybitSubscribeMessage.java | 7 +- .../java/dto/marketdata/BybitOrderbook.java | 3 +- .../dto/marketdata/BybitOrderbookData.java | 4 +- .../java/dto/marketdata/BybitPublicOrder.java | 1 - .../dto/trade/BybitComplexOrderChanges.java | 73 ++- .../trade/BybitComplexPositionChanges.java | 39 +- .../dto/trade/BybitOrderChangesResponse.java | 1 - .../trade/BybitPositionChangesResponse.java | 5 - .../src/main/java/dto/trade/BybitTrade.java | 27 +- .../bybit/BybitStreamAdapters.java | 136 ++++-- .../bybit/BybitStreamingExchange.java | 11 +- .../BybitStreamingMarketDataService.java | 41 +- .../bybit/BybitStreamingService.java | 37 +- .../bybit/BybitStreamingTradeService.java | 52 +- .../bybit/BybitStreamExample.java | 186 ++++---- .../CexioStreamingMarketDataService.java | 1 - .../CoinjarStreamingMarketDataService.java | 1 - .../coinjar/CoinjarOrderChangesExample.java | 7 +- .../coinjar/CoinjarUserTradesExample.java | 7 +- .../core/StreamingMarketDataService.java | 10 +- .../v1/dydxStreamingMarketDataService.java | 1 - .../v3/dydxStreamingMarketDataService.java | 1 - .../gateio/GateioStreamingAccountService.java | 5 +- .../gateio/GateioStreamingAdapters.java | 35 +- .../gateio/GateioStreamingAuthHelper.java | 6 +- .../gateio/GateioStreamingExchange.java | 6 +- .../GateioStreamingMarketDataService.java | 7 +- .../gateio/GateioStreamingService.java | 125 +++-- .../gateio/GateioStreamingTradeService.java | 1 - .../xchangestream/gateio/config/Config.java | 6 +- .../gateio/config/IdGenerator.java | 6 +- .../InstantToTimestampSecondsConverter.java | 4 +- .../xchangestream/gateio/dto/Event.java | 5 +- .../gateio/dto/request/GateioWsRequest.java | 3 - .../CurrencyPairLevelIntervalPayload.java | 1 - .../request/payload/CurrencyPairPayload.java | 1 - .../dto/request/payload/EmptyPayload.java | 4 +- .../dto/request/payload/StringPayload.java | 1 - .../dto/response/GateioWsNotification.java | 17 +- .../dto/response/balance/BalancePayload.java | 2 - ...GateioMultipleSpotBalanceNotification.java | 19 +- .../GateioSingleSpotBalanceNotification.java | 2 - .../GateioOrderBookNotification.java | 6 +- .../response/orderbook/OrderBookPayload.java | 5 - .../ticker/GateioTickerNotification.java | 6 +- .../dto/response/ticker/TickerPayload.java | 1 - .../trade/GateioTradeNotification.java | 5 +- .../dto/response/trade/TradePayload.java | 1 - .../GateioMultipleUserTradeNotification.java | 19 +- .../GateioSingleUserTradeNotification.java | 5 +- .../response/usertrade/UserTradePayload.java | 1 - ...eioStreamingAccountServiceIntegration.java | 23 +- .../GateioStreamingAccountServiceTest.java | 38 +- .../gateio/GateioStreamingAuthHelperTest.java | 6 +- .../gateio/GateioStreamingExchangeIT.java | 27 +- ...StreamingMarketDataServiceIntegration.java | 40 +- .../GateioStreamingMarketDataServiceTest.java | 81 ++-- .../gateio/GateioStreamingServiceTest.java | 13 +- ...ateioStreamingTradeServiceIntegration.java | 31 +- .../GateioStreamingTradeServiceTest.java | 48 +- .../response/GateioWsNotificationTest.java | 13 +- .../GeminiStreamingMarketDataService.java | 1 - .../kraken/KrakenStreamingAdapters.java | 2 +- .../KrakenStreamingMarketDataService.java | 13 +- .../kraken/KrakenStreamingService.java | 24 +- .../kraken/dto/KrakenStreamingOhlc.java | 15 +- .../kraken/dto/KrakenSubscriptionConfig.java | 2 +- .../kucoin/KucoinStreamingExchange.java | 3 - .../kucoin/KucoinStreamingService.java | 1 - .../lgo/LgoStreamingMarketDataService.java | 1 - .../okex/OkexStreamingExchange.java | 2 +- .../okex/OkexStreamingMarketDataService.java | 33 +- .../OkexStreamingPublicDataIntegration.java | 2 +- .../service/netty/NettyStreamingService.java | 3 +- 275 files changed, 3207 insertions(+), 3130 deletions(-) diff --git a/pom.xml b/pom.xml index ec7bc6a7de3..588bcc80bc1 100644 --- a/pom.xml +++ b/pom.xml @@ -461,7 +461,7 @@ com.spotify.fmt fmt-maven-plugin - 2.23 + 2.25 .*\.java false @@ -508,7 +508,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.7.0 + 3.10.1 true none @@ -590,7 +590,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.7.0 + 3.10.1 attach-javadocs diff --git a/xchange-bibox/src/main/java/org/knowm/xchange/bibox/service/BiboxTradeService.java b/xchange-bibox/src/main/java/org/knowm/xchange/bibox/service/BiboxTradeService.java index 690b58c0921..5c373793caa 100644 --- a/xchange-bibox/src/main/java/org/knowm/xchange/bibox/service/BiboxTradeService.java +++ b/xchange-bibox/src/main/java/org/knowm/xchange/bibox/service/BiboxTradeService.java @@ -68,5 +68,4 @@ public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { return BiboxAdapters.adaptUserTrades(getBiboxOrderHistory()); } - } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java index ab2ac00628a..87b4c653967 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java @@ -66,7 +66,6 @@ public class BinanceAdapters { private static final Map SYMBOL_TO_CURRENCY_PAIR = new HashMap<>(); - private BinanceAdapters() {} /** @@ -186,17 +185,14 @@ public static OrderType convertType(boolean isBuyer) { return isBuyer ? OrderType.BID : OrderType.ASK; } - public static void putSymbolMapping(String symbol, CurrencyPair currencyPair) { SYMBOL_TO_CURRENCY_PAIR.put(symbol, currencyPair); } - public static CurrencyPair toCurrencyPair(String symbol) { return SYMBOL_TO_CURRENCY_PAIR.get(symbol); } - public static Instrument adaptSymbol(String symbol, boolean isFuture) { CurrencyPair currencyPair = toCurrencyPair(symbol); @@ -247,9 +243,11 @@ public static Order adaptOrder(BinanceOrder order, boolean isFuture) { return builder.build(); } - public static Ticker toTicker(BinanceTicker24h binanceTicker24h, boolean isFuture) { - Instrument instrument = (isFuture) ? new FuturesContract(binanceTicker24h.getCurrencyPair(), "PERP"): binanceTicker24h.getCurrencyPair(); + Instrument instrument = + (isFuture) + ? new FuturesContract(binanceTicker24h.getCurrencyPair(), "PERP") + : binanceTicker24h.getCurrencyPair(); return new Ticker.Builder() .instrument(instrument) .open(binanceTicker24h.getOpenPrice()) @@ -269,7 +267,6 @@ public static Ticker toTicker(BinanceTicker24h binanceTicker24h, boolean isFutur .build(); } - static CurrencyMetaData adaptCurrencyMetaData( Map currencies, Currency currency, diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java index eddeaee6ccb..b8503410818 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java @@ -338,7 +338,6 @@ BinanceDustLog getDustLog( @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; - @GET @Path("/sapi/v1/capital/config/getall") List getCurrencyInfos( @@ -348,7 +347,6 @@ List getCurrencyInfos( @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; - /** * Submit a withdraw request. * diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceExchange.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceExchange.java index 2d82ab3c84b..88bed19bc20 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceExchange.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceExchange.java @@ -87,13 +87,13 @@ public void applySpecification(ExchangeSpecification exchangeSpecification) { } public boolean isFuturesEnabled() { - return ExchangeType.FUTURES.equals(exchangeSpecification. - getExchangeSpecificParametersItem(EXCHANGE_TYPE)); + return ExchangeType.FUTURES.equals( + exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE)); } public boolean isPortfolioMarginEnabled() { - return ExchangeType.PORTFOLIO_MARGIN.equals(exchangeSpecification - .getExchangeSpecificParametersItem(EXCHANGE_TYPE)); + return ExchangeType.PORTFOLIO_MARGIN.equals( + exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE)); } public boolean usingSandbox() { @@ -103,7 +103,8 @@ public boolean usingSandbox() { @Override public void remoteInit() { try { - BinanceMarketDataServiceRaw marketDataServiceRaw = (BinanceMarketDataServiceRaw) marketDataService; + BinanceMarketDataServiceRaw marketDataServiceRaw = + (BinanceMarketDataServiceRaw) marketDataService; BinanceAccountService accountService = (BinanceAccountService) getAccountService(); Map assetDetailMap = null; if (!usingSandbox() && isAuthenticated()) { @@ -112,7 +113,10 @@ public void remoteInit() { BinanceExchangeInfo exchangeInfo; // get exchange type or SPOT as default - ExchangeType exchangeType = (ExchangeType) ObjectUtils.defaultIfNull(exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE), SPOT); + ExchangeType exchangeType = + (ExchangeType) + ObjectUtils.defaultIfNull( + exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE), SPOT); switch (exchangeType) { case FUTURES: @@ -126,8 +130,15 @@ public void remoteInit() { // init symbol mappings exchangeInfo.getSymbols().stream() - .filter(symbol -> ObjectUtils.allNotNull(symbol.getBaseAsset(), symbol.getQuoteAsset(), symbol.getSymbol())) - .forEach(symbol -> BinanceAdapters.putSymbolMapping(symbol.getSymbol(), new CurrencyPair(symbol.getBaseAsset(), symbol.getQuoteAsset()))); + .filter( + symbol -> + ObjectUtils.allNotNull( + symbol.getBaseAsset(), symbol.getQuoteAsset(), symbol.getSymbol())) + .forEach( + symbol -> + BinanceAdapters.putSymbolMapping( + symbol.getSymbol(), + new CurrencyPair(symbol.getBaseAsset(), symbol.getQuoteAsset()))); } catch (Exception e) { throw new ExchangeException("Failed to initialize: " + e.getMessage(), e); @@ -140,38 +151,37 @@ protected boolean isAuthenticated() { && exchangeSpecification.getSecretKey() != null; } - /** - * Adjust host parameters depending on exchange specific parameters - */ + /** Adjust host parameters depending on exchange specific parameters */ private static void concludeHostParams(ExchangeSpecification exchangeSpecification) { - if(exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE) != null) { - switch ((ExchangeType)exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE)) { - case SPOT: { - if (enabledSandbox(exchangeSpecification)) - exchangeSpecification.setSslUri(SANDBOX_SPOT_URL); - break; - } - case FUTURES: { - if (!enabledSandbox(exchangeSpecification)) - exchangeSpecification.setSslUri(FUTURES_URL); - else - exchangeSpecification.setSslUri(SANDBOX_FUTURES_URL); - break; - } - case INVERSE: { - if (!enabledSandbox(exchangeSpecification)) - exchangeSpecification.setSslUri(INVERSE_FUTURES_URL); - else - exchangeSpecification.setSslUri(SANDBOX_INVERSE_FUTURES_URL); - break; - } + if (exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE) != null) { + switch ((ExchangeType) + exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE)) { + case SPOT: + { + if (enabledSandbox(exchangeSpecification)) + exchangeSpecification.setSslUri(SANDBOX_SPOT_URL); + break; + } + case FUTURES: + { + if (!enabledSandbox(exchangeSpecification)) + exchangeSpecification.setSslUri(FUTURES_URL); + else exchangeSpecification.setSslUri(SANDBOX_FUTURES_URL); + break; + } + case INVERSE: + { + if (!enabledSandbox(exchangeSpecification)) + exchangeSpecification.setSslUri(INVERSE_FUTURES_URL); + else exchangeSpecification.setSslUri(SANDBOX_INVERSE_FUTURES_URL); + break; + } } } } - private static boolean enabledSandbox(ExchangeSpecification exchangeSpecification) { - return Boolean.TRUE.equals(exchangeSpecification.getExchangeSpecificParametersItem(USE_SANDBOX)); + return Boolean.TRUE.equals( + exchangeSpecification.getExchangeSpecificParametersItem(USE_SANDBOX)); } - } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceFutures.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceFutures.java index abd251eb424..180978557f6 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceFutures.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceFutures.java @@ -73,8 +73,7 @@ BinanceTicker24h ticker24h(@QueryParam("symbol") String symbol) */ @GET @Path("fapi/v1/ticker/24hr") - List ticker24h() - throws IOException, BinanceException; + List ticker24h() throws IOException, BinanceException; /** * Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/ExchangeType.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/ExchangeType.java index ed0a05cdd1f..61605fbeaab 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/ExchangeType.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/ExchangeType.java @@ -9,4 +9,3 @@ public enum ExchangeType { INVERSE, PORTFOLIO_MARGIN; } - diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/BinanceCurrencyInfo.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/BinanceCurrencyInfo.java index 99b7ada13c4..b8ca563532e 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/BinanceCurrencyInfo.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/BinanceCurrencyInfo.java @@ -58,7 +58,6 @@ public class BinanceCurrencyInfo { @JsonProperty("networkList") private List networks; - @Data @Builder @Jacksonized @@ -133,6 +132,5 @@ public static class Network { @JsonProperty("contractAddress") private String contractAddress; - } } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePrice.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePrice.java index 3ecef525356..88898cd6e52 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePrice.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePrice.java @@ -24,5 +24,4 @@ public class BinancePrice { public boolean isValid() { return currencyPair != null && price != null; } - } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePriceQuantity.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePriceQuantity.java index 1c0dc93cd9d..4b5e99f9acf 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePriceQuantity.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinancePriceQuantity.java @@ -34,5 +34,4 @@ public final class BinancePriceQuantity { public boolean isValid() { return ObjectUtils.allNotNull(currencyPair, bidPrice, bidQty, askPrice, askQty); } - } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinanceTicker24h.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinanceTicker24h.java index 77a722d9ca4..85822caef6b 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinanceTicker24h.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/marketdata/BinanceTicker24h.java @@ -41,7 +41,6 @@ public final class BinanceTicker24h { @JsonDeserialize(converter = StringToCurrencyPairConverter.class) private CurrencyPair currencyPair; - public boolean isValid() { return currencyPair != null; } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/meta/BinanceSystemStatus.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/meta/BinanceSystemStatus.java index 54f7c981877..16335076d14 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/meta/BinanceSystemStatus.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/dto/meta/BinanceSystemStatus.java @@ -11,11 +11,8 @@ public class BinanceSystemStatus { // 0: normal,1:system maintenance - @JsonProperty - String status; + @JsonProperty String status; // normal or system maintenance - @JsonProperty - String msg; - + @JsonProperty String msg; } diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountService.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountService.java index 6fe9d290f72..fb37325ce54 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountService.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountService.java @@ -109,19 +109,21 @@ public AccountInfo getAccountInfo() throws IOException { try { List wallets = new ArrayList<>(); List openPositions = new ArrayList<>(); - switch ((ExchangeType)exchange.getExchangeSpecification().getExchangeSpecificParametersItem( - EXCHANGE_TYPE)) { - case SPOT: { - wallets.add(BinanceAdapters.adaptBinanceSpotWallet(account())); - break; - } - case FUTURES: { - BinanceFutureAccountInformation futureAccountInformation = futuresAccount(); - wallets.add(BinanceAdapters.adaptBinanceFutureWallet(futureAccountInformation)); - openPositions.addAll( - BinanceAdapters.adaptOpenPositions(futureAccountInformation.getPositions())); - break; - } + switch ((ExchangeType) + exchange.getExchangeSpecification().getExchangeSpecificParametersItem(EXCHANGE_TYPE)) { + case SPOT: + { + wallets.add(BinanceAdapters.adaptBinanceSpotWallet(account())); + break; + } + case FUTURES: + { + BinanceFutureAccountInformation futureAccountInformation = futuresAccount(); + wallets.add(BinanceAdapters.adaptBinanceFutureWallet(futureAccountInformation)); + openPositions.addAll( + BinanceAdapters.adaptOpenPositions(futureAccountInformation.getPositions())); + break; + } } return new AccountInfo( exchange.getExchangeSpecification().getUserName(), diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountServiceRaw.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountServiceRaw.java index b4a766a73f3..4b920c56a59 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountServiceRaw.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceAccountServiceRaw.java @@ -39,16 +39,16 @@ public BinanceAccountInformation account() throws BinanceException, IOException .call(); } - public List currencyInfos() throws BinanceException, IOException { return decorateApiCall( - () -> binance.getCurrencyInfos(getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) + () -> + binance.getCurrencyInfos( + getRecvWindow(), getTimestampFactory(), apiKey, signatureCreator)) .withRetry(retry("currencyInfo")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER), 5) .call(); } - public BinanceFutureAccountInformation futuresAccount() throws BinanceException, IOException { return decorateApiCall( () -> diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceBaseService.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceBaseService.java index 2df288edb7e..12386c8635c 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceBaseService.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceBaseService.java @@ -37,30 +37,34 @@ protected BinanceBaseService( .build(); ExchangeSpecification futuresSpec; ExchangeSpecification inverseFuturesSpec; - if(exchange.getExchangeSpecification().getExchangeSpecificParametersItem(EXCHANGE_TYPE) != null) - { - switch ((ExchangeType) exchange.getExchangeSpecification() - .getExchangeSpecificParametersItem(EXCHANGE_TYPE)) { - case SPOT: { - break; - } - case FUTURES: { - futuresSpec = exchange.getExchangeSpecification(); - binanceFutures = - ExchangeRestProxyBuilder.forInterface(BinanceFuturesAuthenticated.class, futuresSpec) - .build(); - inverseBinanceFutures = null; - break; - } - case INVERSE: { - inverseFuturesSpec = exchange.getExchangeSpecification(); - inverseBinanceFutures = - ExchangeRestProxyBuilder.forInterface(BinanceFuturesAuthenticated.class, - inverseFuturesSpec) - .build(); - binanceFutures = null; - break; - } + if (exchange.getExchangeSpecification().getExchangeSpecificParametersItem(EXCHANGE_TYPE) + != null) { + switch ((ExchangeType) + exchange.getExchangeSpecification().getExchangeSpecificParametersItem(EXCHANGE_TYPE)) { + case SPOT: + { + break; + } + case FUTURES: + { + futuresSpec = exchange.getExchangeSpecification(); + binanceFutures = + ExchangeRestProxyBuilder.forInterface( + BinanceFuturesAuthenticated.class, futuresSpec) + .build(); + inverseBinanceFutures = null; + break; + } + case INVERSE: + { + inverseFuturesSpec = exchange.getExchangeSpecification(); + inverseBinanceFutures = + ExchangeRestProxyBuilder.forInterface( + BinanceFuturesAuthenticated.class, inverseFuturesSpec) + .build(); + binanceFutures = null; + break; + } } } this.apiKey = exchange.getExchangeSpecification().getApiKey(); diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataService.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataService.java index 91d01008baa..cf1d2e54fe3 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataService.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataService.java @@ -36,7 +36,6 @@ public BinanceMarketDataService( super(exchange, resilienceRegistries); } - @Override public ExchangeHealth getExchangeHealth() { try { @@ -49,7 +48,6 @@ public ExchangeHealth getExchangeHealth() { return ExchangeHealth.OFFLINE; } - /** * optional parameters provided in the args array: * @@ -70,19 +68,18 @@ public Trades getTrades(Instrument instrument, Object... args) throws IOExceptio @Override public Ticker getTicker(Instrument instrument, Object... args) throws IOException { try { - return BinanceAdapters.toTicker(ticker24hAllProducts(instrument), instrument instanceof FuturesContract); + return BinanceAdapters.toTicker( + ticker24hAllProducts(instrument), instrument instanceof FuturesContract); } catch (BinanceException e) { throw BinanceErrorAdapter.adapt(e); } } - @Override public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { return getTicker((Instrument) currencyPair, args); } - @Override public List getTickers(Params params) throws IOException { try { @@ -102,7 +99,6 @@ public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws return getOrderBook((Instrument) currencyPair, args); } - @Override public OrderBook getOrderBook(Instrument instrument, Object... args) throws IOException { return getBinanceOrderBook(instrument, args); diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataServiceRaw.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataServiceRaw.java index fe3ca61615e..db7997dfd6e 100644 --- a/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataServiceRaw.java +++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/service/BinanceMarketDataServiceRaw.java @@ -40,7 +40,6 @@ public BinanceTime binanceTime() throws IOException { .call(); } - public BinanceExchangeInfo getExchangeInfo() throws IOException { return decorateApiCall(binance::exchangeInfo) .withRetry(retry("exchangeInfo")) @@ -48,7 +47,6 @@ public BinanceExchangeInfo getExchangeInfo() throws IOException { .call(); } - public BinanceExchangeInfo getFutureExchangeInfo() throws IOException { return decorateApiCall(binanceFutures::exchangeInfo) .withRetry(retry("exchangeInfo")) @@ -56,7 +54,6 @@ public BinanceExchangeInfo getFutureExchangeInfo() throws IOException { .call(); } - public BinanceOrderbook getBinanceOrderbookAllProducts(Instrument pair, Integer limit) throws IOException { return decorateApiCall( @@ -109,13 +106,13 @@ public List klines( } public List ticker24hAllProducts(boolean isFutures) throws IOException { - if(isFutures) + if (isFutures) return decorateApiCall(binanceFutures::ticker24h) .withRetry(retry("ticker24h")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER), 40) .call(); else - return decorateApiCall(binance::ticker24h) + return decorateApiCall(binance::ticker24h) .withRetry(retry("ticker24h")) .withRateLimiter(rateLimiter(REQUEST_WEIGHT_RATE_LIMITER), 80) .call(); diff --git a/xchange-binance/src/test/java/org/knowm/xchange/binance/AbstractResilienceTest.java b/xchange-binance/src/test/java/org/knowm/xchange/binance/AbstractResilienceTest.java index 8f9dd14b57a..6616aca0dcb 100644 --- a/xchange-binance/src/test/java/org/knowm/xchange/binance/AbstractResilienceTest.java +++ b/xchange-binance/src/test/java/org/knowm/xchange/binance/AbstractResilienceTest.java @@ -32,7 +32,8 @@ protected BinanceExchange createExchangeWithRateLimiterEnabled() { } protected BinanceExchange createExchange(boolean retryEnabled, boolean rateLimiterEnabled) { - BinanceExchange exchange = ExchangeFactory.INSTANCE.createExchangeWithoutSpecification(BinanceExchange.class); + BinanceExchange exchange = + ExchangeFactory.INSTANCE.createExchangeWithoutSpecification(BinanceExchange.class); ExchangeSpecification specification = exchange.getDefaultExchangeSpecification(); specification.setHost("localhost"); specification.setSslUri("http://localhost:" + wireMockRule.port() + "/"); diff --git a/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceExchangeTypeIntegration.java b/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceExchangeTypeIntegration.java index dae9be0ab38..eb3868c0ec0 100644 --- a/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceExchangeTypeIntegration.java +++ b/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceExchangeTypeIntegration.java @@ -34,10 +34,9 @@ public void testConnections() throws InterruptedException, IOException { private static void testConnection(Instrument instrument, ExchangeSpecification spec) throws IOException { - Exchange exchange = - ExchangeFactory.INSTANCE.createExchange(spec); + Exchange exchange = ExchangeFactory.INSTANCE.createExchange(spec); Trades trades = exchange.getMarketDataService().getTrades(instrument); - for(Trade trade : trades.getTrades()) { + for (Trade trade : trades.getTrades()) { tradeCheck(trade, instrument); } Ticker ticker = exchange.getMarketDataService().getTicker(instrument); @@ -70,8 +69,7 @@ private static ExchangeSpecification getSpec(ExchangeType exchangeType, boolean private static ExchangeSpecification getSpec1(ExchangeType exchangeType, boolean useSandbox) { ExchangeSpecification exchangeSpecification; - exchangeSpecification = - new ExchangeSpecification(BinanceExchange.class); + exchangeSpecification = new ExchangeSpecification(BinanceExchange.class); exchangeSpecification.setExchangeSpecificParametersItem(EXCHANGE_TYPE, exchangeType); if (useSandbox) { exchangeSpecification.setExchangeSpecificParametersItem(USE_SANDBOX, true); diff --git a/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceFutureTest.java b/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceFutureTest.java index 2a601b849d8..dbbb023324a 100644 --- a/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceFutureTest.java +++ b/xchange-binance/src/test/java/org/knowm/xchange/binance/BinanceFutureTest.java @@ -57,8 +57,7 @@ public void setUp() throws IOException { spec.setExchangeSpecificParametersItem(USE_SANDBOX, true); spec.setExchangeSpecificParametersItem(EXCHANGE_TYPE, FUTURES); - Exchange exchange = - ExchangeFactory.INSTANCE.createExchange(spec); + Exchange exchange = ExchangeFactory.INSTANCE.createExchange(spec); binanceExchange = exchange; } diff --git a/xchange-binance/src/test/java/org/knowm/xchange/binance/ExchangeMetaDataIntegration.java b/xchange-binance/src/test/java/org/knowm/xchange/binance/ExchangeMetaDataIntegration.java index d7dda443773..bc4a145feaa 100644 --- a/xchange-binance/src/test/java/org/knowm/xchange/binance/ExchangeMetaDataIntegration.java +++ b/xchange-binance/src/test/java/org/knowm/xchange/binance/ExchangeMetaDataIntegration.java @@ -10,22 +10,23 @@ public class ExchangeMetaDataIntegration extends BinanceExchangeIntegration { - @Test public void valid_instrumentsMetaData() { - Map instruments = exchange.getExchangeMetaData().getInstruments(); - assertThat(instruments.values()).allSatisfy(instrumentMetaData -> { - assertThat(instrumentMetaData.getPriceScale()).isNotNull(); - assertThat(instrumentMetaData.getAmountStepSize()).isNotNull(); - - assertThat(instrumentMetaData.getMinimumAmount()).isLessThan(instrumentMetaData.getMaximumAmount()); - }); + Map instruments = + exchange.getExchangeMetaData().getInstruments(); + assertThat(instruments.values()) + .allSatisfy( + instrumentMetaData -> { + assertThat(instrumentMetaData.getPriceScale()).isNotNull(); + assertThat(instrumentMetaData.getAmountStepSize()).isNotNull(); + + assertThat(instrumentMetaData.getMinimumAmount()) + .isLessThan(instrumentMetaData.getMaximumAmount()); + }); } - @Test public void valid_symbol_mapping() { assertThat(BinanceAdapters.toCurrencyPair("BTCUSDT")).isEqualTo(CurrencyPair.BTC_USDT); } - } diff --git a/xchange-binance/src/test/java/org/knowm/xchange/binance/service/account/AccountServiceIntegration.java b/xchange-binance/src/test/java/org/knowm/xchange/binance/service/account/AccountServiceIntegration.java index a60c034fe82..526f7af6b02 100644 --- a/xchange-binance/src/test/java/org/knowm/xchange/binance/service/account/AccountServiceIntegration.java +++ b/xchange-binance/src/test/java/org/knowm/xchange/binance/service/account/AccountServiceIntegration.java @@ -51,7 +51,6 @@ public void testAssetDetail() throws Exception { Assert.assertFalse(assetDetails.isEmpty()); } - @Test public void testCurrencyInfos() throws Exception { assumeProduction(); @@ -59,7 +58,6 @@ public void testCurrencyInfos() throws Exception { assertThat(currencyInfos).isNotEmpty(); } - @Test public void testMetaData() { diff --git a/xchange-binance/src/test/java/org/knowm/xchange/binance/service/marketdata/MarketDataServiceIntegration.java b/xchange-binance/src/test/java/org/knowm/xchange/binance/service/marketdata/MarketDataServiceIntegration.java index 5abc058178c..aa0233b368c 100644 --- a/xchange-binance/src/test/java/org/knowm/xchange/binance/service/marketdata/MarketDataServiceIntegration.java +++ b/xchange-binance/src/test/java/org/knowm/xchange/binance/service/marketdata/MarketDataServiceIntegration.java @@ -16,10 +16,10 @@ public class MarketDataServiceIntegration extends BinanceExchangeIntegration { @Test public void exchange_health() { - assertThat(exchange.getMarketDataService().getExchangeHealth()).isEqualTo(ExchangeHealth.ONLINE); + assertThat(exchange.getMarketDataService().getExchangeHealth()) + .isEqualTo(ExchangeHealth.ONLINE); } - @Test public void valid_timestamp() { @@ -27,24 +27,22 @@ public void valid_timestamp() { assertThat(serverTime).isPositive(); } - @Test public void valid_all_tickers() throws IOException { List tickers = exchange.getMarketDataService().getTickers(null); assertThat(tickers).isNotEmpty(); - - assertThat(tickers).allSatisfy(ticker -> { - assertThat(ticker.getInstrument()).isNotNull(); - assertThat(ticker.getLast()).isNotNull(); - if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { - assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); - } - }); - + assertThat(tickers) + .allSatisfy( + ticker -> { + assertThat(ticker.getInstrument()).isNotNull(); + assertThat(ticker.getLast()).isNotNull(); + if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { + assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); + } + }); } - @Test public void valid_ticker() throws Exception { Ticker ticker = exchange.getMarketDataService().getTicker(CurrencyPair.BTC_USDT); @@ -53,15 +51,13 @@ public void valid_ticker() throws Exception { assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); } - @Test public void valid_orderBook() throws IOException { - OrderBook orderBook = exchange.getMarketDataService().getOrderBook((Instrument) CurrencyPair.BTC_USDT); + OrderBook orderBook = + exchange.getMarketDataService().getOrderBook((Instrument) CurrencyPair.BTC_USDT); assertThat(orderBook.getAsks()).isNotEmpty(); assertThat(orderBook.getBids()).isNotEmpty(); assertThat(orderBook.getBids().get(0)).isLessThan(orderBook.getAsks().get(0)); } - - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/Bitget.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/Bitget.java index 2ccacc26ccb..a591653fb89 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/Bitget.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/Bitget.java @@ -23,28 +23,23 @@ public interface Bitget { @Path("api/v2/public/time") BitgetResponse serverTime() throws IOException, BitgetException; - @GET @Path("api/v2/spot/public/coins") - BitgetResponse> coins(@QueryParam("coin") String coin) throws IOException, BitgetException; - + BitgetResponse> coins(@QueryParam("coin") String coin) + throws IOException, BitgetException; @GET @Path("api/v2/spot/public/symbols") BitgetResponse> symbols(@QueryParam("symbol") String symbol) throws IOException, BitgetException; - @GET @Path("api/v2/spot/market/tickers") BitgetResponse> tickers(@QueryParam("symbol") String symbol) throws IOException, BitgetException; - @GET @Path("api/v2/spot/market/orderbook") BitgetResponse orderbook(@QueryParam("symbol") String symbol) throws IOException, BitgetException; - - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAdapters.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAdapters.java index 61ab482b919..a0d2fdc60b4 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAdapters.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAdapters.java @@ -37,37 +37,33 @@ public class BitgetAdapters { private final Map SYMBOL_TO_CURRENCY_PAIR = new HashMap<>(); - public CurrencyPair toCurrencyPair(String symbol) { return SYMBOL_TO_CURRENCY_PAIR.get(symbol); } - public String toString(Instrument instrument) { - return instrument == null ? null : instrument.getBase().toString() + instrument.getCounter().toString(); + return instrument == null + ? null + : instrument.getBase().toString() + instrument.getCounter().toString(); } - public String toString(Currency currency) { - return Optional.ofNullable(currency) - .map(Currency::getCurrencyCode) - .orElse(null); + return Optional.ofNullable(currency).map(Currency::getCurrencyCode).orElse(null); } - public void putSymbolMapping(String symbol, CurrencyPair currencyPair) { SYMBOL_TO_CURRENCY_PAIR.put(symbol, currencyPair); } - public InstrumentMetaData toInstrumentMetaData(BitgetSymbolDto bitgetSymbolDto) { - InstrumentMetaData.Builder builder = new InstrumentMetaData.Builder() - .tradingFee(bitgetSymbolDto.getTakerFeeRate()) - .minimumAmount(bitgetSymbolDto.getMinTradeAmount()) - .maximumAmount(bitgetSymbolDto.getMaxTradeAmount()) - .volumeScale(bitgetSymbolDto.getQuantityPrecision()) - .priceScale(bitgetSymbolDto.getPricePrecision()) - .marketOrderEnabled(bitgetSymbolDto.getStatus() == Status.ONLINE); + InstrumentMetaData.Builder builder = + new InstrumentMetaData.Builder() + .tradingFee(bitgetSymbolDto.getTakerFeeRate()) + .minimumAmount(bitgetSymbolDto.getMinTradeAmount()) + .maximumAmount(bitgetSymbolDto.getMaxTradeAmount()) + .volumeScale(bitgetSymbolDto.getQuantityPrecision()) + .priceScale(bitgetSymbolDto.getPricePrecision()) + .marketOrderEnabled(bitgetSymbolDto.getStatus() == Status.ONLINE); // set min quote amount for USDT if (bitgetSymbolDto.getCurrencyPair().getCounter().equals(Currency.USDT)) { @@ -77,7 +73,6 @@ public InstrumentMetaData toInstrumentMetaData(BitgetSymbolDto bitgetSymbolDto) return builder.build(); } - public Ticker toTicker(BitgetTickerDto bitgetTickerDto) { CurrencyPair currencyPair = toCurrencyPair(bitgetTickerDto.getSymbol()); if (currencyPair == null) { @@ -100,14 +95,10 @@ public Ticker toTicker(BitgetTickerDto bitgetTickerDto) { .build(); } - public Date toDate(Instant instant) { - return Optional.ofNullable(instant) - .map(Date::from) - .orElse(null); + return Optional.ofNullable(instant).map(Date::from).orElse(null); } - public Balance toBalance(BitgetBalanceDto balance) { return new Balance.Builder() .currency(balance.getCurrency()) @@ -117,45 +108,43 @@ public Balance toBalance(BitgetBalanceDto balance) { .build(); } - public Wallet toWallet(List bitgetBalanceDtos) { - List balances = bitgetBalanceDtos.stream() - .map(BitgetAdapters::toBalance) - .collect(Collectors.toList()); + List balances = + bitgetBalanceDtos.stream().map(BitgetAdapters::toBalance).collect(Collectors.toList()); return Wallet.Builder.from(balances).id("spot").build(); } - public OrderBook toOrderBook(BitgetMarketDepthDto bitgetMarketDepthDto, Instrument instrument) { - List asks = bitgetMarketDepthDto.getAsks().stream() - .map(priceSizeEntry -> - new LimitOrder( - OrderType.ASK, - priceSizeEntry.getSize(), - instrument, - null, - null, - priceSizeEntry.getPrice()) - ) - .collect(Collectors.toList()); - - List bids = bitgetMarketDepthDto.getBids().stream() - .map(priceSizeEntry -> - new LimitOrder( - OrderType.BID, - priceSizeEntry.getSize(), - instrument, - null, - null, - priceSizeEntry.getPrice()) - ) - .collect(Collectors.toList()); + List asks = + bitgetMarketDepthDto.getAsks().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.ASK, + priceSizeEntry.getSize(), + instrument, + null, + null, + priceSizeEntry.getPrice())) + .collect(Collectors.toList()); + + List bids = + bitgetMarketDepthDto.getBids().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.BID, + priceSizeEntry.getSize(), + instrument, + null, + null, + priceSizeEntry.getPrice())) + .collect(Collectors.toList()); return new OrderBook(toDate(bitgetMarketDepthDto.getTimestamp()), asks, bids); } - public Order toOrder(BitgetOrderInfoDto order) { if (order == null) { return null; @@ -171,8 +160,7 @@ public Order toOrder(BitgetOrderInfoDto order) { builder = new MarketOrder.Builder(orderType, instrument); break; case LIMIT: - builder = new LimitOrder.Builder(orderType, instrument) - .limitPrice(order.getPrice()); + builder = new LimitOrder.Builder(orderType, instrument).limitPrice(order.getPrice()); break; default: throw new IllegalArgumentException("Can't map " + order.getOrderType()); @@ -203,7 +191,6 @@ public Order toOrder(BitgetOrderInfoDto order) { .build(); } - public OrderStatus toOrderStatus(BitgetOrderStatus bitgetOrderStatus) { switch (bitgetOrderStatus) { case PENDING: @@ -219,7 +206,6 @@ public OrderStatus toOrderStatus(BitgetOrderStatus bitgetOrderStatus) { } } - public BitgetPlaceOrderDto toBitgetPlaceOrderDto(MarketOrder marketOrder) { return BitgetPlaceOrderDto.builder() .symbol(toString(marketOrder.getInstrument())) @@ -229,6 +215,4 @@ public BitgetPlaceOrderDto toBitgetPlaceOrderDto(MarketOrder marketOrder) { .size(marketOrder.getOriginalAmount()) .build(); } - - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAuthenticated.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAuthenticated.java index a22f8f75a10..899c566bdf6 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAuthenticated.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetAuthenticated.java @@ -31,7 +31,6 @@ BitgetResponse> balances( @HeaderParam("ACCESS-TIMESTAMP") SynchronizedValueFactory timestamp) throws IOException, BitgetException; - @GET @Path("api/v2/spot/trade/orderInfo") BitgetResponse> orderInfo( @@ -42,7 +41,6 @@ BitgetResponse> orderInfo( @QueryParam("orderId") String orderId) throws IOException, BitgetException; - @POST @Path("api/v2/spot/trade/place-order") @Consumes(MediaType.APPLICATION_JSON) @@ -53,6 +51,4 @@ BitgetResponse createOrder( @HeaderParam("ACCESS-TIMESTAMP") SynchronizedValueFactory timestamp, BitgetPlaceOrderDto bitgetPlaceOrderDto) throws IOException, BitgetException; - - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetExchange.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetExchange.java index b7f3ce80acb..0446fb285d9 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetExchange.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/BitgetExchange.java @@ -35,23 +35,24 @@ public ExchangeSpecification getDefaultExchangeSpecification() { @Override public void remoteInit() throws IOException { - BitgetMarketDataServiceRaw bitgetMarketDataServiceRaw = (BitgetMarketDataServiceRaw) marketDataService; + BitgetMarketDataServiceRaw bitgetMarketDataServiceRaw = + (BitgetMarketDataServiceRaw) marketDataService; // initialize symbol mappings List bitgetSymbolDtos = bitgetMarketDataServiceRaw.getBitgetSymbolDtos(null); - bitgetSymbolDtos.forEach(bitgetSymbolDto -> { - BitgetAdapters.putSymbolMapping(bitgetSymbolDto.getSymbol(), bitgetSymbolDto.getCurrencyPair()); - }); - + bitgetSymbolDtos.forEach( + bitgetSymbolDto -> { + BitgetAdapters.putSymbolMapping( + bitgetSymbolDto.getSymbol(), bitgetSymbolDto.getCurrencyPair()); + }); // initialize instrument metadata - Map instruments = bitgetSymbolDtos.stream() - .collect(Collectors.toMap( - BitgetSymbolDto::getCurrencyPair, - BitgetAdapters::toInstrumentMetaData) - ); + Map instruments = + bitgetSymbolDtos.stream() + .collect( + Collectors.toMap( + BitgetSymbolDto::getCurrencyPair, BitgetAdapters::toInstrumentMetaData)); exchangeMetaData = new ExchangeMetaData(instruments, null, null, null, null); - } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/config/deserializer/FeeDetailDeserializer.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/config/deserializer/FeeDetailDeserializer.java index 4628bd65e43..ed13e35df40 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/config/deserializer/FeeDetailDeserializer.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/config/deserializer/FeeDetailDeserializer.java @@ -16,4 +16,4 @@ public FeeDetail deserialize(JsonParser p, DeserializationContext ctxt) throws I return objectMapper.readValue(text, FeeDetail.class); } -} \ No newline at end of file +} diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetException.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetException.java index 34d33813bd7..18fe54a3e18 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetException.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetException.java @@ -22,5 +22,4 @@ public class BitgetException extends RuntimeException { @JsonProperty("data") Object data; - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetResponse.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetResponse.java index 82f44b7677f..21d0e6eee3e 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetResponse.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/BitgetResponse.java @@ -12,23 +12,22 @@ @Jacksonized public class BitgetResponse { - @JsonProperty("code") - private Integer code; + @JsonProperty("code") + private Integer code; - @JsonProperty("msg") - private String message; + @JsonProperty("msg") + private String message; - @JsonProperty("requestTime") - private Instant requestTime; + @JsonProperty("requestTime") + private Instant requestTime; - @JsonProperty("data") - private T data; + @JsonProperty("data") + private T data; - public void setCode(Integer code) { - if (code != 0) { - throw new ExceptionalReturnContentException(String.valueOf(code)); - } - this.code = code; + public void setCode(Integer code) { + if (code != 0) { + throw new ExceptionalReturnContentException(String.valueOf(code)); } - + this.code = code; + } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/account/BitgetBalanceDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/account/BitgetBalanceDto.java index 5e4813d3dd1..75625eac277 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/account/BitgetBalanceDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/account/BitgetBalanceDto.java @@ -15,23 +15,22 @@ @Jacksonized public class BitgetBalanceDto { - @JsonProperty("coin") - @JsonDeserialize(converter = StringToCurrencyConverter.class) - private Currency currency; + @JsonProperty("coin") + @JsonDeserialize(converter = StringToCurrencyConverter.class) + private Currency currency; - @JsonProperty("available") - private BigDecimal available; + @JsonProperty("available") + private BigDecimal available; - @JsonProperty("frozen") - private BigDecimal frozen; + @JsonProperty("frozen") + private BigDecimal frozen; - @JsonProperty("locked") - private BigDecimal locked; + @JsonProperty("locked") + private BigDecimal locked; - @JsonProperty("limitAvailable") - private BigDecimal limitAvailable; - - @JsonProperty("uTime") - private Instant timestamp; + @JsonProperty("limitAvailable") + private BigDecimal limitAvailable; + @JsonProperty("uTime") + private Instant timestamp; } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetChainDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetChainDto.java index 62139145dec..ea1dcc33c7e 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetChainDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetChainDto.java @@ -11,59 +11,56 @@ @Jacksonized public class BitgetChainDto { - @JsonProperty("chain") - private String chain; + @JsonProperty("chain") + private String chain; - @JsonProperty("needTag") - private Boolean needTag; + @JsonProperty("needTag") + private Boolean needTag; - @JsonProperty("withdrawable") - private Boolean isWithdrawEnabled; + @JsonProperty("withdrawable") + private Boolean isWithdrawEnabled; - @JsonProperty("rechargeable") - private Boolean isDepositEnabled; + @JsonProperty("rechargeable") + private Boolean isDepositEnabled; - @JsonProperty("withdrawFee") - private BigDecimal withdrawFee; + @JsonProperty("withdrawFee") + private BigDecimal withdrawFee; - @JsonProperty("extraWithdrawFee") - private BigDecimal extraWithdrawFee; + @JsonProperty("extraWithdrawFee") + private BigDecimal extraWithdrawFee; - @JsonProperty("depositConfirm") - private Integer depositConfirmBlockCount; + @JsonProperty("depositConfirm") + private Integer depositConfirmBlockCount; - @JsonProperty("withdrawConfirm") - private Integer withdrawConfirmBlockCount; + @JsonProperty("withdrawConfirm") + private Integer withdrawConfirmBlockCount; - @JsonProperty("minDepositAmount") - private BigDecimal minDepositAmount; + @JsonProperty("minDepositAmount") + private BigDecimal minDepositAmount; - @JsonProperty("minWithdrawAmount") - private BigDecimal minWithdrawAmount; + @JsonProperty("minWithdrawAmount") + private BigDecimal minWithdrawAmount; - @JsonProperty("browserUrl") - private String browserUrl; + @JsonProperty("browserUrl") + private String browserUrl; - @JsonProperty("contractAddress") - private String contractAddress; + @JsonProperty("contractAddress") + private String contractAddress; - @JsonProperty("withdrawStep") - private Integer withdrawStep; + @JsonProperty("withdrawStep") + private Integer withdrawStep; - @JsonProperty("withdrawMinScale") - private Integer withdrawMinScale; + @JsonProperty("withdrawMinScale") + private Integer withdrawMinScale; - @JsonProperty("congestion") - private Congestion congestion; + @JsonProperty("congestion") + private Congestion congestion; + public static enum Congestion { + @JsonProperty("normal") + NORMAL, - public static enum Congestion { - @JsonProperty("normal") - NORMAL, - - @JsonProperty("congested") - CONGESTED; - } - + @JsonProperty("congested") + CONGESTED; + } } - diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetCoinDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetCoinDto.java index 60217f85ae8..9601b6e41f1 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetCoinDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetCoinDto.java @@ -15,21 +15,20 @@ @Jacksonized public class BitgetCoinDto { - @JsonProperty("coinId") - private String coinId; + @JsonProperty("coinId") + private String coinId; - @JsonProperty("coin") - @JsonDeserialize(converter = StringToCurrencyConverter.class) - private Currency currency; + @JsonProperty("coin") + @JsonDeserialize(converter = StringToCurrencyConverter.class) + private Currency currency; - @JsonProperty("transfer") - private Boolean canTransfer; + @JsonProperty("transfer") + private Boolean canTransfer; - @JsonProperty("areaCoin") - @JsonDeserialize(converter = StringToBooleanConverter.class) - private Boolean isAreaCoin; - - @JsonProperty("chains") - private List chains; + @JsonProperty("areaCoin") + @JsonDeserialize(converter = StringToBooleanConverter.class) + private Boolean isAreaCoin; + @JsonProperty("chains") + private List chains; } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetMarketDepthDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetMarketDepthDto.java index 17746d1e792..733861d1cdd 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetMarketDepthDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetMarketDepthDto.java @@ -23,7 +23,6 @@ public class BitgetMarketDepthDto { @JsonProperty("ts") Instant timestamp; - @Data @Builder @Jacksonized diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetServerTime.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetServerTime.java index 6af71802610..bd21a6f1389 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetServerTime.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetServerTime.java @@ -13,5 +13,4 @@ public class BitgetServerTime { @JsonProperty("serverTime") private Instant serverTime; - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetSymbolDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetSymbolDto.java index da353d48c2a..05179ccfcb5 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetSymbolDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetSymbolDto.java @@ -16,71 +16,69 @@ @Jacksonized public class BitgetSymbolDto { - @JsonProperty("symbol") - private String symbol; + @JsonProperty("symbol") + private String symbol; - @JsonProperty("baseCoin") - @JsonDeserialize(converter = StringToCurrencyConverter.class) - private Currency base; + @JsonProperty("baseCoin") + @JsonDeserialize(converter = StringToCurrencyConverter.class) + private Currency base; - @JsonProperty("quoteCoin") - @JsonDeserialize(converter = StringToCurrencyConverter.class) - private Currency quote; + @JsonProperty("quoteCoin") + @JsonDeserialize(converter = StringToCurrencyConverter.class) + private Currency quote; - @JsonProperty("minTradeAmount") - private BigDecimal minTradeAmount; + @JsonProperty("minTradeAmount") + private BigDecimal minTradeAmount; - @JsonProperty("maxTradeAmount") - private BigDecimal maxTradeAmount; + @JsonProperty("maxTradeAmount") + private BigDecimal maxTradeAmount; - @JsonProperty("takerFeeRate") - private BigDecimal takerFeeRate; + @JsonProperty("takerFeeRate") + private BigDecimal takerFeeRate; - @JsonProperty("makerFeeRate") - private BigDecimal makerFeeRate; + @JsonProperty("makerFeeRate") + private BigDecimal makerFeeRate; - @JsonProperty("pricePrecision") - private Integer pricePrecision; + @JsonProperty("pricePrecision") + private Integer pricePrecision; - @JsonProperty("quantityPrecision") - private Integer quantityPrecision; + @JsonProperty("quantityPrecision") + private Integer quantityPrecision; - @JsonProperty("quotePrecision") - private Integer quotePrecision; + @JsonProperty("quotePrecision") + private Integer quotePrecision; - @JsonProperty("status") - private Status status; + @JsonProperty("status") + private Status status; - @JsonProperty("minTradeUSDT") - private BigDecimal minTradeUSDT; + @JsonProperty("minTradeUSDT") + private BigDecimal minTradeUSDT; - @JsonProperty("buyLimitPriceRatio") - private BigDecimal buyLimitPriceRatio; + @JsonProperty("buyLimitPriceRatio") + private BigDecimal buyLimitPriceRatio; - @JsonProperty("sellLimitPriceRatio") - private BigDecimal sellLimitPriceRatio; + @JsonProperty("sellLimitPriceRatio") + private BigDecimal sellLimitPriceRatio; - @JsonProperty("areaSymbol") - @JsonDeserialize(converter = StringToBooleanConverter.class) - private Boolean isAreaSymbol; + @JsonProperty("areaSymbol") + @JsonDeserialize(converter = StringToBooleanConverter.class) + private Boolean isAreaSymbol; + public CurrencyPair getCurrencyPair() { + return new CurrencyPair(base, quote); + } - public CurrencyPair getCurrencyPair() { - return new CurrencyPair(base, quote); - } + public static enum Status { + @JsonProperty("offline") + OFFLINE, + @JsonProperty("gray") + GRAY, - public static enum Status { - @JsonProperty("offline") - OFFLINE, + @JsonProperty("online") + ONLINE, - @JsonProperty("gray") - GRAY, - - @JsonProperty("online") - ONLINE, - - @JsonProperty("halt") - HALT - } + @JsonProperty("halt") + HALT + } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetTickerDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetTickerDto.java index 2fd05042b35..6e1c354da23 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetTickerDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/marketdata/BitgetTickerDto.java @@ -12,52 +12,51 @@ @Jacksonized public class BitgetTickerDto { - @JsonProperty("symbol") - private String symbol; + @JsonProperty("symbol") + private String symbol; - @JsonProperty("high24h") - private BigDecimal high24h; + @JsonProperty("high24h") + private BigDecimal high24h; - @JsonProperty("open") - private BigDecimal open24h; + @JsonProperty("open") + private BigDecimal open24h; - @JsonProperty("lastPr") - private BigDecimal lastPrice; + @JsonProperty("lastPr") + private BigDecimal lastPrice; - @JsonProperty("low24h") - private BigDecimal low24h; + @JsonProperty("low24h") + private BigDecimal low24h; - @JsonProperty("quoteVolume") - private BigDecimal quoteVolume24h; + @JsonProperty("quoteVolume") + private BigDecimal quoteVolume24h; - @JsonProperty("baseVolume") - private BigDecimal assetVolume24h; + @JsonProperty("baseVolume") + private BigDecimal assetVolume24h; - @JsonProperty("usdtVolume") - private BigDecimal usdtVolume24h; + @JsonProperty("usdtVolume") + private BigDecimal usdtVolume24h; - @JsonProperty("bidPr") - private BigDecimal bestBidPrice; + @JsonProperty("bidPr") + private BigDecimal bestBidPrice; - @JsonProperty("bidSz") - private BigDecimal bestBidSize; + @JsonProperty("bidSz") + private BigDecimal bestBidSize; - @JsonProperty("askPr") - private BigDecimal bestAskPrice; + @JsonProperty("askPr") + private BigDecimal bestAskPrice; - @JsonProperty("askSz") - private BigDecimal bestAskSize; + @JsonProperty("askSz") + private BigDecimal bestAskSize; - @JsonProperty("openUtc") - private BigDecimal openUtc; + @JsonProperty("openUtc") + private BigDecimal openUtc; - @JsonProperty("ts") - private Instant timestamp; + @JsonProperty("ts") + private Instant timestamp; - @JsonProperty("changeUtc24h") - private BigDecimal changeUtc24h; - - @JsonProperty("change24h") - private BigDecimal change24h; + @JsonProperty("changeUtc24h") + private BigDecimal changeUtc24h; + @JsonProperty("change24h") + private BigDecimal change24h; } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetOrderInfoDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetOrderInfoDto.java index 3a6c9e2dc9f..26869c7dc78 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetOrderInfoDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetOrderInfoDto.java @@ -17,131 +17,122 @@ @Jacksonized public class BitgetOrderInfoDto { - @JsonProperty("userId") - private String acccountId; + @JsonProperty("userId") + private String acccountId; - @JsonProperty("symbol") - private String symbol; + @JsonProperty("symbol") + private String symbol; - @JsonProperty("orderId") - private String orderId; + @JsonProperty("orderId") + private String orderId; - @JsonProperty("clientOid") - private String clientOid; + @JsonProperty("clientOid") + private String clientOid; - @JsonProperty("price") - private BigDecimal price; + @JsonProperty("price") + private BigDecimal price; - @JsonProperty("size") - private BigDecimal size; + @JsonProperty("size") + private BigDecimal size; - @JsonProperty("orderType") - private OrderType orderType; + @JsonProperty("orderType") + private OrderType orderType; - @JsonProperty("side") - @JsonDeserialize(converter = StringToOrderTypeConverter.class) - private Order.OrderType orderSide; + @JsonProperty("side") + @JsonDeserialize(converter = StringToOrderTypeConverter.class) + private Order.OrderType orderSide; - @JsonProperty("status") - private BitgetOrderStatus orderStatus; + @JsonProperty("status") + private BitgetOrderStatus orderStatus; - @JsonProperty("priceAvg") - private BigDecimal priceAvg; + @JsonProperty("priceAvg") + private BigDecimal priceAvg; - @JsonProperty("baseVolume") - private BigDecimal baseVolume; + @JsonProperty("baseVolume") + private BigDecimal baseVolume; - @JsonProperty("quoteVolume") - private BigDecimal quoteVolume; + @JsonProperty("quoteVolume") + private BigDecimal quoteVolume; - @JsonProperty("enterPointSource") - private String enterPointSource; + @JsonProperty("enterPointSource") + private String enterPointSource; - @JsonProperty("cTime") - private Instant createdAt; + @JsonProperty("cTime") + private Instant createdAt; - @JsonProperty("uTime") - private Instant updatedAt; + @JsonProperty("uTime") + private Instant updatedAt; - @JsonProperty("orderSource") - private OrderSource orderSource; + @JsonProperty("orderSource") + private OrderSource orderSource; - @JsonProperty("feeDetail") - @JsonDeserialize(using = FeeDetailDeserializer.class) - private FeeDetail feeDetail; + @JsonProperty("feeDetail") + @JsonDeserialize(using = FeeDetailDeserializer.class) + private FeeDetail feeDetail; + public BigDecimal getFee() { + return Optional.ofNullable(feeDetail) + .map(FeeDetail::getNewFees) + .map(NewFees::getTotalFee) + .map(BigDecimal::abs) + .orElse(null); + } - public BigDecimal getFee() { - return Optional.ofNullable(feeDetail) - .map(FeeDetail::getNewFees) - .map(NewFees::getTotalFee) - .map(BigDecimal::abs) - .orElse(null); - } + public static enum OrderType { + @JsonProperty("limit") + LIMIT, + @JsonProperty("market") + MARKET + } - public static enum OrderType { - @JsonProperty("limit") - LIMIT, + public static enum BitgetOrderStatus { + @JsonProperty("live") + PENDING, - @JsonProperty("market") - MARKET - } + @JsonProperty("partially_filled") + PARTIALLY_FILLED, + @JsonProperty("filled") + FILLED, - public static enum BitgetOrderStatus { - @JsonProperty("live") - PENDING, + @JsonProperty("cancelled") + CANCELLED + } - @JsonProperty("partially_filled") - PARTIALLY_FILLED, + public static enum OrderSource { + @JsonProperty("normal") + NORMAL, - @JsonProperty("filled") - FILLED, + @JsonProperty("market") + MARKET, - @JsonProperty("cancelled") - CANCELLED + @JsonProperty("spot_trader_buy") + SPOT_TRADER_BUY, - } + @JsonProperty("spot_follower_buy") + SPOT_FOLLOWER_BUY, + @JsonProperty("spot_trader_sell") + SPOT_TRADER_SELL, - public static enum OrderSource { - @JsonProperty("normal") - NORMAL, + @JsonProperty("spot_follower_sell") + SPOT_FOLLOWER_SELL + } - @JsonProperty("market") - MARKET, - - @JsonProperty("spot_trader_buy") - SPOT_TRADER_BUY, - - @JsonProperty("spot_follower_buy") - SPOT_FOLLOWER_BUY, - - @JsonProperty("spot_trader_sell") - SPOT_TRADER_SELL, - - @JsonProperty("spot_follower_sell") - SPOT_FOLLOWER_SELL - - } - - - @Data - @Builder - @Jacksonized - public static class NewFees { - @JsonProperty("t") - private BigDecimal totalFee; - } - - - @Data - @Builder - @Jacksonized - public static class FeeDetail { - @JsonProperty("newFees") - private NewFees newFees; - } + @Data + @Builder + @Jacksonized + public static class NewFees { + @JsonProperty("t") + private BigDecimal totalFee; + } + @Data + @Builder + @Jacksonized + public static class FeeDetail { + @JsonProperty("newFees") + private NewFees newFees; + } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetPlaceOrderDto.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetPlaceOrderDto.java index b66048be66d..82c140753ed 100755 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetPlaceOrderDto.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/dto/trade/BitgetPlaceOrderDto.java @@ -18,94 +18,89 @@ @Jacksonized public class BitgetPlaceOrderDto { - @JsonProperty("symbol") - private String symbol; + @JsonProperty("symbol") + private String symbol; - @JsonProperty("side") - @JsonDeserialize(converter = StringToOrderTypeConverter.class) - @JsonSerialize(converter = OrderTypeToStringConverter.class) - private Order.OrderType orderSide; + @JsonProperty("side") + @JsonDeserialize(converter = StringToOrderTypeConverter.class) + @JsonSerialize(converter = OrderTypeToStringConverter.class) + private Order.OrderType orderSide; - @JsonProperty("orderType") - private OrderType orderType; + @JsonProperty("orderType") + private OrderType orderType; - @JsonProperty("force") - private TimeInForce timeInForce; + @JsonProperty("force") + private TimeInForce timeInForce; - @JsonProperty("price") - private BigDecimal price; + @JsonProperty("price") + private BigDecimal price; - @JsonProperty("size") - private BigDecimal size; + @JsonProperty("size") + private BigDecimal size; - @JsonProperty("clientOid") - private String clientOid; + @JsonProperty("clientOid") + private String clientOid; - @JsonProperty("triggerPrice") - private BigDecimal triggerPrice; + @JsonProperty("triggerPrice") + private BigDecimal triggerPrice; - @JsonProperty("tpslType") - private TpSlType tpSlType; + @JsonProperty("tpslType") + private TpSlType tpSlType; - @JsonProperty("requestTime") - private Instant requestTime; + @JsonProperty("requestTime") + private Instant requestTime; - @JsonProperty("receiveWindow") - private Instant receiveWindow; + @JsonProperty("receiveWindow") + private Instant receiveWindow; - @JsonProperty("stpMode") - private StpMode stpMode; + @JsonProperty("stpMode") + private StpMode stpMode; - @JsonProperty("presetTakeProfitPrice") - private BigDecimal presetTakeProfitPrice; + @JsonProperty("presetTakeProfitPrice") + private BigDecimal presetTakeProfitPrice; - @JsonProperty("executeTakeProfitPrice") - private BigDecimal executeTakeProfitPrice; + @JsonProperty("executeTakeProfitPrice") + private BigDecimal executeTakeProfitPrice; - @JsonProperty("presetStopLossPrice") - private BigDecimal presetStopLossPrice; + @JsonProperty("presetStopLossPrice") + private BigDecimal presetStopLossPrice; - @JsonProperty("executeStopLossPrice") - private BigDecimal executeStopLossPrice; + @JsonProperty("executeStopLossPrice") + private BigDecimal executeStopLossPrice; + public enum TimeInForce { + @JsonProperty("gtc") + GOOD_TIL_CANCELLED, - public enum TimeInForce { - @JsonProperty("gtc") - GOOD_TIL_CANCELLED, + @JsonProperty("post_only") + POST_ONLY, - @JsonProperty("post_only") - POST_ONLY, + @JsonProperty("fok") + FILL_OR_KILL, - @JsonProperty("fok") - FILL_OR_KILL, + @JsonProperty("ioc") + IMMEDIATE_OR_CANCEL + } - @JsonProperty("ioc") - IMMEDIATE_OR_CANCEL - } + public enum TpSlType { + @JsonProperty("normal") + NORMAL, + @JsonProperty("tpsl") + SPOT_TP_SL + } - public enum TpSlType { - @JsonProperty("normal") - NORMAL, + public enum StpMode { + @JsonProperty("none") + NONE, - @JsonProperty("tpsl") - SPOT_TP_SL - } - - - public enum StpMode { - @JsonProperty("none") - NONE, - - @JsonProperty("cancel_taker") - CANCEL_TAKER, - - @JsonProperty("cancel_maker") - CANCEL_MAKER, - - @JsonProperty("cancel_both") - CANCEL_BOTH - } + @JsonProperty("cancel_taker") + CANCEL_TAKER, + @JsonProperty("cancel_maker") + CANCEL_MAKER, + @JsonProperty("cancel_both") + CANCEL_BOTH + } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountService.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountService.java index d8222013fd7..70b3f2113e0 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountService.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountService.java @@ -17,7 +17,6 @@ public BitgetAccountService(BitgetExchange exchange) { super(exchange); } - @Override public AccountInfo getAccountInfo() throws IOException { try { @@ -29,5 +28,4 @@ public AccountInfo getAccountInfo() throws IOException { throw BitgetErrorAdapter.adapt(e); } } - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountServiceRaw.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountServiceRaw.java index 4ffc0195feb..3423c6dc4a8 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountServiceRaw.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetAccountServiceRaw.java @@ -11,8 +11,9 @@ public BitgetAccountServiceRaw(BitgetExchange exchange) { super(exchange); } - public List getBitgetBalances() throws IOException { - return bitgetAuthenticated.balances(apiKey, bitgetDigest, passphrase, exchange.getNonceFactory()).getData(); + return bitgetAuthenticated + .balances(apiKey, bitgetDigest, passphrase, exchange.getNonceFactory()) + .getData(); } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetBaseService.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetBaseService.java index 5d1f6bace4c..ad4d40f44a5 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetBaseService.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetBaseService.java @@ -18,18 +18,24 @@ public class BitgetBaseService extends BaseExchangeService imple public BitgetBaseService(BitgetExchange exchange) { super(exchange); - bitget = ExchangeRestProxyBuilder - .forInterface(Bitget.class, exchange.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.setJacksonObjectMapperFactory(new BitgetJacksonObjectMapperFactory())) - .build(); - bitgetAuthenticated = ExchangeRestProxyBuilder - .forInterface(BitgetAuthenticated.class, exchange.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.setJacksonObjectMapperFactory(new BitgetJacksonObjectMapperFactory())) - .build(); + bitget = + ExchangeRestProxyBuilder.forInterface(Bitget.class, exchange.getExchangeSpecification()) + .clientConfigCustomizer( + clientConfig -> + clientConfig.setJacksonObjectMapperFactory( + new BitgetJacksonObjectMapperFactory())) + .build(); + bitgetAuthenticated = + ExchangeRestProxyBuilder.forInterface( + BitgetAuthenticated.class, exchange.getExchangeSpecification()) + .clientConfigCustomizer( + clientConfig -> + clientConfig.setJacksonObjectMapperFactory( + new BitgetJacksonObjectMapperFactory())) + .build(); apiKey = exchange.getExchangeSpecification().getApiKey(); passphrase = exchange.getExchangeSpecification().getPassword(); bitgetDigest = BitgetDigest.createInstance(exchange.getExchangeSpecification().getSecretKey()); - } } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetDigest.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetDigest.java index 3d2a4ca24e0..1f2e9f1c29a 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetDigest.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetDigest.java @@ -15,12 +15,10 @@ private BitgetDigest(String secretKeyBase64) { super(secretKeyBase64, HMAC_SHA_256); } - public static BitgetDigest createInstance(String secretKeyBase64) { return secretKeyBase64 == null ? null : new BitgetDigest(secretKeyBase64); } - @SneakyThrows @Override public String digestParams(RestInvocation restInvocation) { diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataService.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataService.java index f02332cdf95..e610a4e6c49 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataService.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataService.java @@ -20,8 +20,8 @@ import org.knowm.xchange.service.marketdata.MarketDataService; import org.knowm.xchange.service.marketdata.params.Params; -public class BitgetMarketDataService extends BitgetMarketDataServiceRaw implements - MarketDataService { +public class BitgetMarketDataService extends BitgetMarketDataServiceRaw + implements MarketDataService { public BitgetMarketDataService(BitgetExchange exchange) { super(exchange); @@ -44,13 +44,11 @@ public ExchangeHealth getExchangeHealth() { return ExchangeHealth.OFFLINE; } - @Override public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { return getTicker((Instrument) currencyPair, args); } - @Override public Ticker getTicker(Instrument instrument, Object... args) throws IOException { try { @@ -62,7 +60,6 @@ public Ticker getTicker(Instrument instrument, Object... args) throws IOExceptio } } - @Override public List getTickers(Params params) throws IOException { try { @@ -76,13 +73,11 @@ public List getTickers(Params params) throws IOException { } } - @Override public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { return getOrderBook((Instrument) currencyPair, args); } - @Override public OrderBook getOrderBook(Instrument instrument, Object... args) throws IOException { Objects.requireNonNull(instrument); diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRaw.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRaw.java index ee8882c9410..f0c254bd122 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRaw.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRaw.java @@ -14,35 +14,27 @@ public class BitgetMarketDataServiceRaw extends BitgetBaseService { - public BitgetMarketDataServiceRaw(BitgetExchange exchange) { super(exchange); } - public BitgetServerTime getBitgetServerTime() throws IOException { return bitget.serverTime().getData(); } - public List getBitgetCoinDtoList(Currency currency) throws IOException { return bitget.coins(BitgetAdapters.toString(currency)).getData(); } - public List getBitgetSymbolDtos(Instrument instrument) throws IOException { return bitget.symbols(BitgetAdapters.toString(instrument)).getData(); } - public List getBitgetTickerDtos(Instrument instrument) throws IOException { return bitget.tickers(BitgetAdapters.toString(instrument)).getData(); } - public BitgetMarketDepthDto getBitgetMarketDepthDtos(Instrument instrument) throws IOException { return bitget.orderbook(BitgetAdapters.toString(instrument)).getData(); } - - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeService.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeService.java index 73a52bf5493..2c1cffd754d 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeService.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeService.java @@ -21,7 +21,6 @@ public BitgetTradeService(BitgetExchange exchange) { super(exchange); } - @Override public Collection getOrder(OrderQueryParams... orderQueryParams) throws IOException { Validate.validState(orderQueryParams.length == 1); @@ -31,23 +30,17 @@ public Collection getOrder(OrderQueryParams... orderQueryParams) throws I try { BitgetOrderInfoDto orderStatus = bitgetOrderInfoDto(params.getOrderId()); return Collections.singletonList(BitgetAdapters.toOrder(orderStatus)); - } - catch (BitgetException e) { + } catch (BitgetException e) { throw BitgetErrorAdapter.adapt(e); } - } - @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { try { return createOrder(BitgetAdapters.toBitgetPlaceOrderDto(marketOrder)).getOrderId(); - } - catch (BitgetException e) { + } catch (BitgetException e) { throw BitgetErrorAdapter.adapt(e); } } - - } diff --git a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeServiceRaw.java b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeServiceRaw.java index 870d26c6494..31468840a76 100644 --- a/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeServiceRaw.java +++ b/xchange-bitget/src/main/java/org/knowm/xchange/bitget/service/BitgetTradeServiceRaw.java @@ -12,19 +12,22 @@ public BitgetTradeServiceRaw(BitgetExchange exchange) { super(exchange); } - public BitgetOrderInfoDto bitgetOrderInfoDto(String orderId) throws IOException { - List results = bitgetAuthenticated.orderInfo( - apiKey, bitgetDigest, passphrase, exchange.getNonceFactory(), orderId).getData(); + List results = + bitgetAuthenticated + .orderInfo(apiKey, bitgetDigest, passphrase, exchange.getNonceFactory(), orderId) + .getData(); if (results.size() != 1) { return null; } return results.get(0); } - - public BitgetOrderInfoDto createOrder(BitgetPlaceOrderDto bitgetPlaceOrderDto) throws IOException { - return bitgetAuthenticated.createOrder(apiKey, bitgetDigest, passphrase, exchange.getNonceFactory(), bitgetPlaceOrderDto).getData(); + public BitgetOrderInfoDto createOrder(BitgetPlaceOrderDto bitgetPlaceOrderDto) + throws IOException { + return bitgetAuthenticated + .createOrder( + apiKey, bitgetDigest, passphrase, exchange.getNonceFactory(), bitgetPlaceOrderDto) + .getData(); } - } diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeIntegration.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeIntegration.java index e22fc7207cf..1b1b5ab5815 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeIntegration.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeIntegration.java @@ -13,9 +13,8 @@ class BitgetExchangeIntegration extends BitgetIntegrationTestParent { @Test void valid_metadata() { assertThat(exchange.getExchangeMetaData()).isNotNull(); - Map instruments = exchange.getExchangeMetaData().getInstruments(); + Map instruments = + exchange.getExchangeMetaData().getInstruments(); assertThat(instruments).containsKey(CurrencyPair.BTC_USDT); } - - -} \ No newline at end of file +} diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeWiremock.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeWiremock.java index 446f4e6a930..418acc55f14 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeWiremock.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetExchangeWiremock.java @@ -14,7 +14,7 @@ public abstract class BitgetExchangeWiremock { protected static BitgetExchange exchange; -// private static final boolean IS_RECORDING = true; + // private static final boolean IS_RECORDING = true; private static final boolean IS_RECORDING = false; private static WireMockServer wireMockServer; diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetIntegrationTestParent.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetIntegrationTestParent.java index 52bee0a28a6..17797877dac 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetIntegrationTestParent.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/BitgetIntegrationTestParent.java @@ -19,8 +19,7 @@ static void init() { @BeforeEach void exchange_online() { // skip if offline - assumeThat(exchange.getMarketDataService().getExchangeHealth()).isEqualTo(ExchangeHealth.ONLINE); + assumeThat(exchange.getMarketDataService().getExchangeHealth()) + .isEqualTo(ExchangeHealth.ONLINE); } - - } diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetAccountServiceIntegration.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetAccountServiceIntegration.java index 637d669ef90..fdaffd13585 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetAccountServiceIntegration.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetAccountServiceIntegration.java @@ -15,7 +15,6 @@ class BitgetAccountServiceIntegration { static BitgetExchange exchange; - @BeforeAll public static void credentialsPresent() { // skip if there are no credentials @@ -33,12 +32,9 @@ public static void credentialsPresent() { exchange = (BitgetExchange) ExchangeFactory.INSTANCE.createExchange(exSpec); } - @Test void valid_balances() throws IOException { AccountInfo accountInfo = exchange.getAccountService().getAccountInfo(); assertThat(accountInfo.getWallet("spot").getBalances()).isNotEmpty(); } - - -} \ No newline at end of file +} diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetDigestTest.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetDigestTest.java index 75fbd049f44..5f19528e09a 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetDigestTest.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetDigestTest.java @@ -14,9 +14,7 @@ @ExtendWith(MockitoExtension.class) class BitgetDigestTest { - @Mock - RestInvocation restInvocation; - + @Mock RestInvocation restInvocation; @Test void signature_no_query_params() { @@ -35,6 +33,4 @@ void signature_no_query_params() { assertThat(actual).isEqualTo(expected); } - - -} \ No newline at end of file +} diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceIntegration.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceIntegration.java index 0a0d09f0bf8..e3269f87c3e 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceIntegration.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceIntegration.java @@ -25,35 +25,35 @@ void valid_single_ticker() throws IOException { if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); } - } - @Test void check_exceptions() { assertThatExceptionOfType(InstrumentNotValidException.class) - .isThrownBy(() -> - exchange.getMarketDataService().getTicker(new CurrencyPair("NONEXISTING/NONEXISTING"))); - + .isThrownBy( + () -> + exchange + .getMarketDataService() + .getTicker(new CurrencyPair("NONEXISTING/NONEXISTING"))); } - @Test void valid_tickers() throws IOException { List tickers = exchange.getMarketDataService().getTickers(null); assertThat(tickers).isNotEmpty(); - assertThat(tickers).allSatisfy(ticker -> { - assertThat(ticker.getInstrument()).isNotNull(); - assertThat(ticker.getLast()).isNotNull(); + assertThat(tickers) + .allSatisfy( + ticker -> { + assertThat(ticker.getInstrument()).isNotNull(); + assertThat(ticker.getLast()).isNotNull(); - if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { - assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); - } - }); + if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { + assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); + } + }); } - @Test void valid_orderbook() throws IOException { OrderBook orderBook = exchange.getMarketDataService().getOrderBook(CurrencyPair.BTC_USDT); @@ -61,18 +61,21 @@ void valid_orderbook() throws IOException { assertThat(orderBook.getBids()).isNotEmpty(); assertThat(orderBook.getAsks()).isNotEmpty(); - assertThat(orderBook.getAsks().get(0).getLimitPrice()).isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); - - assertThat(orderBook.getBids()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); - }); - - assertThat(orderBook.getAsks()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); - }); + assertThat(orderBook.getAsks().get(0).getLimitPrice()) + .isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); + + assertThat(orderBook.getBids()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); + }); + + assertThat(orderBook.getAsks()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); + }); } - - -} \ No newline at end of file +} diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRawIntegration.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRawIntegration.java index ee24c10a9be..eda4e940481 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRawIntegration.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetMarketDataServiceRawIntegration.java @@ -13,7 +13,8 @@ class BitgetMarketDataServiceRawIntegration extends BitgetIntegrationTestParent { - BitgetMarketDataServiceRaw bitgetMarketDataServiceRaw = (BitgetMarketDataServiceRaw) exchange.getMarketDataService(); + BitgetMarketDataServiceRaw bitgetMarketDataServiceRaw = + (BitgetMarketDataServiceRaw) exchange.getMarketDataService(); @Test void valid_coins() throws IOException { @@ -22,19 +23,21 @@ void valid_coins() throws IOException { assertThat(coins).isNotEmpty(); // validate coins - assertThat(coins).allSatisfy(coin -> { - assertThat(coin.getCoinId()).isNotNull(); - assertThat(coin.getCurrency()).isNotNull(); - - // validate each chain - assertThat(coin.getChains()).allSatisfy(chain -> { - assertThat(chain.getChain()).isNotNull(); - }); - - }); + assertThat(coins) + .allSatisfy( + coin -> { + assertThat(coin.getCoinId()).isNotNull(); + assertThat(coin.getCurrency()).isNotNull(); + + // validate each chain + assertThat(coin.getChains()) + .allSatisfy( + chain -> { + assertThat(chain.getChain()).isNotNull(); + }); + }); } - @Test void valid_coin() throws IOException { List coins = bitgetMarketDataServiceRaw.getBitgetCoinDtoList(Currency.USDT); @@ -43,13 +46,13 @@ void valid_coin() throws IOException { assertThat(coins.get(0).getCurrency()).isEqualTo(Currency.USDT); assertThat(coins.get(0).getCoinId()).isNotNull(); - assertThat(coins.get(0).getChains()).allSatisfy(chain -> { - assertThat(chain.getChain()).isNotNull(); - }); - + assertThat(coins.get(0).getChains()) + .allSatisfy( + chain -> { + assertThat(chain.getChain()).isNotNull(); + }); } - @Test void valid_symbol() throws IOException { List symbols = bitgetMarketDataServiceRaw.getBitgetSymbolDtos(BTC_USDT); @@ -61,10 +64,8 @@ void valid_symbol() throws IOException { assertThat(symbol.getPricePrecision()).isPositive(); assertThat(symbol.getQuantityPrecision()).isPositive(); assertThat(symbol.getQuotePrecision()).isPositive(); - } - @Test void valid_symbols() throws IOException { List symbols = bitgetMarketDataServiceRaw.getBitgetSymbolDtos(null); @@ -72,14 +73,12 @@ void valid_symbols() throws IOException { assertThat(symbols).isNotEmpty(); // validate symbols - assertThat(symbols).allSatisfy(symbol -> { - assertThat(symbol.getCurrencyPair()).isNotNull(); - assertThat(symbol.getBase()).isNotNull(); - assertThat(symbol.getQuote()).isNotNull(); - - }); - + assertThat(symbols) + .allSatisfy( + symbol -> { + assertThat(symbol.getCurrencyPair()).isNotNull(); + assertThat(symbol.getBase()).isNotNull(); + assertThat(symbol.getQuote()).isNotNull(); + }); } - - -} \ No newline at end of file +} diff --git a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetTradeServiceTest.java b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetTradeServiceTest.java index 50356073bd0..b4156ffe46d 100644 --- a/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetTradeServiceTest.java +++ b/xchange-bitget/src/test/java/org/knowm/xchange/bitget/service/BitgetTradeServiceTest.java @@ -21,7 +21,6 @@ class BitgetTradeServiceTest extends BitgetExchangeWiremock { TradeService tradeService = exchange.getTradeService(); - @Test void sell_order_details() throws IOException { MarketOrder expected = @@ -38,12 +37,13 @@ void sell_order_details() throws IOException { Collection orders = tradeService.getOrder("1214193970718347264"); assertThat(orders).hasSize(1); - assertThat(orders).first() + assertThat(orders) + .first() .usingComparatorForType(BigDecimal::compareTo, BigDecimal.class) - .usingRecursiveComparison().isEqualTo(expected); + .usingRecursiveComparison() + .isEqualTo(expected); } - @Test void buy_order_details() throws IOException { MarketOrder expected = @@ -58,14 +58,16 @@ void buy_order_details() throws IOException { .fee(new BigDecimal("0.0020706")) .build(); - Collection orders = tradeService.getOrder(new DefaultQueryOrderParamInstrument(null, "1214189703404097539")); + Collection orders = + tradeService.getOrder(new DefaultQueryOrderParamInstrument(null, "1214189703404097539")); assertThat(orders).hasSize(1); - assertThat(orders).first() + assertThat(orders) + .first() .usingComparatorForType(BigDecimal::compareTo, BigDecimal.class) - .usingRecursiveComparison().isEqualTo(expected); + .usingRecursiveComparison() + .isEqualTo(expected); } - @Test void place_market_buy_order() throws IOException { MarketOrder marketOrder = @@ -78,7 +80,6 @@ void place_market_buy_order() throws IOException { assertThat(actualResponse).isEqualTo("1214189703404097539"); } - @Test void place_market_sell_order() throws IOException { MarketOrder marketOrder = @@ -90,6 +91,4 @@ void place_market_sell_order() throws IOException { String actualResponse = exchange.getTradeService().placeMarketOrder(marketOrder); assertThat(actualResponse).isEqualTo("1214193970718347264"); } - - -} \ No newline at end of file +} diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAuthenticatedV2.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAuthenticatedV2.java index 2a065718308..aa3ce8c1c6f 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAuthenticatedV2.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAuthenticatedV2.java @@ -1238,4 +1238,4 @@ enum BankCurrency { ZMW, ZWL } -} \ No newline at end of file +} diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampExchange.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampExchange.java index 81a666b66ef..0e6e5c47bb0 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampExchange.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampExchange.java @@ -69,7 +69,6 @@ public void remoteInit() throws IOException, ExchangeException { BitstampMarketDataServiceRaw dataService = (BitstampMarketDataServiceRaw) this.marketDataService; List bitstampPairInfos = dataService.getTradingPairsInfo(); - exchangeMetaData = - BitstampAdapters.adaptMetaData(bitstampPairInfos, exchangeMetaData); + exchangeMetaData = BitstampAdapters.adaptMetaData(bitstampPairInfos, exchangeMetaData); } } diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalRequest.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalRequest.java index c64db930cfb..ab6647614b3 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalRequest.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalRequest.java @@ -28,6 +28,7 @@ public class WithdrawalRequest { @JsonProperty("transaction_id") private String transactionId; // Transaction id (bitcoin withdrawals only). + private String txid; public WithdrawalRequest(@JsonProperty("datetime") String datetime) { diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/trade/BitstampOrderFlags.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/trade/BitstampOrderFlags.java index 2df4bedf17c..eab5aef224e 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/trade/BitstampOrderFlags.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/dto/trade/BitstampOrderFlags.java @@ -4,15 +4,12 @@ public enum BitstampOrderFlags implements IOrderFlags { /** - * This type of market order allows setting the amount in either counter or base currency, - * (the opposite of the usual market order) - * For buys, the amount is in the counter currency. - * For sells, the amount is in the base currency. + * This type of market order allows setting the amount in either counter or base currency, (the + * opposite of the usual market order) For buys, the amount is in the counter currency. For sells, + * the amount is in the base currency. */ INSTANT_MARKET, - /** - * Set amount in counter currency (only supported for sell orders). - */ + /** Set amount in counter currency (only supported for sell orders). */ INSTANT_AMOUNT_IN_COUNTER } diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampAccountServiceRaw.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampAccountServiceRaw.java index 1d70f13f078..f2da056628f 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampAccountServiceRaw.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampAccountServiceRaw.java @@ -1,7 +1,6 @@ package org.knowm.xchange.bitstamp.service; import java.io.IOException; -import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; @@ -27,7 +26,6 @@ import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.FundsExceededException; -import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; /** @@ -114,21 +112,24 @@ public BitstampWithdrawal withdrawBitstampFunds( } else if (currency.equals(Currency.XLM)) { response = withdrawXLM(amount, address, tag); } else { - response = checkAndReturnWithdrawal(bitstampAuthenticatedV2.withdrawCrypto(apiKeyForV2Requests, - signatureCreatorV2, - uuidNonceFactory, - timestampFactory, - API_VERSION, - currency.getCurrencyCode().toLowerCase(), - address, - amount, - null, - null, - null, - null, - null, - null, - null)); + response = + checkAndReturnWithdrawal( + bitstampAuthenticatedV2.withdrawCrypto( + apiKeyForV2Requests, + signatureCreatorV2, + uuidNonceFactory, + timestampFactory, + API_VERSION, + currency.getCurrencyCode().toLowerCase(), + address, + amount, + null, + null, + null, + null, + null, + null, + null)); } if (response.error != null) { @@ -351,12 +352,12 @@ public List getWithdrawalRequests(Long timeDelta) throws IOEx try { return bitstampAuthenticatedV2.getWithdrawalRequests( - apiKeyForV2Requests, - signatureCreatorV2, - uuidNonceFactory, - timestampFactory, - API_VERSION, - timeDelta); + apiKeyForV2Requests, + signatureCreatorV2, + uuidNonceFactory, + timestampFactory, + API_VERSION, + timeDelta); } catch (BitstampException e) { throw handleError(e); } @@ -366,11 +367,7 @@ public List getWithdrawalFees() throws IOException { try { return bitstampAuthenticatedV2.getWithdrawalFees( - apiKeyForV2Requests, - signatureCreatorV2, - uuidNonceFactory, - timestampFactory, - API_VERSION); + apiKeyForV2Requests, signatureCreatorV2, uuidNonceFactory, timestampFactory, API_VERSION); } catch (BitstampException e) { throw handleError(e); } diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeService.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeService.java index ec6203eb4e0..83b4b3aea6e 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeService.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeService.java @@ -92,11 +92,11 @@ private String placeInstantMarketOrder(MarketOrder order) throws IOException, Bi if (side == Side.sell) { boolean amountInCounter = order.hasFlag(BitstampOrderFlags.INSTANT_AMOUNT_IN_COUNTER); bitstampOrder = - placeBitstampInstantSellMarketOrder(order.getCurrencyPair(), side, order.getOriginalAmount(), amountInCounter); + placeBitstampInstantSellMarketOrder( + order.getCurrencyPair(), side, order.getOriginalAmount(), amountInCounter); } else { bitstampOrder = placeBitstampInstantMarketOrder(order.getCurrencyPair(), side, order.getOriginalAmount()); - } if (bitstampOrder.getErrorMessage() != null) { @@ -106,7 +106,7 @@ private String placeInstantMarketOrder(MarketOrder order) throws IOException, Bi return Long.toString(bitstampOrder.getId()); } - @Override + @Override public String placeMarketOrder(MarketOrder order) throws IOException, BitstampException { BitstampAuthenticatedV2.Side side = order.getType().equals(BID) diff --git a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeServiceRaw.java b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeServiceRaw.java index 78636bb741a..63851c01c12 100644 --- a/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeServiceRaw.java +++ b/xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/service/BitstampTradeServiceRaw.java @@ -113,7 +113,10 @@ public BitstampOrder placeBitstampOrder( } public BitstampOrder placeBitstampInstantSellMarketOrder( - CurrencyPair pair, BitstampAuthenticatedV2.Side side, BigDecimal amount, boolean amountInCounter) + CurrencyPair pair, + BitstampAuthenticatedV2.Side side, + BigDecimal amount, + boolean amountInCounter) throws IOException { try { @@ -133,8 +136,7 @@ public BitstampOrder placeBitstampInstantSellMarketOrder( } public BitstampOrder placeBitstampInstantMarketOrder( - CurrencyPair pair, BitstampAuthenticatedV2.Side side, BigDecimal amount) - throws IOException { + CurrencyPair pair, BitstampAuthenticatedV2.Side side, BigDecimal amount) throws IOException { try { return bitstampAuthenticatedV2.placeInstantMarketOrder( diff --git a/xchange-bitstamp/src/test/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalFeesJSONTest.java b/xchange-bitstamp/src/test/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalFeesJSONTest.java index 34fd836a659..13c2ba031a3 100644 --- a/xchange-bitstamp/src/test/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalFeesJSONTest.java +++ b/xchange-bitstamp/src/test/java/org/knowm/xchange/bitstamp/dto/account/WithdrawalFeesJSONTest.java @@ -24,8 +24,7 @@ public void testUnmarshal() throws IOException { List withdrawalFees = mapper.readValue( - is, - mapper.getTypeFactory().constructCollectionType(List.class, WithdrawalFee.class)); + is, mapper.getTypeFactory().constructCollectionType(List.class, WithdrawalFee.class)); assertThat(withdrawalFees.size()).isEqualTo(1); assertThat(withdrawalFees.get(0).getNetwork()).isEqualTo("bitcoin"); diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainMarketDataService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainMarketDataService.java index 4eaf97c0aa2..95dc750ca20 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainMarketDataService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainMarketDataService.java @@ -1,6 +1,5 @@ package org.knowm.xchange.blockchain.service; - import java.io.IOException; import org.knowm.xchange.blockchain.BlockchainAdapters; import org.knowm.xchange.blockchain.BlockchainAuthenticated; @@ -41,5 +40,4 @@ public OrderBook getOrderBook(Instrument instrument, Object... args) throws IOEx throw BlockchainErrorAdapter.adapt(e); } } - } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/Bybit.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/Bybit.java index 1f4e9f5e454..2888bc6d2cd 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/Bybit.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/Bybit.java @@ -32,16 +32,14 @@ BybitResult> getTicker24h( @GET @Path("/instruments-info") BybitResult> getInstrumentsInfo( - @QueryParam("category") String category, - @QueryParam("limit") String limit) throws IOException, BybitException; + @QueryParam("category") String category, @QueryParam("limit") String limit) + throws IOException, BybitException; /** * @apiSpec API */ @GET @Path("/tickers") - BybitResult> getTickers( - @QueryParam("category") String category) + BybitResult> getTickers(@QueryParam("category") String category) throws IOException, BybitException; - } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAdapters.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAdapters.java index d09624c8c29..158861aa0b4 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAdapters.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAdapters.java @@ -10,7 +10,6 @@ import java.util.Arrays; import java.util.Date; import java.util.List; -import java.util.Locale; import org.knowm.xchange.bybit.dto.BybitCategory; import org.knowm.xchange.bybit.dto.BybitResult; import org.knowm.xchange.bybit.dto.account.allcoins.BybitAllCoinBalance; @@ -48,9 +47,10 @@ public class BybitAdapters { - private static final ThreadLocal OPTION_DATE_FORMAT = ThreadLocal.withInitial( - () -> new SimpleDateFormat("ddMMMyy")); - public static final List QUOTE_CURRENCIES = Arrays.asList("USDT", "USDC", "EUR", "BTC", "ETH", "DAI", "BRZ"); + private static final ThreadLocal OPTION_DATE_FORMAT = + ThreadLocal.withInitial(() -> new SimpleDateFormat("ddMMMyy")); + public static final List QUOTE_CURRENCIES = + Arrays.asList("USDT", "USDC", "EUR", "BTC", "ETH", "DAI", "BRZ"); public static Wallet adaptBybitBalances(List coinWalletBalances) { List balances = new ArrayList<>(coinWalletBalances.size()); @@ -156,18 +156,21 @@ public static CurrencyPair guessSymbol(String symbol) { public static Instrument guessSymbol(String symbol, BybitCategory category) { switch (category) { - case SPOT: { - return guessSymbol(symbol); - } - case LINEAR: { - if (symbol.endsWith("USDT")) { - int splitIndex = symbol.lastIndexOf("USDT"); - return new FuturesContract((symbol.substring(0, splitIndex)+"/"+ symbol.substring(splitIndex)+"/PERP")); - } else if (symbol.endsWith("PERP")) { - int splitIndex = symbol.lastIndexOf("PERP"); - return new FuturesContract((symbol.substring(0, splitIndex)+"/"+ "USDC/PERP")); + case SPOT: + { + return guessSymbol(symbol); + } + case LINEAR: + { + if (symbol.endsWith("USDT")) { + int splitIndex = symbol.lastIndexOf("USDT"); + return new FuturesContract( + (symbol.substring(0, splitIndex) + "/" + symbol.substring(splitIndex) + "/PERP")); + } else if (symbol.endsWith("PERP")) { + int splitIndex = symbol.lastIndexOf("PERP"); + return new FuturesContract((symbol.substring(0, splitIndex) + "/" + "USDC/PERP")); + } } - } } return null; } @@ -393,30 +396,38 @@ private static Builder adaptBybitTickerBuilder( public static Instrument convertBybitSymbolToInstrument(String symbol, BybitCategory category) { switch (category) { - case SPOT: { - return guessSymbol(symbol); - } - case LINEAR: { - if (symbol.endsWith("USDT")) { - int splitIndex = symbol.lastIndexOf("USDT"); - return new FuturesContract(new CurrencyPair(symbol.substring(0, splitIndex), "USDT"),"PERP"); + case SPOT: + { + return guessSymbol(symbol); } - if (symbol.endsWith("PERP")) { - int splitIndex = symbol.lastIndexOf("PERP"); - return new FuturesContract(new CurrencyPair(symbol.substring(0, splitIndex), "USDC"),"PERP"); + case LINEAR: + { + if (symbol.endsWith("USDT")) { + int splitIndex = symbol.lastIndexOf("USDT"); + return new FuturesContract( + new CurrencyPair(symbol.substring(0, splitIndex), "USDT"), "PERP"); + } + if (symbol.endsWith("PERP")) { + int splitIndex = symbol.lastIndexOf("PERP"); + return new FuturesContract( + new CurrencyPair(symbol.substring(0, splitIndex), "USDC"), "PERP"); + } + // USDC Futures + int splitIndex = symbol.lastIndexOf("-"); + return new FuturesContract( + new CurrencyPair(symbol.substring(0, splitIndex), "USDC"), + symbol.substring(splitIndex + 1)); + } + case INVERSE: + { + int splitIndex = symbol.lastIndexOf("USD"); + String perp = symbol.length() > splitIndex + 3 ? symbol.substring(splitIndex + 3) : ""; + return new FuturesContract( + new CurrencyPair(symbol.substring(0, splitIndex), "USD"), perp); + } + case OPTION: + { } - //USDC Futures - int splitIndex = symbol.lastIndexOf("-"); - return new FuturesContract(new CurrencyPair(symbol.substring(0, splitIndex), - "USDC"),symbol.substring(splitIndex+1)); - } - case INVERSE: { - int splitIndex = symbol.lastIndexOf("USD"); - String perp = symbol.length() > splitIndex+3 ? symbol.substring(splitIndex+3) : ""; - return new FuturesContract(new CurrencyPair(symbol.substring(0, splitIndex), "USD"), - perp); - } - case OPTION: {} } return null; } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAuthenticated.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAuthenticated.java index c1f3efe4830..4677c430e97 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAuthenticated.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitAuthenticated.java @@ -13,14 +13,14 @@ import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import java.io.IOException; -import org.knowm.xchange.bybit.dto.trade.BybitAmendOrderPayload; -import org.knowm.xchange.bybit.dto.trade.BybitCancelOrderPayload; -import org.knowm.xchange.bybit.dto.trade.BybitPlaceOrderPayload; import org.knowm.xchange.bybit.dto.BybitResult; import org.knowm.xchange.bybit.dto.account.allcoins.BybitAllCoinsBalance; import org.knowm.xchange.bybit.dto.account.feerates.BybitFeeRates; import org.knowm.xchange.bybit.dto.account.walletbalance.BybitWalletBalance; +import org.knowm.xchange.bybit.dto.trade.BybitAmendOrderPayload; +import org.knowm.xchange.bybit.dto.trade.BybitCancelOrderPayload; import org.knowm.xchange.bybit.dto.trade.BybitOrderResponse; +import org.knowm.xchange.bybit.dto.trade.BybitPlaceOrderPayload; import org.knowm.xchange.bybit.dto.trade.details.BybitOrderDetail; import org.knowm.xchange.bybit.dto.trade.details.BybitOrderDetails; import org.knowm.xchange.bybit.service.BybitException; @@ -105,7 +105,7 @@ BybitResult placeLimitOrder( @HeaderParam(X_BAPI_SIGN) ParamsDigest signature, @HeaderParam(X_BAPI_TIMESTAMP) SynchronizedValueFactory timestamp, BybitPlaceOrderPayload payload) - throws IOException,BybitException; + throws IOException, BybitException; /** * @apiSpec API @@ -118,7 +118,7 @@ BybitResult cancelOrder( @HeaderParam(X_BAPI_SIGN) ParamsDigest signature, @HeaderParam(X_BAPI_TIMESTAMP) SynchronizedValueFactory timestamp, BybitCancelOrderPayload payload) - throws IOException,BybitException; + throws IOException, BybitException; /** * @apiSpec API @@ -131,6 +131,5 @@ BybitResult amendOrder( @HeaderParam(X_BAPI_SIGN) ParamsDigest signature, @HeaderParam(X_BAPI_TIMESTAMP) SynchronizedValueFactory timestamp, BybitAmendOrderPayload payload) - throws IOException,BybitException; - + throws IOException, BybitException; } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitExchange.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitExchange.java index b4c20853655..901b398c3c2 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitExchange.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/BybitExchange.java @@ -19,10 +19,9 @@ public class BybitExchange extends BaseExchange { public static final String SPECIFIC_PARAM_ACCOUNT_TYPE = "accountType"; private static final String BASE_URL = "https://api.bybit.com"; -// private static final String DEMO_URL = "https://api-demo.bybit.com"; + // private static final String DEMO_URL = "https://api-demo.bybit.com"; private static final String TESTNET_URL = "https://api-testnet.bybit.com"; - @Override protected void initServices() { marketDataService = new BybitMarketDataService(this); @@ -45,8 +44,7 @@ public ExchangeSpecification getDefaultExchangeSpecification() { exchangeSpecification.setExchangeDescription("BYBIT"); exchangeSpecification.setExchangeSpecificParametersItem( SPECIFIC_PARAM_ACCOUNT_TYPE, BybitAccountType.UNIFIED); - exchangeSpecification.setExchangeSpecificParametersItem( - Exchange.USE_SANDBOX, false); + exchangeSpecification.setExchangeSpecificParametersItem(Exchange.USE_SANDBOX, false); return exchangeSpecification; } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitAmendOrderPayload.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitAmendOrderPayload.java index 0f4c7b683ec..0dd551e8b9d 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitAmendOrderPayload.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitAmendOrderPayload.java @@ -26,10 +26,22 @@ public class BybitAmendOrderPayload { String tpLimitPrice; String slLimitPrice; - public BybitAmendOrderPayload(BybitCategory category, String symbol, String orderId, - String orderLinkId, String triggerPrice, String qty, String price, - String tpslMode, String takeProfit, String stopLoss, String tpTriggerBy, String slTriggerBy, - String triggerBy, String tpLimitPrice, String slLimitPrice) { + public BybitAmendOrderPayload( + BybitCategory category, + String symbol, + String orderId, + String orderLinkId, + String triggerPrice, + String qty, + String price, + String tpslMode, + String takeProfit, + String stopLoss, + String tpTriggerBy, + String slTriggerBy, + String triggerBy, + String tpLimitPrice, + String slLimitPrice) { this.category = category; this.symbol = symbol; this.orderId = orderId; diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitCancelOrderPayload.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitCancelOrderPayload.java index d67c9e64899..601a78107c8 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitCancelOrderPayload.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitCancelOrderPayload.java @@ -1,7 +1,6 @@ package org.knowm.xchange.bybit.dto.trade; import lombok.Getter; -import org.knowm.xchange.bybit.Bybit; import org.knowm.xchange.bybit.dto.BybitCategory; @Getter @@ -13,11 +12,11 @@ public class BybitCancelOrderPayload { private String orderLinkId; private String orderFilter; - public BybitCancelOrderPayload(BybitCategory category, String symbol, String orderId, String orderLinkId) { + public BybitCancelOrderPayload( + BybitCategory category, String symbol, String orderId, String orderLinkId) { this.category = category; this.symbol = symbol; this.orderId = orderId; this.orderLinkId = orderLinkId; } - } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitPlaceOrderPayload.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitPlaceOrderPayload.java index 3a870d035d9..4bf30322d2a 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitPlaceOrderPayload.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/dto/trade/BybitPlaceOrderPayload.java @@ -14,7 +14,11 @@ public class BybitPlaceOrderPayload { private String orderLinkId; private String price; - public BybitPlaceOrderPayload(String category, String symbol, String side, String orderType, + public BybitPlaceOrderPayload( + String category, + String symbol, + String side, + String orderType, BigDecimal qty, String orderLinkId) { this.category = category; @@ -24,8 +28,15 @@ public BybitPlaceOrderPayload(String category, String symbol, String side, Strin this.qty = qty.toString(); this.orderLinkId = orderLinkId; } - public BybitPlaceOrderPayload(String category, String symbol, String side, String orderType, - BigDecimal qty, String orderLinkId, BigDecimal price) { + + public BybitPlaceOrderPayload( + String category, + String symbol, + String side, + String orderType, + BigDecimal qty, + String orderLinkId, + BigDecimal price) { this.category = category; this.symbol = symbol; this.side = side; diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitMarketDataService.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitMarketDataService.java index b76da919996..fdd09b42a1a 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitMarketDataService.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitMarketDataService.java @@ -68,11 +68,9 @@ public List getTickers(Params params) throws IOException { BybitCategory category; if (params == null) { category = BybitCategory.SPOT; - } - else if (!(params instanceof BybitCategory)) { + } else if (!(params instanceof BybitCategory)) { throw new IllegalArgumentException("Params must be instance of BybitCategory"); - } - else { + } else { category = (BybitCategory) params; } @@ -84,21 +82,23 @@ else if (!(params instanceof BybitCategory)) { for (BybitTicker ticker : response.getResult().getList()) { switch (category) { case SPOT: - result.add(BybitAdapters.adaptBybitSpotTicker(BybitAdapters.convertBybitSymbolToInstrument - (ticker.getSymbol(), category), response.getTime(), (BybitSpotTicker) ticker)); + result.add( + BybitAdapters.adaptBybitSpotTicker( + BybitAdapters.convertBybitSymbolToInstrument(ticker.getSymbol(), category), + response.getTime(), + (BybitSpotTicker) ticker)); break; case LINEAR: case INVERSE: - result.add(BybitAdapters.adaptBybitLinearInverseTicker( - BybitAdapters.convertBybitSymbolToInstrument - (ticker.getSymbol(), category), response.getTime(), - (BybitLinearInverseTicker) ticker)); + result.add( + BybitAdapters.adaptBybitLinearInverseTicker( + BybitAdapters.convertBybitSymbolToInstrument(ticker.getSymbol(), category), + response.getTime(), + (BybitLinearInverseTicker) ticker)); break; default: } } return result; } - } - diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeService.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeService.java index f515b9c2c8e..37a0d069009 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeService.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeService.java @@ -74,33 +74,45 @@ public Collection getOrder(String... orderIds) throws IOException { return results; } - public String amendOrder(Order order) throws IOException { BybitCategory category = BybitAdapters.getCategory(order.getInstrument()); BybitResult response = null; if (order instanceof LimitOrder) { - response = amendOrder(category, - convertToBybitSymbol(order.getInstrument()), order.getId(), order.getUserReference(), - null, order.getOriginalAmount().toString(), ((LimitOrder) order) - .getLimitPrice().toString(), null, null, null, - null, null, null, null, null); + response = + amendOrder( + category, + convertToBybitSymbol(order.getInstrument()), + order.getId(), + order.getUserReference(), + null, + order.getOriginalAmount().toString(), + ((LimitOrder) order).getLimitPrice().toString(), + null, + null, + null, + null, + null, + null, + null, + null); } - //Todo order instanceof StopOrder + // Todo order instanceof StopOrder if (response != null) { return response.getResult().getOrderId(); } return ""; } - public String cancelOrder(Order order) throws IOException { BybitCategory category = BybitAdapters.getCategory(order.getInstrument()); - BybitResult response = cancelOrder(category, - convertToBybitSymbol(order.getInstrument()), order.getId(), order.getUserReference()); + BybitResult response = + cancelOrder( + category, + convertToBybitSymbol(order.getInstrument()), + order.getId(), + order.getUserReference()); if (response != null) { return response.getResult().getOrderId(); - } else - return ""; + } else return ""; } - } diff --git a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeServiceRaw.java b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeServiceRaw.java index 4f691befe3e..3eba5bd9b9b 100644 --- a/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeServiceRaw.java +++ b/xchange-bybit/src/main/java/org/knowm/xchange/bybit/service/BybitTradeServiceRaw.java @@ -6,12 +6,12 @@ import java.math.BigDecimal; import org.knowm.xchange.Exchange; import org.knowm.xchange.bybit.dto.BybitCategory; -import org.knowm.xchange.bybit.dto.trade.BybitCancelOrderPayload; -import org.knowm.xchange.bybit.dto.trade.BybitAmendOrderPayload; -import org.knowm.xchange.bybit.dto.trade.BybitPlaceOrderPayload; import org.knowm.xchange.bybit.dto.BybitResult; +import org.knowm.xchange.bybit.dto.trade.BybitAmendOrderPayload; +import org.knowm.xchange.bybit.dto.trade.BybitCancelOrderPayload; import org.knowm.xchange.bybit.dto.trade.BybitOrderResponse; import org.knowm.xchange.bybit.dto.trade.BybitOrderType; +import org.knowm.xchange.bybit.dto.trade.BybitPlaceOrderPayload; import org.knowm.xchange.bybit.dto.trade.BybitSide; import org.knowm.xchange.bybit.dto.trade.details.BybitOrderDetail; import org.knowm.xchange.bybit.dto.trade.details.BybitOrderDetails; @@ -36,14 +36,16 @@ public BybitResult> getBybitOrder( public BybitResult placeMarketOrder( BybitCategory category, String symbol, BybitSide side, BigDecimal qty, String orderLinkId) throws IOException { - BybitPlaceOrderPayload payload = new BybitPlaceOrderPayload(category.getValue(), - symbol, side.getValue(), BybitOrderType.MARKET.getValue(), qty, orderLinkId); + BybitPlaceOrderPayload payload = + new BybitPlaceOrderPayload( + category.getValue(), + symbol, + side.getValue(), + BybitOrderType.MARKET.getValue(), + qty, + orderLinkId); BybitResult placeOrder = - bybitAuthenticated.placeMarketOrder( - apiKey, - signatureCreator, - nonceFactory, - payload); + bybitAuthenticated.placeMarketOrder(apiKey, signatureCreator, nonceFactory, payload); if (!placeOrder.isSuccess()) { throw createBybitExceptionFromResult(placeOrder); } @@ -51,54 +53,81 @@ public BybitResult placeMarketOrder( } public BybitResult placeLimitOrder( - BybitCategory category, String symbol, BybitSide side, BigDecimal qty, BigDecimal limitPrice, + BybitCategory category, + String symbol, + BybitSide side, + BigDecimal qty, + BigDecimal limitPrice, String orderLinkId) throws IOException { - BybitPlaceOrderPayload payload = new BybitPlaceOrderPayload(category.getValue(), - symbol, side.getValue(), BybitOrderType.LIMIT.getValue(), qty, orderLinkId, limitPrice); + BybitPlaceOrderPayload payload = + new BybitPlaceOrderPayload( + category.getValue(), + symbol, + side.getValue(), + BybitOrderType.LIMIT.getValue(), + qty, + orderLinkId, + limitPrice); BybitResult placeOrder = - bybitAuthenticated.placeLimitOrder( - apiKey, - signatureCreator, - nonceFactory, - payload); + bybitAuthenticated.placeLimitOrder(apiKey, signatureCreator, nonceFactory, payload); if (!placeOrder.isSuccess()) { throw createBybitExceptionFromResult(placeOrder); } return placeOrder; } - public BybitResult amendOrder(BybitCategory category, String symbol, String orderId, - String orderLinkId, String triggerPrice, String qty, String price, String tpslMode, String takeProfit, - String stopLoss, String tpTriggerBy,String slTriggerBy,String triggerBy,String tpLimitPrice, - String slLimitPrice) throws IOException { - //if only userId is used, don't need to send id - if(orderId!= null && orderId.isEmpty()) - orderId = null; - BybitAmendOrderPayload payload = new BybitAmendOrderPayload(category, symbol,orderId,orderLinkId,triggerPrice,qty,price, - tpslMode, takeProfit, stopLoss, tpTriggerBy, slTriggerBy, triggerBy, tpLimitPrice, slLimitPrice); + public BybitResult amendOrder( + BybitCategory category, + String symbol, + String orderId, + String orderLinkId, + String triggerPrice, + String qty, + String price, + String tpslMode, + String takeProfit, + String stopLoss, + String tpTriggerBy, + String slTriggerBy, + String triggerBy, + String tpLimitPrice, + String slLimitPrice) + throws IOException { + // if only userId is used, don't need to send id + if (orderId != null && orderId.isEmpty()) orderId = null; + BybitAmendOrderPayload payload = + new BybitAmendOrderPayload( + category, + symbol, + orderId, + orderLinkId, + triggerPrice, + qty, + price, + tpslMode, + takeProfit, + stopLoss, + tpTriggerBy, + slTriggerBy, + triggerBy, + tpLimitPrice, + slLimitPrice); BybitResult amendOrder = - bybitAuthenticated.amendOrder( - apiKey, - signatureCreator, - nonceFactory, - payload); + bybitAuthenticated.amendOrder(apiKey, signatureCreator, nonceFactory, payload); if (!amendOrder.isSuccess()) { throw createBybitExceptionFromResult(amendOrder); } return amendOrder; } - - public BybitResult cancelOrder(BybitCategory category,String symbol, - String orderId, String orderLinkId) throws IOException { - BybitCancelOrderPayload payload = new BybitCancelOrderPayload(category, symbol, orderId, orderLinkId); + public BybitResult cancelOrder( + BybitCategory category, String symbol, String orderId, String orderLinkId) + throws IOException { + BybitCancelOrderPayload payload = + new BybitCancelOrderPayload(category, symbol, orderId, orderLinkId); BybitResult cancelOrder = - bybitAuthenticated.cancelOrder( - apiKey, - signatureCreator, - nonceFactory, - payload); + bybitAuthenticated.cancelOrder(apiKey, signatureCreator, nonceFactory, payload); if (!cancelOrder.isSuccess()) { throw createBybitExceptionFromResult(cancelOrder); } diff --git a/xchange-bybit/src/test/java/org/knowm/xchange/bybit/BybitAdaptersTest.java b/xchange-bybit/src/test/java/org/knowm/xchange/bybit/BybitAdaptersTest.java index 0b775001686..61dd2d4d9c0 100644 --- a/xchange-bybit/src/test/java/org/knowm/xchange/bybit/BybitAdaptersTest.java +++ b/xchange-bybit/src/test/java/org/knowm/xchange/bybit/BybitAdaptersTest.java @@ -19,8 +19,10 @@ public void testGuessSymbol() { assertThat(guessSymbol("BTCDAI")).isEqualTo(new CurrencyPair("BTC", "DAI")); assertThat(guessSymbol("ABCDEFG")).isEqualTo(new CurrencyPair("ABCD", "EFG")); - assertThat(guessSymbol("BTCUSDT", BybitCategory.LINEAR)).isEqualTo(new FuturesContract("BTC/USDT/PERP")); - assertThat(guessSymbol("ETHPERP", BybitCategory.LINEAR)).isEqualTo(new FuturesContract("ETH/USDC/PERP")); + assertThat(guessSymbol("BTCUSDT", BybitCategory.LINEAR)) + .isEqualTo(new FuturesContract("BTC/USDT/PERP")); + assertThat(guessSymbol("ETHPERP", BybitCategory.LINEAR)) + .isEqualTo(new FuturesContract("ETH/USDC/PERP")); } @Test @@ -55,6 +57,5 @@ public void testConvertToInstrument() { assertThat(BybitAdapters.convertBybitSymbolToInstrument("ETHUSDH24", BybitCategory.INVERSE)) .isEqualTo(new FuturesContract("ETH/USD/H24")); - } } diff --git a/xchange-bybit/src/test/java/org/knowm/xchange/bybit/TradeExample.java b/xchange-bybit/src/test/java/org/knowm/xchange/bybit/TradeExample.java index 817c8fdc635..b21a6a340fc 100644 --- a/xchange-bybit/src/test/java/org/knowm/xchange/bybit/TradeExample.java +++ b/xchange-bybit/src/test/java/org/knowm/xchange/bybit/TradeExample.java @@ -37,75 +37,95 @@ public static void testTrade() throws IOException { exchangeSpecification.setExchangeSpecificParametersItem( SPECIFIC_PARAM_ACCOUNT_TYPE, BybitAccountType.UNIFIED); exchangeSpecification.setExchangeSpecificParametersItem(USE_SANDBOX, true); - Exchange exchange = ExchangeFactory.INSTANCE.createExchange( - exchangeSpecification); + Exchange exchange = ExchangeFactory.INSTANCE.createExchange(exchangeSpecification); Instrument ETH_USDT = new CurrencyPair("ETH/USDT"); Instrument BTC_USDT_PERP = new FuturesContract(new CurrencyPair("BTC/USDT"), "PERP"); Instrument ETH_USDT_PERP = new FuturesContract(new CurrencyPair("ETH/USDT"), "PERP"); -// System.out.printf("Tickers SPOT %s", exchange.getMarketDataService().getTickers(BybitCategory.SPOT)); -// System.out.printf("Tickers LINEAR %s", exchange.getMarketDataService().getTickers(BybitCategory.LINEAR)); -// System.out.printf("Tickers INVERSE %s", exchange.getMarketDataService().getTickers(BybitCategory.INVERSE)); -// System.out.printf("Tickers OPTION %s", exchange.getMarketDataService().getTickers(BybitCategory.OPTION)); - System.out.printf("Wallets: %n%s%n", - exchange.getAccountService().getAccountInfo().getWallets()); - Ticker tickerETH_USDT_PERP = exchange - .getMarketDataService() - .getTicker(ETH_USDT_PERP); - Ticker tickerETH_USDT = exchange - .getMarketDataService() - .getTicker(ETH_USDT); + // System.out.printf("Tickers SPOT %s", + // exchange.getMarketDataService().getTickers(BybitCategory.SPOT)); + // System.out.printf("Tickers LINEAR %s", + // exchange.getMarketDataService().getTickers(BybitCategory.LINEAR)); + // System.out.printf("Tickers INVERSE %s", + // exchange.getMarketDataService().getTickers(BybitCategory.INVERSE)); + // System.out.printf("Tickers OPTION %s", + // exchange.getMarketDataService().getTickers(BybitCategory.OPTION)); + System.out.printf( + "Wallets: %n%s%n", exchange.getAccountService().getAccountInfo().getWallets()); + Ticker tickerETH_USDT_PERP = exchange.getMarketDataService().getTicker(ETH_USDT_PERP); + Ticker tickerETH_USDT = exchange.getMarketDataService().getTicker(ETH_USDT); System.out.println(tickerETH_USDT_PERP.toString()); - System.out.printf("Instrument %s:%n %s", ETH_USDT, exchange.getExchangeMetaData() - .getInstruments().get(ETH_USDT)); - System.out.printf("Instrument %s:%n %s", ETH_USDT_PERP, exchange.getExchangeMetaData() - .getInstruments().get(ETH_USDT_PERP)); - BigDecimal minAmountSpot = exchange.getExchangeMetaData().getInstruments().get(ETH_USDT) - .getMinimumAmount(); + System.out.printf( + "Instrument %s:%n %s", + ETH_USDT, exchange.getExchangeMetaData().getInstruments().get(ETH_USDT)); + System.out.printf( + "Instrument %s:%n %s", + ETH_USDT_PERP, exchange.getExchangeMetaData().getInstruments().get(ETH_USDT_PERP)); + BigDecimal minAmountSpot = + exchange.getExchangeMetaData().getInstruments().get(ETH_USDT).getMinimumAmount(); - //sell + // sell MarketOrder marketOrderSpot = new MarketOrder(OrderType.ASK, minAmountSpot, ETH_USDT); String marketSpotOrderId = exchange.getTradeService().placeMarketOrder(marketOrderSpot); System.out.println("Market Spot order id: " + marketSpotOrderId); - BigDecimal minAmountFuture = exchange.getExchangeMetaData().getInstruments().get(ETH_USDT_PERP) - .getMinimumAmount(); + BigDecimal minAmountFuture = + exchange.getExchangeMetaData().getInstruments().get(ETH_USDT_PERP).getMinimumAmount(); - //long + // long String marketFutureOrderId = exchange .getTradeService() - .placeMarketOrder( - new MarketOrder(OrderType.BID, minAmountFuture, ETH_USDT_PERP)); + .placeMarketOrder(new MarketOrder(OrderType.BID, minAmountFuture, ETH_USDT_PERP)); System.out.println("Market Future order id: " + marketFutureOrderId); - //short - LimitOrder limitOrderFuture = new LimitOrder(OrderType.ASK, minAmountFuture, ETH_USDT_PERP, - null, null, tickerETH_USDT_PERP.getHigh()); - String limitFutureOrderId = - exchange.getTradeService().placeLimitOrder(limitOrderFuture); + // short + LimitOrder limitOrderFuture = + new LimitOrder( + OrderType.ASK, + minAmountFuture, + ETH_USDT_PERP, + null, + null, + tickerETH_USDT_PERP.getHigh()); + String limitFutureOrderId = exchange.getTradeService().placeLimitOrder(limitOrderFuture); System.out.println("Limit Future order id: " + limitFutureOrderId); - //amend order by order id - LimitOrder amendOrder1 = new LimitOrder(limitOrderFuture.getType(), - limitOrderFuture.getOriginalAmount().multiply(new BigDecimal(2)), - limitOrderFuture.getInstrument(), limitFutureOrderId, limitOrderFuture.getTimestamp(), - tickerETH_USDT_PERP.getHigh(), - null, null, null, OrderStatus.PENDING_NEW, null); + // amend order by order id + LimitOrder amendOrder1 = + new LimitOrder( + limitOrderFuture.getType(), + limitOrderFuture.getOriginalAmount().multiply(new BigDecimal(2)), + limitOrderFuture.getInstrument(), + limitFutureOrderId, + limitOrderFuture.getTimestamp(), + tickerETH_USDT_PERP.getHigh(), + null, + null, + null, + OrderStatus.PENDING_NEW, + null); String limitFutureOrderAmend1 = ((BybitTradeService) exchange.getTradeService()).amendOrder(amendOrder1); System.out.printf("amend limit order %s%n", limitFutureOrderAmend1); - //amend order by user id - LimitOrder amendOrder2 = new LimitOrder(limitOrderFuture.getType(), - limitOrderFuture.getOriginalAmount(), limitOrderFuture.getInstrument(), - "", limitOrderFuture.getTimestamp(), tickerETH_USDT_PERP.getLast(), - null, null, null, OrderStatus.PENDING_NEW, limitOrderFuture.getUserReference()); + // amend order by user id + LimitOrder amendOrder2 = + new LimitOrder( + limitOrderFuture.getType(), + limitOrderFuture.getOriginalAmount(), + limitOrderFuture.getInstrument(), + "", + limitOrderFuture.getTimestamp(), + tickerETH_USDT_PERP.getLast(), + null, + null, + null, + OrderStatus.PENDING_NEW, + limitOrderFuture.getUserReference()); String limitFutureOrderAmend2 = - ((BybitTradeService) exchange.getTradeService()) - .amendOrder(amendOrder2); + ((BybitTradeService) exchange.getTradeService()).amendOrder(amendOrder2); System.out.printf("amend limit order %s%n", limitFutureOrderAmend2); - } } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/Coinex.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/Coinex.java index 64004f2e363..d73646e5784 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/Coinex.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/Coinex.java @@ -22,33 +22,28 @@ public interface Coinex { @GET @Path("v1/common/asset/config") - CoinexResponse> allChainInfos() - throws IOException, CoinexException; - + CoinexResponse> allChainInfos() throws IOException, CoinexException; @GET @Path("v1/market/ticker/all") CoinexResponse allMarketStatistics() throws IOException, CoinexException; - @GET @Path("v1/market/ticker") - CoinexResponse singleMarketStatistics(@QueryParam("market") String market) - throws IOException, CoinexException; - + CoinexResponse singleMarketStatistics( + @QueryParam("market") String market) throws IOException, CoinexException; @GET @Path("v2/spot/market") CoinexResponse> marketStatus(@QueryParam("market") String markets) throws IOException, CoinexException; - @GET @Path("v2/spot/depth") - CoinexResponse marketDepth(@QueryParam("market") String market, - @QueryParam("limit") Integer limit, @QueryParam("interval") Integer interval) + CoinexResponse marketDepth( + @QueryParam("market") String market, + @QueryParam("limit") Integer limit, + @QueryParam("interval") Integer interval) throws IOException, CoinexException; - - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAdapters.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAdapters.java index 302bc9385e5..26b8cea69f0 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAdapters.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAdapters.java @@ -33,7 +33,6 @@ public class CoinexAdapters { private final Map SYMBOL_TO_CURRENCY_PAIR = new HashMap<>(); - public String instrumentsToString(Collection instruments) { if (instruments == null || instruments.isEmpty()) { return null; @@ -42,12 +41,10 @@ public String instrumentsToString(Collection instruments) { } } - public void putSymbolMapping(String symbol, CurrencyPair currencyPair) { SYMBOL_TO_CURRENCY_PAIR.put(symbol, currencyPair); } - public Balance toBalance(CoinexBalanceInfo balance) { return new Balance.Builder() .currency(balance.getCurrency()) @@ -56,7 +53,6 @@ public Balance toBalance(CoinexBalanceInfo balance) { .build(); } - public CoinexOrder toCoinexOrder(MarketOrder marketOrder) { return CoinexOrder.builder() .currencyPair((CurrencyPair) marketOrder.getInstrument()) @@ -68,12 +64,10 @@ public CoinexOrder toCoinexOrder(MarketOrder marketOrder) { .build(); } - public CurrencyPair toCurrencyPair(String symbol) { return SYMBOL_TO_CURRENCY_PAIR.get(symbol); } - public InstrumentMetaData toInstrumentMetaData(CoinexCurrencyPairInfo coinexCurrencyPairInfo) { return new InstrumentMetaData.Builder() .tradingFee(coinexCurrencyPairInfo.getTakerFeeRate()) @@ -83,7 +77,6 @@ public InstrumentMetaData toInstrumentMetaData(CoinexCurrencyPairInfo coinexCurr .build(); } - public Order toOrder(CoinexOrder coinexOrder) { Order.Builder builder; Instrument instrument = coinexOrder.getCurrencyPair(); @@ -94,8 +87,7 @@ public Order toOrder(CoinexOrder coinexOrder) { builder = new MarketOrder.Builder(orderType, instrument); break; case "limit": - builder = new LimitOrder.Builder(orderType, instrument) - .limitPrice(coinexOrder.getPrice()); + builder = new LimitOrder.Builder(orderType, instrument).limitPrice(coinexOrder.getPrice()); break; default: throw new IllegalArgumentException("Can't map " + coinexOrder.getType()); @@ -104,18 +96,21 @@ public Order toOrder(CoinexOrder coinexOrder) { if (orderType == OrderType.BID) { // buy orders fill quote builder.cumulativeAmount(coinexOrder.getFilledQuoteAmount()); - } - else if (orderType == OrderType.ASK) { + } else if (orderType == OrderType.ASK) { // sell orders fill asset builder.cumulativeAmount(coinexOrder.getFilledAssetAmount()); - } - else { + } else { throw new IllegalArgumentException("Can't map " + orderType); } // average price - if (coinexOrder.getFilledAssetAmount() != null && coinexOrder.getFilledQuoteAmount() != null && coinexOrder.getFilledAssetAmount().signum() > 0) { - builder.averagePrice(coinexOrder.getFilledQuoteAmount().divide(coinexOrder.getFilledAssetAmount(), MathContext.DECIMAL32)); + if (coinexOrder.getFilledAssetAmount() != null + && coinexOrder.getFilledQuoteAmount() != null + && coinexOrder.getFilledAssetAmount().signum() > 0) { + builder.averagePrice( + coinexOrder + .getFilledQuoteAmount() + .divide(coinexOrder.getFilledAssetAmount(), MathContext.DECIMAL32)); } return builder @@ -127,36 +122,36 @@ else if (orderType == OrderType.ASK) { .build(); } - public OrderBook toOrderBook(CoinexMarketDepth coinexMarketDepth) { - List asks = coinexMarketDepth.getDepth().getAsks().stream() - .map(priceSizeEntry -> - new LimitOrder( - OrderType.ASK, - priceSizeEntry.getSize(), - coinexMarketDepth.getCurrencyPair(), - null, - null, - priceSizeEntry.getPrice()) - ) - .collect(Collectors.toList()); - - List bids = coinexMarketDepth.getDepth().getBids().stream() - .map(priceSizeEntry -> - new LimitOrder( - OrderType.BID, - priceSizeEntry.getSize(), - coinexMarketDepth.getCurrencyPair(), - null, - null, - priceSizeEntry.getPrice()) - ) - .collect(Collectors.toList()); + List asks = + coinexMarketDepth.getDepth().getAsks().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.ASK, + priceSizeEntry.getSize(), + coinexMarketDepth.getCurrencyPair(), + null, + null, + priceSizeEntry.getPrice())) + .collect(Collectors.toList()); + + List bids = + coinexMarketDepth.getDepth().getBids().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.BID, + priceSizeEntry.getSize(), + coinexMarketDepth.getCurrencyPair(), + null, + null, + priceSizeEntry.getPrice())) + .collect(Collectors.toList()); return new OrderBook(Date.from(coinexMarketDepth.getDepth().getUpdatedAt()), asks, bids); } - public String toString(Instrument instrument) { if (instrument == null) { return null; @@ -165,7 +160,6 @@ public String toString(Instrument instrument) { } } - public Ticker toTicker(Instrument instrument, CoinexTickerV1 coinexTickerV1, Instant timestamp) { Builder builder = new Ticker.Builder(); @@ -189,19 +183,14 @@ public Ticker toTicker(Instrument instrument, CoinexTickerV1 coinexTickerV1, Ins return builder.build(); } - public Ticker toTicker(String symbol, CoinexTickerV1 coinexTickerV1, Instant timestamp) { return toTicker(toCurrencyPair(symbol), coinexTickerV1, timestamp); } - public Wallet toWallet(List coinexBalanceInfos) { - List balances = coinexBalanceInfos.stream() - .map(CoinexAdapters::toBalance) - .collect(Collectors.toList()); + List balances = + coinexBalanceInfos.stream().map(CoinexAdapters::toBalance).collect(Collectors.toList()); return Wallet.Builder.from(balances).id("spot").build(); } - - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAuthenticated.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAuthenticated.java index 1baa2e2e334..f3063c4273f 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAuthenticated.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexAuthenticated.java @@ -48,6 +48,4 @@ CoinexResponse orderStatus( @QueryParam("market") String market, @QueryParam("order_id") String orderId) throws IOException, CoinexException; - - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexExchange.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexExchange.java index 0420629eb3a..57a87e13b53 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexExchange.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/CoinexExchange.java @@ -36,22 +36,27 @@ public ExchangeSpecification getDefaultExchangeSpecification() { @Override public void remoteInit() throws IOException { - CoinexMarketDataServiceRaw coinexMarketDataServiceRaw = (CoinexMarketDataServiceRaw) marketDataService; + CoinexMarketDataServiceRaw coinexMarketDataServiceRaw = + (CoinexMarketDataServiceRaw) marketDataService; // initialize symbol mappings - List currencyPairInfos = coinexMarketDataServiceRaw.getCoinexCurrencyPairInfos(null); - currencyPairInfos.forEach(currencyPairInfo -> { - CoinexAdapters.putSymbolMapping(currencyPairInfo.getSymbol(), new CurrencyPair(currencyPairInfo.getBaseCurrency(), currencyPairInfo.getQuoteCurrency())); - }); + List currencyPairInfos = + coinexMarketDataServiceRaw.getCoinexCurrencyPairInfos(null); + currencyPairInfos.forEach( + currencyPairInfo -> { + CoinexAdapters.putSymbolMapping( + currencyPairInfo.getSymbol(), + new CurrencyPair( + currencyPairInfo.getBaseCurrency(), currencyPairInfo.getQuoteCurrency())); + }); // initialize instrument metadata - Map instruments = currencyPairInfos.stream() - .collect(Collectors.toMap( - CoinexCurrencyPairInfo::getCurrencyPair, - CoinexAdapters::toInstrumentMetaData) - ); + Map instruments = + currencyPairInfos.stream() + .collect( + Collectors.toMap( + CoinexCurrencyPairInfo::getCurrencyPair, CoinexAdapters::toInstrumentMetaData)); exchangeMetaData = new ExchangeMetaData(instruments, null, null, null, null); - } } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/CurrencyPairToStringConverter.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/CurrencyPairToStringConverter.java index d635f82fef8..24631722aa8 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/CurrencyPairToStringConverter.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/CurrencyPairToStringConverter.java @@ -4,9 +4,7 @@ import org.knowm.xchange.coinex.CoinexAdapters; import org.knowm.xchange.currency.CurrencyPair; -/** - * Converts {@code CurrencyPair} to string - */ +/** Converts {@code CurrencyPair} to string */ public class CurrencyPairToStringConverter extends StdConverter { @Override diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/OrderTypeToStringConverter.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/OrderTypeToStringConverter.java index 24b0d92d646..b66d12d359f 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/OrderTypeToStringConverter.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/OrderTypeToStringConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.dto.Order.OrderType; -/** - * Converts {@code OrderType} to string - */ +/** Converts {@code OrderType} to string */ public class OrderTypeToStringConverter extends StdConverter { @Override diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderStatusConverter.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderStatusConverter.java index 60a9529b674..c2b31ac95ed 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderStatusConverter.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderStatusConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.dto.Order.OrderStatus; -/** - * Converts string to {@code OrderStatus} - */ +/** Converts string to {@code OrderStatus} */ public class StringToOrderStatusConverter extends StdConverter { @Override diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderTypeConverter.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderTypeConverter.java index 5da07deb1fb..ae876764dfa 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderTypeConverter.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/config/converter/StringToOrderTypeConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.dto.Order.OrderType; -/** - * Converts string to {@code OrderType} - */ +/** Converts string to {@code OrderType} */ public class StringToOrderTypeConverter extends StdConverter { @Override diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexException.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexException.java index 53d38f4307b..9182b946f16 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexException.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexException.java @@ -14,5 +14,4 @@ public class CoinexException extends RuntimeException { Object data; String message; - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexResponse.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexResponse.java index de2698154b3..7131ab29a69 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexResponse.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/CoinexResponse.java @@ -18,5 +18,4 @@ public void setCode(Integer code) { } this.code = code; } - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexBalanceInfo.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexBalanceInfo.java index 2feb98870be..6e0ae952bed 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexBalanceInfo.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexBalanceInfo.java @@ -21,5 +21,4 @@ public class CoinexBalanceInfo { private BigDecimal available; private BigDecimal frozen; - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexMarketType.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexMarketType.java index 5a50945319e..21a39e5a909 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexMarketType.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexMarketType.java @@ -6,9 +6,7 @@ @Getter @AllArgsConstructor public enum CoinexMarketType { - SPOT, MARGIN, FUTURES; - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexOrder.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexOrder.java index 2f8eb172998..5f8534fcfa2 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexOrder.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/account/CoinexOrder.java @@ -95,5 +95,4 @@ public class CoinexOrder { @JsonProperty("updated_at") private Instant updatedAt; - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexAllMarketStatisticsV1.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexAllMarketStatisticsV1.java index 4b94c7e8355..8bfb4bfdb48 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexAllMarketStatisticsV1.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexAllMarketStatisticsV1.java @@ -17,5 +17,4 @@ public class CoinexAllMarketStatisticsV1 { @JsonProperty("ticker") private Map tickers; - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexChainInfo.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexChainInfo.java index 7a5757e9a5f..482beccd309 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexChainInfo.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexChainInfo.java @@ -15,32 +15,31 @@ @Jacksonized public class CoinexChainInfo { - @JsonProperty("asset") - @JsonDeserialize(converter = StringToCurrencyConverter.class) - private Currency currency; + @JsonProperty("asset") + @JsonDeserialize(converter = StringToCurrencyConverter.class) + private Currency currency; - @JsonProperty("chain") - private String chainName; + @JsonProperty("chain") + private String chainName; - @JsonProperty("withdrawal_precision") - private Integer withdrawalPrecision; + @JsonProperty("withdrawal_precision") + private Integer withdrawalPrecision; - @JsonProperty("can_deposit") - private Boolean depositEnabled; + @JsonProperty("can_deposit") + private Boolean depositEnabled; - @JsonProperty("can_withdraw") - private Boolean withdrawEnabled; + @JsonProperty("can_withdraw") + private Boolean withdrawEnabled; - @JsonProperty("deposit_least_amount") - private BigDecimal minDepositAmount; + @JsonProperty("deposit_least_amount") + private BigDecimal minDepositAmount; - @JsonProperty("withdraw_least_amount") - private BigDecimal minWitdrawAmount; + @JsonProperty("withdraw_least_amount") + private BigDecimal minWitdrawAmount; - @JsonProperty("withdraw_tx_fee") - private BigDecimal witdrawFeeAmount; - - @JsonProperty("explorer_asset_url") - private URI explorerAssetUrl; + @JsonProperty("withdraw_tx_fee") + private BigDecimal witdrawFeeAmount; + @JsonProperty("explorer_asset_url") + private URI explorerAssetUrl; } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexCurrencyPairInfo.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexCurrencyPairInfo.java index 68ff3c7abb4..d36d5326521 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexCurrencyPairInfo.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexCurrencyPairInfo.java @@ -47,9 +47,7 @@ public class CoinexCurrencyPairInfo { @JsonProperty("min_amount") private BigDecimal minAssetAmount; - public CurrencyPair getCurrencyPair() { return new CurrencyPair(baseCurrency, quoteCurrency); } - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexMarketDepth.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexMarketDepth.java index eb9846bdab2..7895face195 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexMarketDepth.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexMarketDepth.java @@ -43,7 +43,6 @@ public static class Depth { @JsonProperty("updated_at") Instant updatedAt; - } @Data diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexSingleMarketStatisticsV1.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexSingleMarketStatisticsV1.java index 1a4e21405e5..7585a05200b 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexSingleMarketStatisticsV1.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/dto/marketdata/CoinexSingleMarketStatisticsV1.java @@ -16,5 +16,4 @@ public class CoinexSingleMarketStatisticsV1 { @JsonProperty("ticker") private CoinexTickerV1 ticker; - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexAccountServiceRaw.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexAccountServiceRaw.java index 12f8cb05818..eeedcaf70c0 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexAccountServiceRaw.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexAccountServiceRaw.java @@ -12,6 +12,8 @@ public CoinexAccountServiceRaw(CoinexExchange exchange) { } public List getCoinexBalances() throws IOException { - return coinexAuthenticated.balances(apiKey, exchange.getNonceFactory(), coinexV2ParamsDigest).getData(); + return coinexAuthenticated + .balances(apiKey, exchange.getNonceFactory(), coinexV2ParamsDigest) + .getData(); } } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexBaseService.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexBaseService.java index 40a785d2369..c97b98cbc67 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexBaseService.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexBaseService.java @@ -17,18 +17,24 @@ public class CoinexBaseService extends BaseExchangeService imple public CoinexBaseService(CoinexExchange exchange) { super(exchange); - coinex = ExchangeRestProxyBuilder - .forInterface(Coinex.class, exchange.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.setJacksonObjectMapperFactory(new CoinexJacksonObjectMapperFactory())) - .build(); - coinexAuthenticated = ExchangeRestProxyBuilder - .forInterface(CoinexAuthenticated.class, exchange.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.setJacksonObjectMapperFactory(new CoinexJacksonObjectMapperFactory())) - .build(); + coinex = + ExchangeRestProxyBuilder.forInterface(Coinex.class, exchange.getExchangeSpecification()) + .clientConfigCustomizer( + clientConfig -> + clientConfig.setJacksonObjectMapperFactory( + new CoinexJacksonObjectMapperFactory())) + .build(); + coinexAuthenticated = + ExchangeRestProxyBuilder.forInterface( + CoinexAuthenticated.class, exchange.getExchangeSpecification()) + .clientConfigCustomizer( + clientConfig -> + clientConfig.setJacksonObjectMapperFactory( + new CoinexJacksonObjectMapperFactory())) + .build(); apiKey = exchange.getExchangeSpecification().getApiKey(); coinexV2ParamsDigest = CoinexV2Digest.createInstance(exchange.getExchangeSpecification().getSecretKey()); - } } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataService.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataService.java index 30e162eb1ba..985d202633f 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataService.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataService.java @@ -23,32 +23,33 @@ import org.knowm.xchange.service.marketdata.params.InstrumentsParams; import org.knowm.xchange.service.marketdata.params.Params; -public class CoinexMarketDataService extends CoinexMarketDataServiceRaw implements MarketDataService { - +public class CoinexMarketDataService extends CoinexMarketDataServiceRaw + implements MarketDataService { public CoinexMarketDataService(CoinexExchange exchange) { super(exchange); } - @Override public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { return getTicker((Instrument) currencyPair, args); } - @Override public Ticker getTicker(Instrument instrument, Object... args) throws IOException { try { - CoinexSingleMarketStatisticsV1 singleMarketStatisticsV1 = getCoinexSingleMarketStatisticsV1(instrument); - return CoinexAdapters.toTicker(instrument, singleMarketStatisticsV1.getTicker(), singleMarketStatisticsV1.getTimestamp()); + CoinexSingleMarketStatisticsV1 singleMarketStatisticsV1 = + getCoinexSingleMarketStatisticsV1(instrument); + return CoinexAdapters.toTicker( + instrument, + singleMarketStatisticsV1.getTicker(), + singleMarketStatisticsV1.getTimestamp()); } catch (CoinexException e) { throw CoinexErrorAdapter.adapt(e); } } - @Override public List getTickers(Params params) throws IOException { // parse parameters @@ -56,9 +57,9 @@ public List getTickers(Params params) throws IOException { if (params instanceof InstrumentsParams) { instruments = ((InstrumentsParams) params).getInstruments(); } else if (params instanceof CurrencyPairsParam) { - instruments = ((CurrencyPairsParam) params).getCurrencyPairs().stream() - .map(Instrument.class::cast) - .collect(Collectors.toList()); + instruments = + ((CurrencyPairsParam) params) + .getCurrencyPairs().stream().map(Instrument.class::cast).collect(Collectors.toList()); } try { @@ -66,11 +67,15 @@ public List getTickers(Params params) throws IOException { if (instruments.isEmpty()) { CoinexAllMarketStatisticsV1 coinexAllMarketStatisticsV1 = getCoinexAllMarketStatisticsV1(); return coinexAllMarketStatisticsV1.getTickers().entrySet().stream() - .map(entry -> CoinexAdapters.toTicker(entry.getKey(), entry.getValue(), coinexAllMarketStatisticsV1.getTimestamp())) + .map( + entry -> + CoinexAdapters.toTicker( + entry.getKey(), + entry.getValue(), + coinexAllMarketStatisticsV1.getTimestamp())) .filter(ticker -> ticker.getInstrument() != null) .collect(Collectors.toList()); - } - else { + } else { // get the first one Instrument instrument = instruments.iterator().next(); return Collections.singletonList(getTicker(instrument)); @@ -81,27 +86,24 @@ public List getTickers(Params params) throws IOException { } } - @Override public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { return getOrderBook((Instrument) currencyPair, args); } - @Override public OrderBook getOrderBook(Instrument instrument, Object... args) throws IOException { Integer limit = (Integer) ArrayUtils.get(args, 0); Integer interval = (Integer) ArrayUtils.get(args, 1); - return getOrderBook(CoinexOrderBookParams.builder() - .instrument(instrument) - .limit(limit) - .interval(interval) - .build() - ); + return getOrderBook( + CoinexOrderBookParams.builder() + .instrument(instrument) + .limit(limit) + .interval(interval) + .build()); } - @Override public OrderBook getOrderBook(Params params) throws IOException { Validate.isInstanceOf(CoinexOrderBookParams.class, params); diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRaw.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRaw.java index 80e0c48464d..0d48ff84af1 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRaw.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRaw.java @@ -21,35 +21,36 @@ public CoinexMarketDataServiceRaw(CoinexExchange exchange) { super(exchange); } - public List getAllCoinexChainInfos() throws IOException { return new ArrayList<>(coinex.allChainInfos().getData().values()); } - public CoinexAllMarketStatisticsV1 getCoinexAllMarketStatisticsV1() throws IOException { return coinex.allMarketStatistics().getData(); } - - public CoinexSingleMarketStatisticsV1 getCoinexSingleMarketStatisticsV1(Instrument instrument) throws IOException { + public CoinexSingleMarketStatisticsV1 getCoinexSingleMarketStatisticsV1(Instrument instrument) + throws IOException { String market = CoinexAdapters.toString(instrument); return coinex.singleMarketStatistics(market).getData(); } - - public List getCoinexCurrencyPairInfos(Collection instruments) throws IOException { + public List getCoinexCurrencyPairInfos(Collection instruments) + throws IOException { String marketsParam = CoinexAdapters.instrumentsToString(instruments); return coinex.marketStatus(marketsParam).getData(); } - - public CoinexMarketDepth getCoinexOrderBook(CoinexOrderBookParams coinexOrderBookParams) throws IOException { + public CoinexMarketDepth getCoinexOrderBook(CoinexOrderBookParams coinexOrderBookParams) + throws IOException { String instrument = CoinexAdapters.toString(coinexOrderBookParams.getInstrument()); - Integer limit = Optional.ofNullable(coinexOrderBookParams.getLimit()).orElse(CoinexOrderBookParams.DEFAULT_LIMIT); - Integer interval = Optional.ofNullable(coinexOrderBookParams.getInterval()).orElse(CoinexOrderBookParams.DEFAULT_INTERVAL); + Integer limit = + Optional.ofNullable(coinexOrderBookParams.getLimit()) + .orElse(CoinexOrderBookParams.DEFAULT_LIMIT); + Integer interval = + Optional.ofNullable(coinexOrderBookParams.getInterval()) + .orElse(CoinexOrderBookParams.DEFAULT_INTERVAL); return coinex.marketDepth(instrument, limit, interval).getData(); } - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeService.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeService.java index 3960a131664..e17e873c5dc 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeService.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeService.java @@ -21,19 +21,16 @@ public CoinexTradeService(CoinexExchange exchange) { super(exchange); } - @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { try { CoinexOrder coinexOrder = createOrder(CoinexAdapters.toCoinexOrder(marketOrder)); return String.valueOf(coinexOrder.getOrderId()); - } - catch (CoinexException e) { + } catch (CoinexException e) { throw CoinexErrorAdapter.adapt(e); } } - @Override public Collection getOrder(OrderQueryParams... orderQueryParams) throws IOException { Validate.validState(orderQueryParams.length == 1); @@ -44,11 +41,8 @@ public Collection getOrder(OrderQueryParams... orderQueryParams) throws I try { CoinexOrder gateioOrder = orderStatus(params.getInstrument(), params.getOrderId()); return Collections.singletonList(CoinexAdapters.toOrder(gateioOrder)); - } - catch (CoinexException e) { + } catch (CoinexException e) { throw CoinexErrorAdapter.adapt(e); } } - - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeServiceRaw.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeServiceRaw.java index d6466537635..33f5dd6baa6 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeServiceRaw.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexTradeServiceRaw.java @@ -12,16 +12,16 @@ public CoinexTradeServiceRaw(CoinexExchange exchange) { super(exchange); } - public CoinexOrder createOrder(CoinexOrder coinexOrder) throws IOException { - return coinexAuthenticated.createOrder(apiKey, exchange.getNonceFactory(), coinexV2ParamsDigest, coinexOrder).getData(); + return coinexAuthenticated + .createOrder(apiKey, exchange.getNonceFactory(), coinexV2ParamsDigest, coinexOrder) + .getData(); } - public CoinexOrder orderStatus(Instrument instrument, String orderId) throws IOException { String market = CoinexAdapters.toString(instrument); - return coinexAuthenticated.orderStatus(apiKey, exchange.getNonceFactory(), coinexV2ParamsDigest, market, orderId).getData(); + return coinexAuthenticated + .orderStatus(apiKey, exchange.getNonceFactory(), coinexV2ParamsDigest, market, orderId) + .getData(); } - - } diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexV2Digest.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexV2Digest.java index b548cd49ee2..1c58803d53c 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexV2Digest.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/CoinexV2Digest.java @@ -14,12 +14,10 @@ private CoinexV2Digest(String secretKeyBase64) { super(secretKeyBase64, HMAC_SHA_256); } - public static CoinexV2Digest createInstance(String secretKeyBase64) { return secretKeyBase64 == null ? null : new CoinexV2Digest(secretKeyBase64); } - @SneakyThrows @Override public String digestParams(RestInvocation restInvocation) { @@ -34,8 +32,7 @@ public String digestParams(RestInvocation restInvocation) { String timestamp = restInvocation.getHttpHeadersFromParams().get("X-COINEX-TIMESTAMP"); - String payloadToSign = - String.format("%s/%s%s%s%s", method, path, query, body, timestamp); + String payloadToSign = String.format("%s/%s%s%s%s", method, path, query, body, timestamp); Mac mac = getMac(); mac.update(payloadToSign.getBytes(StandardCharsets.UTF_8)); diff --git a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/params/CoinexOrderBookParams.java b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/params/CoinexOrderBookParams.java index c8585f83550..a6adf5a1587 100644 --- a/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/params/CoinexOrderBookParams.java +++ b/xchange-coinex/src/main/java/org/knowm/xchange/coinex/service/params/CoinexOrderBookParams.java @@ -17,5 +17,4 @@ public class CoinexOrderBookParams implements Params { private Integer limit; private Integer interval; - } diff --git a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/CoinexExchangeIntegration.java b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/CoinexExchangeIntegration.java index 416159a01f9..8931eab98cb 100644 --- a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/CoinexExchangeIntegration.java +++ b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/CoinexExchangeIntegration.java @@ -13,13 +13,11 @@ class CoinexExchangeIntegration { CoinexExchange exchange = ExchangeFactory.INSTANCE.createExchange(CoinexExchange.class); - @Test void valid_metadata() { assertThat(exchange.getExchangeMetaData()).isNotNull(); - Map instruments = exchange.getExchangeMetaData().getInstruments(); + Map instruments = + exchange.getExchangeMetaData().getInstruments(); assertThat(instruments).containsKey(CurrencyPair.BTC_USDT); } - - -} \ No newline at end of file +} diff --git a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexAccountServiceIntegration.java b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexAccountServiceIntegration.java index 353286f1d46..4f78e75e50e 100644 --- a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexAccountServiceIntegration.java +++ b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexAccountServiceIntegration.java @@ -30,6 +30,4 @@ void valid_balances() throws IOException { AccountInfo accountInfo = exchange.getAccountService().getAccountInfo(); assertThat(accountInfo.getWallet("spot").getBalances()).isNotEmpty(); } - - -} \ No newline at end of file +} diff --git a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceIntegration.java b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceIntegration.java index 336a546a749..9de6ac4629c 100644 --- a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceIntegration.java +++ b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceIntegration.java @@ -21,16 +21,17 @@ void valid_tickers() throws IOException { List tickers = exchange.getMarketDataService().getTickers(null); assertThat(tickers).isNotEmpty(); - assertThat(tickers).allSatisfy(ticker -> { - assertThat(ticker.getInstrument()).isNotNull(); - assertThat(ticker.getLast()).isNotNull(); - if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { - assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); - } - }); + assertThat(tickers) + .allSatisfy( + ticker -> { + assertThat(ticker.getInstrument()).isNotNull(); + assertThat(ticker.getLast()).isNotNull(); + if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { + assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); + } + }); } - @Test void valid_single_ticker() throws IOException { Ticker ticker = exchange.getMarketDataService().getTicker(CurrencyPair.BTC_USDT); @@ -41,10 +42,8 @@ void valid_single_ticker() throws IOException { if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); } - } - @Test void valid_orderbook() throws IOException { OrderBook orderBook = exchange.getMarketDataService().getOrderBook(CurrencyPair.BTC_USDT); @@ -52,18 +51,21 @@ void valid_orderbook() throws IOException { assertThat(orderBook.getBids()).isNotEmpty(); assertThat(orderBook.getAsks()).isNotEmpty(); - assertThat(orderBook.getAsks().get(0).getLimitPrice()).isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); - - assertThat(orderBook.getBids()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); - }); - - assertThat(orderBook.getAsks()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); - }); - + assertThat(orderBook.getAsks().get(0).getLimitPrice()) + .isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); + + assertThat(orderBook.getBids()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); + }); + + assertThat(orderBook.getAsks()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); + }); } - -} \ No newline at end of file +} diff --git a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRawIntegration.java b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRawIntegration.java index b5283174d7a..629dd17fedb 100644 --- a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRawIntegration.java +++ b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexMarketDataServiceRawIntegration.java @@ -15,14 +15,15 @@ class CoinexMarketDataServiceRawIntegration { @Test void valid_chainInfos() throws IOException { - CoinexMarketDataServiceRaw coinexMarketDataServiceRaw = (CoinexMarketDataServiceRaw) exchange.getMarketDataService(); + CoinexMarketDataServiceRaw coinexMarketDataServiceRaw = + (CoinexMarketDataServiceRaw) exchange.getMarketDataService(); List chainInfos = coinexMarketDataServiceRaw.getAllCoinexChainInfos(); - assertThat(chainInfos).allSatisfy(chainInfo -> { - assertThat(chainInfo.getCurrency()).isNotNull(); - assertThat(chainInfo.getChainName()).isNotEmpty(); - }); + assertThat(chainInfos) + .allSatisfy( + chainInfo -> { + assertThat(chainInfo.getCurrency()).isNotNull(); + assertThat(chainInfo.getChainName()).isNotEmpty(); + }); } - - -} \ No newline at end of file +} diff --git a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexV2DigestTest.java b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexV2DigestTest.java index e472e59930d..25990518aed 100644 --- a/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexV2DigestTest.java +++ b/xchange-coinex/src/test/java/org/knowm/xchange/coinex/service/CoinexV2DigestTest.java @@ -14,8 +14,7 @@ @ExtendWith(MockitoExtension.class) class CoinexV2DigestTest { - @Mock - RestInvocation restInvocation; + @Mock RestInvocation restInvocation; @Test void signature_no_query_params() { @@ -35,7 +34,6 @@ void signature_no_query_params() { assertThat(actual).isEqualTo(expected); } - @Test void signature_with_query_params() { CoinexV2Digest coinexV2Digest = CoinexV2Digest.createInstance("a"); @@ -53,6 +51,4 @@ void signature_with_query_params() { assertThat(actual).isEqualTo(expected); } - - -} \ No newline at end of file +} diff --git a/xchange-coingi/src/main/java/org/knowm/xchange/coingi/service/CoingiAccountService.java b/xchange-coingi/src/main/java/org/knowm/xchange/coingi/service/CoingiAccountService.java index b8455161014..64da6be566a 100644 --- a/xchange-coingi/src/main/java/org/knowm/xchange/coingi/service/CoingiAccountService.java +++ b/xchange-coingi/src/main/java/org/knowm/xchange/coingi/service/CoingiAccountService.java @@ -101,5 +101,4 @@ public CoingiUserTransactionList getTransactions(TradeHistoryParams p) throws IO throw CoingiErrorAdapter.adapt(e); } } - } diff --git a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/account/TransferHistoryOrder.java b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/account/TransferHistoryOrder.java index 914b4fc40d1..00bfccc6440 100644 --- a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/account/TransferHistoryOrder.java +++ b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/account/TransferHistoryOrder.java @@ -1,5 +1,6 @@ package org.knowm.xchange.coinmate.dto.account; public enum TransferHistoryOrder { - ASC, DESC + ASC, + DESC } diff --git a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/trade/CoinmateTransferHistoryEntry.java b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/trade/CoinmateTransferHistoryEntry.java index f10d6b49655..f2f558954bd 100644 --- a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/trade/CoinmateTransferHistoryEntry.java +++ b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/dto/trade/CoinmateTransferHistoryEntry.java @@ -27,8 +27,7 @@ public CoinmateTransferHistoryEntry( @JsonProperty("walletType") String walletType, @JsonProperty("destination") String destination, @JsonProperty("destinationTag") String destinationTag, - @JsonProperty("txid") String txid - ) { + @JsonProperty("txid") String txid) { this.fee = fee; this.transferType = transferType; this.timestamp = timestamp; @@ -82,5 +81,7 @@ public String getDestinationTag() { return destinationTag; } - public String getTxid() { return txid; } + public String getTxid() { + return txid; + } } diff --git a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountService.java b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountService.java index e268cdb5a7d..59aef3d4051 100644 --- a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountService.java +++ b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountService.java @@ -105,7 +105,14 @@ public String withdrawFunds(Currency currency, BigDecimal amount, String address } else if (currency.equals(Currency.SOL)) { response = coinmateSolanaWithdrawal(amount, address); } else if (currency.equals(Currency.USDT)) { - Long tradeId = coinmateWithdrawVirtualCurrency(amount, address, Currency.USDT.getCurrencyCode(), AmountType.GROSS, FeePriority.HIGH, null); + Long tradeId = + coinmateWithdrawVirtualCurrency( + amount, + address, + Currency.USDT.getCurrencyCode(), + AmountType.GROSS, + FeePriority.HIGH, + null); return Long.toString(tradeId); } else { throw new IOException( @@ -119,7 +126,14 @@ public String withdrawFunds(Currency currency, BigDecimal amount, String address public String withdrawFunds(Currency currency, BigDecimal amount, AddressWithTag address) throws IOException { if (currency.equals(Currency.XRP)) { - Long tradeId = coinmateWithdrawVirtualCurrency(amount, address.getAddress(), currency.getCurrencyCode(), AmountType.GROSS, FeePriority.HIGH, address.getAddressTag()); + Long tradeId = + coinmateWithdrawVirtualCurrency( + amount, + address.getAddress(), + currency.getCurrencyCode(), + AmountType.GROSS, + FeePriority.HIGH, + address.getAddressTag()); return Long.toString(tradeId); } else { return withdrawFunds(currency, amount, address.getAddress()); @@ -132,7 +146,14 @@ public String withdrawFunds(WithdrawFundsParams params) throws IOException { DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; if (defaultParams.getCurrency().equals(Currency.XRP)) { - Long tradeId = coinmateWithdrawVirtualCurrency(defaultParams.getAmount(), defaultParams.getAddress(), defaultParams.getCurrency().getCurrencyCode(), AmountType.GROSS, FeePriority.HIGH, defaultParams.getAddressTag()); + Long tradeId = + coinmateWithdrawVirtualCurrency( + defaultParams.getAmount(), + defaultParams.getAddress(), + defaultParams.getCurrency().getCurrencyCode(), + AmountType.GROSS, + FeePriority.HIGH, + defaultParams.getAddressTag()); return Long.toString(tradeId); } @@ -158,7 +179,8 @@ public String requestDepositAddress(Currency currency, String... args) throws IO } else if (currency.equals(Currency.SOL)) { addresses = coinmateSolanaDepositAddresses(); } else if (currency.equals(Currency.USDT)) { - List addressesAll = coinmateVirtualCurrencyDepositAddresses(currency.getCurrencyCode()); + List addressesAll = + coinmateVirtualCurrencyDepositAddresses(currency.getCurrencyCode()); if (addressesAll.isEmpty()) { return null; } diff --git a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountServiceRaw.java b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountServiceRaw.java index e89d6dd016f..63bb394d48f 100644 --- a/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountServiceRaw.java +++ b/xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/service/CoinmateAccountServiceRaw.java @@ -101,21 +101,20 @@ public Long coinmateWithdrawVirtualCurrency( String currencyName, AmountType amountType, FeePriority feePriority, - String destinationTag - ) + String destinationTag) throws IOException { - CoinmateTradeResponse response =coinmateAuthenticated.withdrawVirtualCurrency( - exchange.getExchangeSpecification().getApiKey(), - exchange.getExchangeSpecification().getUserName(), - signatureCreator, - exchange.getNonceFactory(), - currencyName, - amount, - destinationTag, - amountType, - address, - feePriority - ); + CoinmateTradeResponse response = + coinmateAuthenticated.withdrawVirtualCurrency( + exchange.getExchangeSpecification().getApiKey(), + exchange.getExchangeSpecification().getUserName(), + signatureCreator, + exchange.getNonceFactory(), + currencyName, + amount, + destinationTag, + amountType, + address, + feePriority); throwExceptionIfError(response); @@ -130,8 +129,7 @@ public ArrayList coinmateVirtualCurrencyDepositAddresses(String currency exchange.getExchangeSpecification().getUserName(), signatureCreator, exchange.getNonceFactory(), - currencyName - ); + currencyName); throwExceptionIfError(response); @@ -146,8 +144,7 @@ public List coinmateUnconfirmedVirtualCurrencyDeposits(Stri exchange.getExchangeSpecification().getUserName(), signatureCreator, exchange.getNonceFactory(), - currencyName - ); + currencyName); throwExceptionIfError(response); diff --git a/xchange-core/src/main/java/org/knowm/xchange/dto/account/OpenPosition.java b/xchange-core/src/main/java/org/knowm/xchange/dto/account/OpenPosition.java index 847b44fb45c..8f91a92d6b4 100644 --- a/xchange-core/src/main/java/org/knowm/xchange/dto/account/OpenPosition.java +++ b/xchange-core/src/main/java/org/knowm/xchange/dto/account/OpenPosition.java @@ -45,7 +45,6 @@ public OpenPosition( this.unRealisedPnl = unRealisedPnl; } - @Override public boolean equals(final Object o) { if (this == o) return true; diff --git a/xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java b/xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java index 9d74d0295d2..ec8eb77b271 100644 --- a/xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java +++ b/xchange-core/src/main/java/org/knowm/xchange/dto/marketdata/OrderBook.java @@ -22,17 +22,15 @@ public final class OrderBook implements Serializable { private static final long serialVersionUID = -7788306758114464314L; @JsonIgnore public final StampedLock lock = new StampedLock(); + /** the asks */ - @Getter - private final List asks; + @Getter private final List asks; /** the bids */ - @Getter - private final List bids; + @Getter private final List bids; /** the timestamp of the orderbook according to the exchange's server, null if not provided */ - @Getter - private Date timeStamp; + @Getter private Date timeStamp; /** * Constructor @@ -216,9 +214,9 @@ private boolean recheckIdx(List limitOrders, LimitOrder limitOrder, // if negative, check that of limitOrders.get(reversed idx) limitOrders.get(reversed idx-1) // and is lower and bigger than limitOrder return (limitOrders.get(-idx - 1) == null - || limitOrders.get(-idx - 1).compareTo(limitOrder) <= 0) + || limitOrders.get(-idx - 1).compareTo(limitOrder) <= 0) && (limitOrders.get(-idx - 2) == null - || limitOrders.get(-idx - 2).compareTo(limitOrder) >= 0); + || limitOrders.get(-idx - 2).compareTo(limitOrder) >= 0); } } diff --git a/xchange-core/src/main/java/org/knowm/xchange/dto/meta/ExchangeHealth.java b/xchange-core/src/main/java/org/knowm/xchange/dto/meta/ExchangeHealth.java index 9b1cc0e86d1..c561dbf0f86 100644 --- a/xchange-core/src/main/java/org/knowm/xchange/dto/meta/ExchangeHealth.java +++ b/xchange-core/src/main/java/org/knowm/xchange/dto/meta/ExchangeHealth.java @@ -4,8 +4,6 @@ public enum ExchangeHealth { ONLINE, OFFLINE, - /** - * Can only cancel the order but not place order - */ + /** Can only cancel the order but not place order */ CANCEL_ONLY; } diff --git a/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/ConcurrencyTest.java b/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/ConcurrencyTest.java index 9cbc4364d6d..e6bb0e18329 100644 --- a/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/ConcurrencyTest.java +++ b/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/ConcurrencyTest.java @@ -9,7 +9,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import lombok.var; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.trade.LimitOrder; @@ -20,12 +19,12 @@ public class ConcurrencyTest { static Instrument inst = new CurrencyPair("BTC/USDT"); public static void main(String[] args) throws InterruptedException, ExecutionException { - OrderBook orderBook1 = new OrderBook(new Date(), initOrderBookAsks(), initOrderBookBids(), - true); - OrderBook orderBook2 = new OrderBook(new Date(), initOrderBookAsks(), initOrderBookBids(), - true); - OrderBookOld orderBookOld = new OrderBookOld(new Date(), initOrderBookAsks(), - initOrderBookBids(), true); + OrderBook orderBook1 = + new OrderBook(new Date(), initOrderBookAsks(), initOrderBookBids(), true); + OrderBook orderBook2 = + new OrderBook(new Date(), initOrderBookAsks(), initOrderBookBids(), true); + OrderBookOld orderBookOld = + new OrderBookOld(new Date(), initOrderBookAsks(), initOrderBookBids(), true); ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(50); newWay(orderBook1, executor); executor.awaitTermination(100L, TimeUnit.SECONDS); @@ -35,23 +34,31 @@ public static void main(String[] args) throws InterruptedException, ExecutionExc executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(50); oldOB(orderBookOld, executor); executor.awaitTermination(100L, TimeUnit.SECONDS); - if (orderBook1.getAsks().get(0).getOriginalAmount() - .equals(orderBook2.getAsks().get(0).getOriginalAmount()) - && orderBook1.getAsks().get(0).getOriginalAmount() - .equals(orderBookOld.getAsks().get(0).getOriginalAmount())) { + if (orderBook1 + .getAsks() + .get(0) + .getOriginalAmount() + .equals(orderBook2.getAsks().get(0).getOriginalAmount()) + && orderBook1 + .getAsks() + .get(0) + .getOriginalAmount() + .equals(orderBookOld.getAsks().get(0).getOriginalAmount())) { System.out.println("OrderBooks equals"); } } - private static List initOrderBookAsks() { List asks = new ArrayList<>(); - asks.add(new LimitOrder(OrderType.ASK, new BigDecimal(1), inst, "", new Date(), - new BigDecimal(103))); - asks.add(new LimitOrder(OrderType.ASK, new BigDecimal(1), inst, "", new Date(), - new BigDecimal(102))); - asks.add(new LimitOrder(OrderType.ASK, new BigDecimal(1), inst, "", new Date(), - new BigDecimal(101))); + asks.add( + new LimitOrder( + OrderType.ASK, new BigDecimal(1), inst, "", new Date(), new BigDecimal(103))); + asks.add( + new LimitOrder( + OrderType.ASK, new BigDecimal(1), inst, "", new Date(), new BigDecimal(102))); + asks.add( + new LimitOrder( + OrderType.ASK, new BigDecimal(1), inst, "", new Date(), new BigDecimal(101))); return asks; } @@ -108,10 +115,22 @@ private static void oldOB(OrderBookOld orderBookOld, ThreadPoolExecutor executor public static void updateOrderBook1(OrderBook orderBook, boolean oldWay) { Random rand = new Random(123); for (int i = 0; i < 100000; i++) { - OrderBookUpdate orderBookUpdateAsk = new OrderBookUpdate(OrderType.ASK, new BigDecimal(0), - inst, new BigDecimal(101), new Date(), new BigDecimal(rand.nextInt())); - OrderBookUpdate orderBookUpdateBid = new OrderBookUpdate(OrderType.BID, new BigDecimal(0), - inst, new BigDecimal(99), new Date(), new BigDecimal(rand.nextInt())); + OrderBookUpdate orderBookUpdateAsk = + new OrderBookUpdate( + OrderType.ASK, + new BigDecimal(0), + inst, + new BigDecimal(101), + new Date(), + new BigDecimal(rand.nextInt())); + OrderBookUpdate orderBookUpdateBid = + new OrderBookUpdate( + OrderType.BID, + new BigDecimal(0), + inst, + new BigDecimal(99), + new Date(), + new BigDecimal(rand.nextInt())); if (oldWay) { synchronized (orderBook) { orderBook.update(orderBookUpdateAsk); @@ -127,10 +146,22 @@ public static void updateOrderBook1(OrderBook orderBook, boolean oldWay) { public static void updateOrderBookOld1(OrderBookOld orderBookOld) { Random rand = new Random(123); for (int i = 0; i < 100000; i++) { - OrderBookUpdate orderBookUpdateAsk = new OrderBookUpdate(OrderType.ASK, new BigDecimal(0), - inst, new BigDecimal(101), new Date(), new BigDecimal(rand.nextInt())); - OrderBookUpdate orderBookUpdateBid = new OrderBookUpdate(OrderType.BID, new BigDecimal(0), - inst, new BigDecimal(99), new Date(), new BigDecimal(rand.nextInt())); + OrderBookUpdate orderBookUpdateAsk = + new OrderBookUpdate( + OrderType.ASK, + new BigDecimal(0), + inst, + new BigDecimal(101), + new Date(), + new BigDecimal(rand.nextInt())); + OrderBookUpdate orderBookUpdateBid = + new OrderBookUpdate( + OrderType.BID, + new BigDecimal(0), + inst, + new BigDecimal(99), + new Date(), + new BigDecimal(rand.nextInt())); synchronized (orderBookOld) { orderBookOld.update(orderBookUpdateAsk); orderBookOld.update(orderBookUpdateBid); @@ -141,10 +172,22 @@ public static void updateOrderBookOld1(OrderBookOld orderBookOld) { private static void updateOrderBook2(OrderBook orderBook, boolean oldWay) { Random rand = new Random(123); for (int i = 0; i < 100000; i++) { - LimitOrder bookUpdateAsk = new LimitOrder(OrderType.ASK, new BigDecimal(rand.nextInt()), - inst, "", new Date(), new BigDecimal(101)); - LimitOrder bookUpdateBid = new LimitOrder(OrderType.BID, new BigDecimal(rand.nextInt()), - inst, "", new Date(), new BigDecimal(99)); + LimitOrder bookUpdateAsk = + new LimitOrder( + OrderType.ASK, + new BigDecimal(rand.nextInt()), + inst, + "", + new Date(), + new BigDecimal(101)); + LimitOrder bookUpdateBid = + new LimitOrder( + OrderType.BID, + new BigDecimal(rand.nextInt()), + inst, + "", + new Date(), + new BigDecimal(99)); if (oldWay) { synchronized (orderBook) { orderBook.update(bookUpdateAsk); @@ -160,10 +203,22 @@ private static void updateOrderBook2(OrderBook orderBook, boolean oldWay) { private static void updateOrderBookOld2(OrderBookOld orderBookOld) { Random rand = new Random(123); for (int i = 0; i < 100000; i++) { - LimitOrder bookUpdateAsk = new LimitOrder(OrderType.ASK, new BigDecimal(rand.nextInt()), - inst, "", new Date(), new BigDecimal(101)); - LimitOrder bookUpdateBid = new LimitOrder(OrderType.BID, new BigDecimal(rand.nextInt()), - inst, "", new Date(), new BigDecimal(99)); + LimitOrder bookUpdateAsk = + new LimitOrder( + OrderType.ASK, + new BigDecimal(rand.nextInt()), + inst, + "", + new Date(), + new BigDecimal(101)); + LimitOrder bookUpdateBid = + new LimitOrder( + OrderType.BID, + new BigDecimal(rand.nextInt()), + inst, + "", + new Date(), + new BigDecimal(99)); synchronized (orderBookOld) { orderBookOld.update(bookUpdateAsk); orderBookOld.update(bookUpdateBid); @@ -209,6 +264,4 @@ private static void readOrderBookOld(OrderBookOld orderBookOld) { } } } - } - diff --git a/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/OrderBookOld.java b/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/OrderBookOld.java index 576ef60626a..0d578a95b69 100644 --- a/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/OrderBookOld.java +++ b/xchange-core/src/test/java/org/knowm/xchange/dto/marketdata/OrderBookOld.java @@ -14,267 +14,270 @@ import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.instrument.Instrument; - /** DTO representing the exchange order book */ - public final class OrderBookOld implements Serializable { - - private static final long serialVersionUID = -7788306758114464314L; - - /** the asks */ - private final List asks; - - /** the bids */ - private final List bids; - - /** the timestamp of the orderbook according to the exchange's server, null if not provided */ - private Date timeStamp; - - /** - * Constructor - * - * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if - * not provided - * @param asks The ASK orders - * @param bids The BID orders - */ - @JsonCreator - public OrderBookOld( - @JsonProperty("timeStamp") Date timeStamp, - @JsonProperty("asks") List asks, - @JsonProperty("bids") List bids) { - - this(timeStamp, asks, bids, false); - } +/** DTO representing the exchange order book */ +public final class OrderBookOld implements Serializable { + + private static final long serialVersionUID = -7788306758114464314L; + + /** the asks */ + private final List asks; + + /** the bids */ + private final List bids; + + /** the timestamp of the orderbook according to the exchange's server, null if not provided */ + private Date timeStamp; + + /** + * Constructor + * + * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if + * not provided + * @param asks The ASK orders + * @param bids The BID orders + */ + @JsonCreator + public OrderBookOld( + @JsonProperty("timeStamp") Date timeStamp, + @JsonProperty("asks") List asks, + @JsonProperty("bids") List bids) { + + this(timeStamp, asks, bids, false); + } - /** - * Constructor - * - * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if - * not provided - * @param asks The ASK orders - * @param bids The BID orders - * @param sort True if the asks and bids need to be sorted - */ - public OrderBookOld(Date timeStamp, List asks, List bids, boolean sort) { - - this.timeStamp = timeStamp; - if (sort) { - this.asks = new ArrayList<>(asks); - this.bids = new ArrayList<>(bids); - Collections.sort(this.asks); - Collections.sort(this.bids); - } else { - this.asks = asks; - this.bids = bids; - } + /** + * Constructor + * + * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if + * not provided + * @param asks The ASK orders + * @param bids The BID orders + * @param sort True if the asks and bids need to be sorted + */ + public OrderBookOld(Date timeStamp, List asks, List bids, boolean sort) { + + this.timeStamp = timeStamp; + if (sort) { + this.asks = new ArrayList<>(asks); + this.bids = new ArrayList<>(bids); + Collections.sort(this.asks); + Collections.sort(this.bids); + } else { + this.asks = asks; + this.bids = bids; } + } - /** - * Constructor - * - * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if - * not provided - * @param asks The ASK orders - * @param bids The BID orders - */ - public OrderBookOld(Date timeStamp, Stream asks, Stream bids) { - - this(timeStamp, asks, bids, false); - } + /** + * Constructor + * + * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if + * not provided + * @param asks The ASK orders + * @param bids The BID orders + */ + public OrderBookOld(Date timeStamp, Stream asks, Stream bids) { + + this(timeStamp, asks, bids, false); + } - /** - * Constructor - * - * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if - * not provided - * @param asks The ASK orders - * @param bids The BID orders - * @param sort True if the asks and bids need to be sorted - */ - public OrderBookOld(Date timeStamp, Stream asks, Stream bids, boolean sort) { - - this.timeStamp = timeStamp; - if (sort) { - this.asks = asks.sorted().collect(Collectors.toList()); - this.bids = bids.sorted().collect(Collectors.toList()); - } else { - this.asks = asks.collect(Collectors.toList()); - this.bids = bids.collect(Collectors.toList()); - } + /** + * Constructor + * + * @param timeStamp - the timestamp of the orderbook according to the exchange's server, null if + * not provided + * @param asks The ASK orders + * @param bids The BID orders + * @param sort True if the asks and bids need to be sorted + */ + public OrderBookOld( + Date timeStamp, Stream asks, Stream bids, boolean sort) { + + this.timeStamp = timeStamp; + if (sort) { + this.asks = asks.sorted().collect(Collectors.toList()); + this.bids = bids.sorted().collect(Collectors.toList()); + } else { + this.asks = asks.collect(Collectors.toList()); + this.bids = bids.collect(Collectors.toList()); } + } - // Returns a copy of limitOrder with tradeableAmount replaced. - private static LimitOrder withAmount(LimitOrder limitOrder, BigDecimal tradeableAmount) { + // Returns a copy of limitOrder with tradeableAmount replaced. + private static LimitOrder withAmount(LimitOrder limitOrder, BigDecimal tradeableAmount) { - OrderType type = limitOrder.getType(); - Instrument instrument = limitOrder.getInstrument(); - String id = limitOrder.getId(); - Date date = limitOrder.getTimestamp(); - BigDecimal limit = limitOrder.getLimitPrice(); - return new LimitOrder(type, tradeableAmount, instrument, id, date, limit); - } + OrderType type = limitOrder.getType(); + Instrument instrument = limitOrder.getInstrument(); + String id = limitOrder.getId(); + Date date = limitOrder.getTimestamp(); + BigDecimal limit = limitOrder.getLimitPrice(); + return new LimitOrder(type, tradeableAmount, instrument, id, date, limit); + } - public Date getTimeStamp() { + public Date getTimeStamp() { - return timeStamp; - } + return timeStamp; + } - public List getAsks() { + public List getAsks() { - return asks; - } + return asks; + } - public List getBids() { + public List getBids() { - return bids; - } - - public List getOrders(OrderType type) { + return bids; + } - return type == OrderType.ASK ? asks : bids; - } + public List getOrders(OrderType type) { - /** - * Given a new LimitOrder, it will replace a matching limit order in the orderbook if one is - * found, or add the new LimitOrder if one is not. timeStamp will be updated if the new timestamp - * is non-null and in the future. - * - * @param limitOrder the new LimitOrder - */ - public void update(LimitOrder limitOrder) { - - update(getOrders(limitOrder.getType()), limitOrder); - updateDate(limitOrder.getTimestamp()); - } + return type == OrderType.ASK ? asks : bids; + } - // Replace the amount for limitOrder's price in the provided list. - private void update(List asks, LimitOrder limitOrder) { + /** + * Given a new LimitOrder, it will replace a matching limit order in the orderbook if one is + * found, or add the new LimitOrder if one is not. timeStamp will be updated if the new timestamp + * is non-null and in the future. + * + * @param limitOrder the new LimitOrder + */ + public void update(LimitOrder limitOrder) { + + update(getOrders(limitOrder.getType()), limitOrder); + updateDate(limitOrder.getTimestamp()); + } - int idx = Collections.binarySearch(asks, limitOrder); - if (idx >= 0) { - asks.remove(idx); - } else { - idx = -idx - 1; - } + // Replace the amount for limitOrder's price in the provided list. + private void update(List asks, LimitOrder limitOrder) { - if (limitOrder.getRemainingAmount().compareTo(BigDecimal.ZERO) != 0) { - asks.add(idx, limitOrder); - } + int idx = Collections.binarySearch(asks, limitOrder); + if (idx >= 0) { + asks.remove(idx); + } else { + idx = -idx - 1; } - /** - * Given an OrderBookUpdate, it will replace a matching limit order in the orderbook if one is - * found, or add a new if one is not. timeStamp will be updated if the new timestamp is non-null - * and in the future. - * - * @param orderBookUpdate the new OrderBookUpdate - */ - public void update(OrderBookUpdate orderBookUpdate) { - - LimitOrder limitOrder = orderBookUpdate.getLimitOrder(); - List limitOrders = getOrders(limitOrder.getType()); - int idx = Collections.binarySearch(limitOrders, limitOrder); - if (idx >= 0) { - limitOrders.remove(idx); - } else { - idx = -idx - 1; - } + if (limitOrder.getRemainingAmount().compareTo(BigDecimal.ZERO) != 0) { + asks.add(idx, limitOrder); + } + } - if (orderBookUpdate.getTotalVolume().compareTo(BigDecimal.ZERO) != 0) { - LimitOrder updatedOrder = withAmount(limitOrder, orderBookUpdate.getTotalVolume()); - limitOrders.add(idx, updatedOrder); - } + /** + * Given an OrderBookUpdate, it will replace a matching limit order in the orderbook if one is + * found, or add a new if one is not. timeStamp will be updated if the new timestamp is non-null + * and in the future. + * + * @param orderBookUpdate the new OrderBookUpdate + */ + public void update(OrderBookUpdate orderBookUpdate) { + + LimitOrder limitOrder = orderBookUpdate.getLimitOrder(); + List limitOrders = getOrders(limitOrder.getType()); + int idx = Collections.binarySearch(limitOrders, limitOrder); + if (idx >= 0) { + limitOrders.remove(idx); + } else { + idx = -idx - 1; + } - updateDate(limitOrder.getTimestamp()); + if (orderBookUpdate.getTotalVolume().compareTo(BigDecimal.ZERO) != 0) { + LimitOrder updatedOrder = withAmount(limitOrder, orderBookUpdate.getTotalVolume()); + limitOrders.add(idx, updatedOrder); } - // Replace timeStamp if the provided date is non-null and in the future - // TODO should this raise an exception if the order timestamp is in the past? - private void updateDate(Date updateDate) { + updateDate(limitOrder.getTimestamp()); + } + + // Replace timeStamp if the provided date is non-null and in the future + // TODO should this raise an exception if the order timestamp is in the past? + private void updateDate(Date updateDate) { - if (updateDate != null && (timeStamp == null || updateDate.after(timeStamp))) { - this.timeStamp = updateDate; - } + if (updateDate != null && (timeStamp == null || updateDate.after(timeStamp))) { + this.timeStamp = updateDate; } + } - @Override - public int hashCode() { + @Override + public int hashCode() { - int hash = 17; - hash = 31 * hash + (this.timeStamp != null ? this.timeStamp.hashCode() : 0); - for (LimitOrder order : this.bids) { - hash = 31 * hash + order.hashCode(); - } - for (LimitOrder order : this.asks) { - hash = 31 * hash + order.hashCode(); - } - return hash; + int hash = 17; + hash = 31 * hash + (this.timeStamp != null ? this.timeStamp.hashCode() : 0); + for (LimitOrder order : this.bids) { + hash = 31 * hash + order.hashCode(); + } + for (LimitOrder order : this.asks) { + hash = 31 * hash + order.hashCode(); } + return hash; + } - @Override - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final org.knowm.xchange.dto.marketdata.OrderBookOld other = (org.knowm.xchange.dto.marketdata.OrderBookOld) obj; - if (this.timeStamp == null - ? other.timeStamp != null - : !this.timeStamp.equals(other.timeStamp)) { - return false; - } - if (this.bids.size() != other.bids.size()) { - return false; - } - for (int index = 0; index < this.bids.size(); index++) { - if (!this.bids.get(index).equals(other.bids.get(index))) { - return false; - } - } - if (this.asks.size() != other.asks.size()) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final org.knowm.xchange.dto.marketdata.OrderBookOld other = + (org.knowm.xchange.dto.marketdata.OrderBookOld) obj; + if (this.timeStamp == null + ? other.timeStamp != null + : !this.timeStamp.equals(other.timeStamp)) { + return false; + } + if (this.bids.size() != other.bids.size()) { + return false; + } + for (int index = 0; index < this.bids.size(); index++) { + if (!this.bids.get(index).equals(other.bids.get(index))) { return false; } - for (int index = 0; index < this.asks.size(); index++) { - if (!this.asks.get(index).equals(other.asks.get(index))) { - return false; - } - } - return true; } - - /** - * Identical to {@link #equals(Object) equals} method except that this ignores different - * timestamps. In other words, this version of equals returns true if the order internal to the - * OrderBooks are equal but their timestamps are unequal. It returns false if any order between - * the two are different. - * - * @param ob - * @return - */ - public boolean ordersEqual(org.knowm.xchange.dto.marketdata.OrderBook ob) { - - if (ob == null) { + if (this.asks.size() != other.asks.size()) { + return false; + } + for (int index = 0; index < this.asks.size(); index++) { + if (!this.asks.get(index).equals(other.asks.get(index))) { return false; } - - Date timestamp = new Date(); - org.knowm.xchange.dto.marketdata.OrderBook thisOb = new org.knowm.xchange.dto.marketdata.OrderBook(timestamp, this.getAsks(), this.getBids()); - org.knowm.xchange.dto.marketdata.OrderBook thatOb = new org.knowm.xchange.dto.marketdata.OrderBook(timestamp, ob.getAsks(), ob.getBids()); - return thisOb.equals(thatOb); } + return true; + } - @Override - public String toString() { - - return "OrderBook [timestamp: " - + timeStamp - + ", asks=" - + asks.toString() - + ", bids=" - + bids.toString() - + "]"; + /** + * Identical to {@link #equals(Object) equals} method except that this ignores different + * timestamps. In other words, this version of equals returns true if the order internal to the + * OrderBooks are equal but their timestamps are unequal. It returns false if any order between + * the two are different. + * + * @param ob + * @return + */ + public boolean ordersEqual(org.knowm.xchange.dto.marketdata.OrderBook ob) { + + if (ob == null) { + return false; } + + Date timestamp = new Date(); + org.knowm.xchange.dto.marketdata.OrderBook thisOb = + new org.knowm.xchange.dto.marketdata.OrderBook(timestamp, this.getAsks(), this.getBids()); + org.knowm.xchange.dto.marketdata.OrderBook thatOb = + new org.knowm.xchange.dto.marketdata.OrderBook(timestamp, ob.getAsks(), ob.getBids()); + return thisOb.equals(thatOb); } + @Override + public String toString() { + + return "OrderBook [timestamp: " + + timeStamp + + ", asks=" + + asks.toString() + + ", bids=" + + bids.toString() + + "]"; + } +} diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/binance/marketdata/BinanceMarketDataDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/binance/marketdata/BinanceMarketDataDemo.java index 80430ec2774..8acbb593246 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/binance/marketdata/BinanceMarketDataDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/binance/marketdata/BinanceMarketDataDemo.java @@ -44,7 +44,9 @@ public static void raw(BinanceExchange exchange, BinanceMarketDataService market tickers.forEach( t -> System.out.println( - t.getCurrencyPair() + " => " + String.format("%+.2f%%", t.getPriceChangePercent()))); + t.getCurrencyPair() + + " => " + + String.format("%+.2f%%", t.getPriceChangePercent()))); System.out.println("raw out end"); } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/Gateio.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/Gateio.java index df71bd93c89..431ecef56a4 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/Gateio.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/Gateio.java @@ -24,38 +24,32 @@ public interface Gateio { @Path("spot/time") GateioServerTime getServerTime() throws IOException, GateioException; - @GET @Path("spot/currencies") List getCurrencies() throws IOException, GateioException; - @GET @Path("spot/order_book") GateioOrderBook getOrderBook( - @QueryParam("currency_pair") String currencyPair, - @QueryParam("with_id") Boolean withId - ) throws IOException, GateioException; - + @QueryParam("currency_pair") String currencyPair, @QueryParam("with_id") Boolean withId) + throws IOException, GateioException; @GET @Path("wallet/currency_chains") - List getCurrencyChains(@QueryParam("currency") String currency) throws IOException, GateioException; - + List getCurrencyChains(@QueryParam("currency") String currency) + throws IOException, GateioException; @GET @Path("spot/currency_pairs") List getCurrencyPairDetails() throws IOException, GateioException; - @GET @Path("spot/currency_pairs/{currency_pair}") - GateioCurrencyPairDetails getCurrencyPairDetails(@PathParam("currency_pair") String currencyPair) throws IOException, GateioException; - + GateioCurrencyPairDetails getCurrencyPairDetails(@PathParam("currency_pair") String currencyPair) + throws IOException, GateioException; @GET @Path("spot/tickers") - List getTickers(@QueryParam("currency_pair") String currencyPair) throws IOException, GateioException; - - + List getTickers(@QueryParam("currency_pair") String currencyPair) + throws IOException, GateioException; } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioAdapters.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioAdapters.java index 8cfa3ae57fd..9a29de2a953 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioAdapters.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioAdapters.java @@ -29,38 +29,52 @@ import org.knowm.xchange.gateio.service.params.GateioWithdrawFundsParams; import org.knowm.xchange.instrument.Instrument; - @UtilityClass public class GateioAdapters { - public String toString(Instrument instrument) { if (instrument == null) { return null; - } - else { - return String.format("%s_%s", - instrument.getBase().getCurrencyCode(), - instrument.getCounter().getCurrencyCode()) - .toUpperCase(Locale.ROOT); + } else { + return String.format( + "%s_%s", + instrument.getBase().getCurrencyCode(), instrument.getCounter().getCurrencyCode()) + .toUpperCase(Locale.ROOT); } } - public OrderBook toOrderBook(GateioOrderBook gateioOrderBook, Instrument instrument) { - List asks = gateioOrderBook.getAsks().stream() - .map(priceSizeEntry -> new LimitOrder(OrderType.ASK, priceSizeEntry.getSize(), instrument, null, null, priceSizeEntry.getPrice())) - .collect(Collectors.toList()); - - List bids = gateioOrderBook.getBids().stream() - .map(priceSizeEntry -> new LimitOrder(OrderType.BID, priceSizeEntry.getSize(), instrument, null, null, priceSizeEntry.getPrice())) - .collect(Collectors.toList()); + List asks = + gateioOrderBook.getAsks().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.ASK, + priceSizeEntry.getSize(), + instrument, + null, + null, + priceSizeEntry.getPrice())) + .collect(Collectors.toList()); + + List bids = + gateioOrderBook.getBids().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.BID, + priceSizeEntry.getSize(), + instrument, + null, + null, + priceSizeEntry.getPrice())) + .collect(Collectors.toList()); return new OrderBook(Date.from(gateioOrderBook.getGeneratedAt()), asks, bids); } - - public InstrumentMetaData toInstrumentMetaData(GateioCurrencyPairDetails gateioCurrencyPairDetails) { + public InstrumentMetaData toInstrumentMetaData( + GateioCurrencyPairDetails gateioCurrencyPairDetails) { return new InstrumentMetaData.Builder() .tradingFee(gateioCurrencyPairDetails.getFee()) .minimumAmount(gateioCurrencyPairDetails.getMinAssetAmount()) @@ -70,7 +84,6 @@ public InstrumentMetaData toInstrumentMetaData(GateioCurrencyPairDetails gateioC .build(); } - public String toString(OrderStatus orderStatus) { switch (orderStatus) { case OPEN: @@ -82,7 +95,6 @@ public String toString(OrderStatus orderStatus) { } } - public OrderStatus toOrderStatus(String gateioOrderStatus) { switch (gateioOrderStatus) { case "open": @@ -98,7 +110,6 @@ public OrderStatus toOrderStatus(String gateioOrderStatus) { } } - public GateioOrder toGateioOrder(MarketOrder marketOrder) { return GateioOrder.builder() .currencyPair((CurrencyPair) marketOrder.getInstrument()) @@ -111,7 +122,6 @@ public GateioOrder toGateioOrder(MarketOrder marketOrder) { .build(); } - public GateioOrder toGateioOrder(LimitOrder limitOrder) { return GateioOrder.builder() .currencyPair((CurrencyPair) limitOrder.getInstrument()) @@ -125,7 +135,6 @@ public GateioOrder toGateioOrder(LimitOrder limitOrder) { .build(); } - public Order toOrder(GateioOrder gateioOrder) { Order.Builder builder; Instrument instrument = gateioOrder.getCurrencyPair(); @@ -136,8 +145,7 @@ public Order toOrder(GateioOrder gateioOrder) { builder = new MarketOrder.Builder(orderType, instrument); break; case "limit": - builder = new LimitOrder.Builder(orderType, instrument) - .limitPrice(gateioOrder.getPrice()); + builder = new LimitOrder.Builder(orderType, instrument).limitPrice(gateioOrder.getPrice()); break; default: throw new IllegalArgumentException("Can't map " + gateioOrder.getType()); @@ -145,12 +153,13 @@ public Order toOrder(GateioOrder gateioOrder) { if (orderType == OrderType.BID) { builder.cumulativeAmount(gateioOrder.getFilledTotalQuote()); - } - else if (orderType == OrderType.ASK) { - BigDecimal filledAssetAmount = gateioOrder.getFilledTotalQuote().divide(gateioOrder.getAvgDealPrice(), MathContext.DECIMAL32); + } else if (orderType == OrderType.ASK) { + BigDecimal filledAssetAmount = + gateioOrder + .getFilledTotalQuote() + .divide(gateioOrder.getAvgDealPrice(), MathContext.DECIMAL32); builder.cumulativeAmount(filledAssetAmount); - } - else { + } else { throw new IllegalArgumentException("Can't map " + orderType); } @@ -165,16 +174,21 @@ else if (orderType == OrderType.ASK) { .build(); } - public UserTrade toUserTrade(GateioUserTradeRaw gateioUserTradeRaw) { - return new GateioUserTrade(gateioUserTradeRaw.getSide(), gateioUserTradeRaw.getAmount(), gateioUserTradeRaw.getCurrencyPair(), - gateioUserTradeRaw.getPrice(), Date.from(gateioUserTradeRaw.getTimeMs()), String.valueOf( - gateioUserTradeRaw.getId()), - String.valueOf(gateioUserTradeRaw.getOrderId()), gateioUserTradeRaw.getFee(), gateioUserTradeRaw.getFeeCurrency(), - gateioUserTradeRaw.getRemark(), gateioUserTradeRaw.getRole()); + return new GateioUserTrade( + gateioUserTradeRaw.getSide(), + gateioUserTradeRaw.getAmount(), + gateioUserTradeRaw.getCurrencyPair(), + gateioUserTradeRaw.getPrice(), + Date.from(gateioUserTradeRaw.getTimeMs()), + String.valueOf(gateioUserTradeRaw.getId()), + String.valueOf(gateioUserTradeRaw.getOrderId()), + gateioUserTradeRaw.getFee(), + gateioUserTradeRaw.getFeeCurrency(), + gateioUserTradeRaw.getRemark(), + gateioUserTradeRaw.getRole()); } - public GateioWithdrawalRequest toGateioWithdrawalRequest(GateioWithdrawFundsParams p) { return GateioWithdrawalRequest.builder() .clientRecordId(p.getClientRecordId()) @@ -184,25 +198,22 @@ public GateioWithdrawalRequest toGateioWithdrawalRequest(GateioWithdrawFundsPara .amount(p.getAmount()) .currency(p.getCurrency()) .build(); - } - public Ticker toTicker(GateioTicker gateioTicker) { return new Ticker.Builder() - .instrument(gateioTicker.getCurrencyPair()) - .last(gateioTicker.getLastPrice()) - .bid(gateioTicker.getHighestBid()) - .ask(gateioTicker.getLowestAsk()) - .high(gateioTicker.getMaxPrice24h()) - .low(gateioTicker.getMinPrice24h()) - .volume(gateioTicker.getAssetVolume()) - .quoteVolume(gateioTicker.getQuoteVolume()) - .percentageChange(gateioTicker.getChangePercentage24h()) - .build(); + .instrument(gateioTicker.getCurrencyPair()) + .last(gateioTicker.getLastPrice()) + .bid(gateioTicker.getHighestBid()) + .ask(gateioTicker.getLowestAsk()) + .high(gateioTicker.getMaxPrice24h()) + .low(gateioTicker.getMinPrice24h()) + .volume(gateioTicker.getAssetVolume()) + .quoteVolume(gateioTicker.getQuoteVolume()) + .percentageChange(gateioTicker.getChangePercentage24h()) + .build(); } - public FundingRecord toFundingRecords(GateioAccountBookRecord gateioAccountBookRecord) { return new FundingRecord.Builder() .setInternalId(gateioAccountBookRecord.getId()) diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioErrorAdapter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioErrorAdapter.java index 9778ce96da1..da730a16a0a 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioErrorAdapter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioErrorAdapter.java @@ -25,7 +25,6 @@ public class GateioErrorAdapter { public final String INVALID_PARAM_VALUE = "INVALID_PARAM_VALUE"; public final String SERVER_ERROR = "SERVER_ERROR"; - public ExchangeException adapt(GateioException e) { switch (e.getLabel()) { @@ -51,15 +50,12 @@ public ExchangeException adapt(GateioException e) { case INVALID_PARAM_VALUE: if (e.getMessage().contains("below minimum") || e.getMessage().contains("too small")) { return new OrderAmountUnderMinimumException(e.getMessage(), e); - } - else { + } else { return new OrderNotValidException(e.getMessage(), e); } default: return new ExchangeException(e.getMessage(), e); } - } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioExchange.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioExchange.java index 5225fbab925..dd0fa22eb18 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioExchange.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioExchange.java @@ -1,5 +1,8 @@ package org.knowm.xchange.gateio; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeUnit; import org.knowm.xchange.BaseExchange; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.dto.meta.ExchangeMetaData; @@ -11,14 +14,10 @@ import org.knowm.xchange.utils.nonce.CurrentTimeIncrementalNonceFactory; import si.mazi.rescu.SynchronizedValueFactory; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.TimeUnit; - public class GateioExchange extends BaseExchange { - private final SynchronizedValueFactory nonceFactory = new CurrentTimeIncrementalNonceFactory(TimeUnit.SECONDS); - + private final SynchronizedValueFactory nonceFactory = + new CurrentTimeIncrementalNonceFactory(TimeUnit.SECONDS); @Override protected void initServices() { @@ -43,10 +42,10 @@ public SynchronizedValueFactory getNonceFactory() { return nonceFactory; } - @Override public void remoteInit() throws IOException { - Map instruments = ((GateioMarketDataService) marketDataService).getMetaDataByInstrument(); + Map instruments = + ((GateioMarketDataService) marketDataService).getMetaDataByInstrument(); exchangeMetaData = new ExchangeMetaData(instruments, null, null, null, null); } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioV4Authenticated.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioV4Authenticated.java index 84ad6bc5b18..77f5603e4a3 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioV4Authenticated.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/GateioV4Authenticated.java @@ -37,9 +37,8 @@ GateioDepositAddress getDepositAddress( @HeaderParam("KEY") String apiKey, @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, - @QueryParam("currency") String currency - ) throws IOException, GateioException; - + @QueryParam("currency") String currency) + throws IOException, GateioException; @GET @Path("wallet/withdraw_status") @@ -47,9 +46,8 @@ List getWithdrawStatus( @HeaderParam("KEY") String apiKey, @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, - @QueryParam("currency") String currency - ) throws IOException, GateioException; - + @QueryParam("currency") String currency) + throws IOException, GateioException; @GET @Path("spot/accounts") @@ -57,9 +55,8 @@ List getSpotAccounts( @HeaderParam("KEY") String apiKey, @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, - @QueryParam("currency") String currency - ) throws IOException, GateioException; - + @QueryParam("currency") String currency) + throws IOException, GateioException; @GET @Path("spot/account_book") @@ -72,9 +69,8 @@ List getAccountBookRecords( @QueryParam("to") Long to, @QueryParam("limit") Integer pageLength, @QueryParam("page") Integer pageNumber, - @QueryParam("type") String type - ) throws IOException, GateioException; - + @QueryParam("type") String type) + throws IOException, GateioException; @GET @Path("spot/orders") @@ -83,9 +79,8 @@ List listOrders( @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, @QueryParam("currency_pair") String currencyPair, - @QueryParam("status") String status - ) throws IOException, GateioException; - + @QueryParam("status") String status) + throws IOException, GateioException; @GET @Path("spot/orders/{order_id}") @@ -94,9 +89,8 @@ GateioOrder getOrder( @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, @PathParam("order_id") String orderId, - @QueryParam("currency_pair") String currencyPair - ) throws IOException, GateioException; - + @QueryParam("currency_pair") String currencyPair) + throws IOException, GateioException; @DELETE @Path("spot/orders/{order_id}") @@ -105,9 +99,8 @@ GateioOrder cancelOrder( @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, @PathParam("order_id") String orderId, - @QueryParam("currency_pair") String currencyPair - ) throws IOException, GateioException; - + @QueryParam("currency_pair") String currencyPair) + throws IOException, GateioException; @POST @Path("spot/orders") @@ -116,9 +109,8 @@ GateioOrder createOrder( @HeaderParam("KEY") String apiKey, @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, - GateioOrder gateioOrder - ) throws IOException, GateioException; - + GateioOrder gateioOrder) + throws IOException, GateioException; @GET @Path("spot/my_trades") @@ -132,9 +124,8 @@ List getTradingHistory( @QueryParam("order_id") String orderId, @QueryParam("account") String account, @QueryParam("from") Long from, - @QueryParam("to") Long to - ) throws IOException, GateioException; - + @QueryParam("to") Long to) + throws IOException, GateioException; @GET @Path("wallet/saved_address") @@ -142,9 +133,8 @@ List getSavedAddresses( @HeaderParam("KEY") String apiKey, @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, - @QueryParam("currency") String currency - ) throws IOException, GateioException; - + @QueryParam("currency") String currency) + throws IOException, GateioException; @GET @Path("wallet/sub_account_transfers") @@ -156,9 +146,8 @@ List getSubAccountTransfers( @QueryParam("from") Long from, @QueryParam("to") Long to, @QueryParam("limit") Integer pageLength, - @QueryParam("offset") Integer zeroBasedPageNumber - ) throws IOException, GateioException; - + @QueryParam("offset") Integer zeroBasedPageNumber) + throws IOException, GateioException; @GET @Path("wallet/withdrawals") @@ -170,9 +159,8 @@ List getWithdrawals( @QueryParam("from") Long from, @QueryParam("to") Long to, @QueryParam("limit") Integer pageLength, - @QueryParam("offset") Integer zeroBasedPageNumber - ) throws IOException, GateioException; - + @QueryParam("offset") Integer zeroBasedPageNumber) + throws IOException, GateioException; @GET @Path("wallet/deposits") @@ -184,9 +172,8 @@ List getDeposits( @QueryParam("from") Long from, @QueryParam("to") Long to, @QueryParam("limit") Integer pageLength, - @QueryParam("offset") Integer zeroBasedPageNumber - ) throws IOException, GateioException; - + @QueryParam("offset") Integer zeroBasedPageNumber) + throws IOException, GateioException; @POST @Path("withdrawals") @@ -195,8 +182,6 @@ GateioWithdrawalRecord withdraw( @HeaderParam("KEY") String apiKey, @HeaderParam("Timestamp") SynchronizedValueFactory timestamp, @HeaderParam("SIGN") ParamsDigest signer, - GateioWithdrawalRequest gateioWithdrawalRequest - ) throws IOException, GateioException; - - + GateioWithdrawalRequest gateioWithdrawalRequest) + throws IOException, GateioException; } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/Config.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/Config.java index fb9de0bfe5e..758375a0bd6 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/Config.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/Config.java @@ -21,5 +21,4 @@ private Config() { public static Config getInstance() { return instance; } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/CurrencyPairToStringConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/CurrencyPairToStringConverter.java index de64a9e0dab..42e42007b71 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/CurrencyPairToStringConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/CurrencyPairToStringConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.currency.CurrencyPair; -/** - * Converts {@code CurrencyPair} to string - */ +/** Converts {@code CurrencyPair} to string */ public class CurrencyPairToStringConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/DoubleToInstantConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/DoubleToInstantConverter.java index fe2a7078702..af4fe31e88b 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/DoubleToInstantConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/DoubleToInstantConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import java.time.Instant; -/** - * Converts timestamp as double in milliseconds to {@code Instant} - */ +/** Converts timestamp as double in milliseconds to {@code Instant} */ public class DoubleToInstantConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/OrderTypeToStringConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/OrderTypeToStringConverter.java index 9fa46e700eb..a1fd9b252ef 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/OrderTypeToStringConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/OrderTypeToStringConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.dto.Order.OrderType; -/** - * Converts {@code OrderType} to string - */ +/** Converts {@code OrderType} to string */ public class OrderTypeToStringConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToBooleanConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToBooleanConverter.java index 2cb8ae6738a..83a5e001424 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToBooleanConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToBooleanConverter.java @@ -2,9 +2,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; -/** - * Converts string value "1" to {@code true}, rest to {@code false} - */ +/** Converts string value "1" to {@code true}, rest to {@code false} */ public class StringToBooleanConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyConverter.java index a6445b19cbb..3e0cfbdc6a4 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.currency.Currency; -/** - * Converts string value {@code Currency} - */ +/** Converts string value {@code Currency} */ public class StringToCurrencyConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyPairConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyPairConverter.java index a9b4cf104de..8d5a000111c 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyPairConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToCurrencyPairConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.currency.CurrencyPair; -/** - * Converts string to {@code CurrencyPair} - */ +/** Converts string to {@code CurrencyPair} */ public class StringToCurrencyPairConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToOrderTypeConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToOrderTypeConverter.java index 418888c54c0..943f7175cfa 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToOrderTypeConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/StringToOrderTypeConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import org.knowm.xchange.dto.Order.OrderType; -/** - * Converts string to {@code OrderType} - */ +/** Converts string to {@code OrderType} */ public class StringToOrderTypeConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/TimestampSecondsToInstantConverter.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/TimestampSecondsToInstantConverter.java index a4142f1f0ae..cb65e2c3db7 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/TimestampSecondsToInstantConverter.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/config/converter/TimestampSecondsToInstantConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import java.time.Instant; -/** - * Converts timestamp in seconds to {@code Instant} - */ +/** Converts timestamp in seconds to {@code Instant} */ public class TimestampSecondsToInstantConverter extends StdConverter { @Override diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/GateioException.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/GateioException.java index e87b1a2dcd0..fd3821cf086 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/GateioException.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/GateioException.java @@ -15,5 +15,4 @@ public class GateioException extends RuntimeException { @JsonProperty("message") String message; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAccountBookRecord.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAccountBookRecord.java index 47f6ce16e8f..f9a55f626e2 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAccountBookRecord.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAccountBookRecord.java @@ -36,7 +36,6 @@ public class GateioAccountBookRecord { @JsonProperty("type") String typeDescription; - public FundingRecord.Type getType() { switch (typeDescription) { case "withdraw": @@ -47,6 +46,4 @@ public FundingRecord.Type getType() { return change.signum() > 0 ? Type.OTHER_INFLOW : Type.OTHER_OUTFLOW; } } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAddressRecord.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAddressRecord.java index 029fe1f9556..4386c519db3 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAddressRecord.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioAddressRecord.java @@ -33,5 +33,4 @@ public class GateioAddressRecord { @JsonProperty("verified") @JsonDeserialize(converter = StringToBooleanConverter.class) Boolean verified; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioCurrencyBalance.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioCurrencyBalance.java index 0b15a5a8d24..996a2048f4a 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioCurrencyBalance.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioCurrencyBalance.java @@ -23,5 +23,4 @@ public class GateioCurrencyBalance { @JsonProperty("locked") BigDecimal locked; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositAddress.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositAddress.java index 25eaf92343d..736f77fe2dd 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositAddress.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositAddress.java @@ -21,7 +21,6 @@ public class GateioDepositAddress { @JsonProperty("multichain_addresses") List multichainAddresses; - @Data @Builder @Jacksonized @@ -41,8 +40,5 @@ public static class MultichainAddress { @JsonProperty("obtain_failed") Boolean failed; - } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositRecord.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositRecord.java index bc039679da2..111a9cf8b72 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositRecord.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioDepositRecord.java @@ -50,7 +50,6 @@ public class GateioDepositRecord { @JsonProperty("chain") String chain; - @Getter @AllArgsConstructor public static enum Status { @@ -69,7 +68,5 @@ public static enum Status { SPLITPEND("the order is automatically split due to large amount"); private final String description; - } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioOrder.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioOrder.java index e655a618f2f..e5e228add2b 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioOrder.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioOrder.java @@ -120,5 +120,4 @@ public class GateioOrder { @JsonProperty("finish_as") String finishAs; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioSubAccountTransfer.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioSubAccountTransfer.java index f8a203174ff..3289fb15725 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioSubAccountTransfer.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioSubAccountTransfer.java @@ -44,5 +44,4 @@ public class GateioSubAccountTransfer { @JsonProperty("sub_account_type") String subAccountType; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawStatus.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawStatus.java index befd5c281e8..dd04e637261 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawStatus.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawStatus.java @@ -50,12 +50,11 @@ public class GateioWithdrawStatus { @JsonProperty("withdraw_fix_on_chains") Map withdrawFeeByChain; - /** * @return withdraw rate converted from percentage */ public BigDecimal getWithdrawRate() { - return new BigDecimal(StringUtils.removeEnd(withdrawPercent, "%")).multiply(new BigDecimal("0.01")); + return new BigDecimal(StringUtils.removeEnd(withdrawPercent, "%")) + .multiply(new BigDecimal("0.01")); } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRecord.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRecord.java index c199e49ecfb..6a14c9a8833 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRecord.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRecord.java @@ -53,7 +53,6 @@ public class GateioWithdrawalRecord { @JsonProperty("fee") BigDecimal fee; - @Getter @AllArgsConstructor public static enum Status { @@ -72,7 +71,5 @@ public static enum Status { SPLITPEND("the order is automatically split due to large amount"); private final String description; - } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRequest.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRequest.java index 8c4afd3e3d5..0486d74afbd 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRequest.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/GateioWithdrawalRequest.java @@ -29,5 +29,4 @@ public class GateioWithdrawalRequest { @JsonProperty("chain") String chain; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/params/GateioSubAccountTransfersParams.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/params/GateioSubAccountTransfersParams.java index d2f19ad882a..6ccebe5423f 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/params/GateioSubAccountTransfersParams.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/account/params/GateioSubAccountTransfersParams.java @@ -17,5 +17,4 @@ public class GateioSubAccountTransfersParams { private Instant startTime; private Instant endTime; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChain.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChain.java index aa0d4fdb4be..2e89500f8c5 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChain.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChain.java @@ -42,6 +42,4 @@ public boolean isDepositEnabled() { public boolean isEnabled() { return (disabled != null) && !disabled; } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfo.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfo.java index 7a66bda9bcb..e142c1eea81 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfo.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfo.java @@ -31,14 +31,11 @@ public class GateioCurrencyInfo { @JsonProperty("chain") String chain; - public boolean isWithdrawEnabled() { return (withdrawDisabled != null) && !withdrawDisabled; } - public boolean isDepositEnabled() { return (depositDisabled != null) && !depositDisabled; } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyPairDetails.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyPairDetails.java index d3438f52240..a181b923e2d 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyPairDetails.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyPairDetails.java @@ -48,5 +48,4 @@ public class GateioCurrencyPairDetails { @JsonProperty("buy_start") @JsonDeserialize(converter = TimestampSecondsToInstantConverter.class) Instant startOfBuys; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioOrderBook.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioOrderBook.java index e55129efc68..38e6af6e666 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioOrderBook.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioOrderBook.java @@ -29,7 +29,6 @@ public class GateioOrderBook { @JsonProperty("bids") List bids; - @Data @Builder @Jacksonized @@ -39,7 +38,5 @@ public static class PriceSizeEntry { BigDecimal price; BigDecimal size; - } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioServerTime.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioServerTime.java index 8ca9c3b9c7f..4c520f2e6dd 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioServerTime.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioServerTime.java @@ -13,5 +13,4 @@ public class GateioServerTime { @JsonProperty("server_time") Instant time; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioTicker.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioTicker.java index 209a3e1bca9..47098b570d6 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioTicker.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/marketdata/GateioTicker.java @@ -60,5 +60,4 @@ public class GateioTicker { @JsonProperty("etf_leverage") BigDecimal etfLeverage; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTrade.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTrade.java index 7e5ffe5902f..72b46bd3be0 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTrade.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTrade.java @@ -14,27 +14,41 @@ public class GateioUserTrade extends UserTrade { Role role; /** - * @param type The trade type (BID side or ASK side) - * @param originalAmount The depth of this trade - * @param instrument The exchange identifier (e.g. "BTC/USD") - * @param price The price (either the bid or the ask) - * @param timestamp The timestamp of the trade - * @param id The id of the trade - * @param orderId The id of the order responsible for execution of this trade - * @param feeAmount The fee that was charged by the exchange for this trade - * @param feeCurrency The symbol of the currency in which the fee was charged + * @param type The trade type (BID side or ASK side) + * @param originalAmount The depth of this trade + * @param instrument The exchange identifier (e.g. "BTC/USD") + * @param price The price (either the bid or the ask) + * @param timestamp The timestamp of the trade + * @param id The id of the trade + * @param orderId The id of the order responsible for execution of this trade + * @param feeAmount The fee that was charged by the exchange for this trade + * @param feeCurrency The symbol of the currency in which the fee was charged * @param orderUserReference The id that the user has insert to the trade - * @param role Trade role + * @param role Trade role */ - public GateioUserTrade(OrderType type, - BigDecimal originalAmount, Instrument instrument, - BigDecimal price, Date timestamp, String id, String orderId, - BigDecimal feeAmount, Currency feeCurrency, - String orderUserReference, Role role) { - super(type, originalAmount, instrument, price, timestamp, id, orderId, feeAmount, feeCurrency, + public GateioUserTrade( + OrderType type, + BigDecimal originalAmount, + Instrument instrument, + BigDecimal price, + Date timestamp, + String id, + String orderId, + BigDecimal feeAmount, + Currency feeCurrency, + String orderUserReference, + Role role) { + super( + type, + originalAmount, + instrument, + price, + timestamp, + id, + orderId, + feeAmount, + feeCurrency, orderUserReference); this.role = role; } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTradeRaw.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTradeRaw.java index e0a67fd79e2..0fe8a95260c 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTradeRaw.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/GateioUserTradeRaw.java @@ -70,5 +70,4 @@ public class GateioUserTradeRaw { @JsonProperty("amend_text") String remark; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/Role.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/Role.java index db867b5f499..2c41d97ec82 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/Role.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/dto/trade/Role.java @@ -10,8 +10,5 @@ public enum Role { TAKER("taker"), MAKER("maker"); - @JsonValue - private final String value; - - + @JsonValue private final String value; } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountService.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountService.java index 9b79d7b0dff..9b148434f1a 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountService.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountService.java @@ -26,35 +26,32 @@ public GateioAccountService(GateioExchange exchange) { super(exchange); } - @Override public AccountInfo getAccountInfo() throws IOException { try { List spotBalances = getSpotBalances(null); - List balances = spotBalances.stream() - .map(balance -> new Balance.Builder() - .currency(balance.getCurrency()) - .available(balance.getAvailable()) - .frozen(balance.getLocked()) - .build()) - .collect(Collectors.toList()); + List balances = + spotBalances.stream() + .map( + balance -> + new Balance.Builder() + .currency(balance.getCurrency()) + .available(balance.getAvailable()) + .frozen(balance.getLocked()) + .build()) + .collect(Collectors.toList()); - Wallet wallet = Wallet.Builder - .from(balances) - .id("spot") - .build(); + Wallet wallet = Wallet.Builder.from(balances).id("spot").build(); return new AccountInfo(wallet); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - @Override public String withdrawFunds(WithdrawFundsParams params) throws IOException { Validate.isInstanceOf(GateioWithdrawFundsParams.class, params); @@ -65,21 +62,18 @@ public String withdrawFunds(WithdrawFundsParams params) throws IOException { try { GateioWithdrawalRecord gateioWithdrawalRecord = withdraw(gateioWithdrawalRequest); return gateioWithdrawalRecord.getId(); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - @Override public List getFundingHistory(TradeHistoryParams params) throws IOException { try { return getAccountBookRecords(params).stream() .map(GateioAdapters::toFundingRecords) .collect(Collectors.toList()); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountServiceRaw.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountServiceRaw.java index c61ec00b127..87ccacb827a 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountServiceRaw.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioAccountServiceRaw.java @@ -34,90 +34,130 @@ public GateioDepositAddress getDepositAddress(Currency currency) throws IOExcept String currencyCode = currency == null ? null : currency.getCurrencyCode(); try { - return gateioV4Authenticated.getDepositAddress(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currencyCode); - } - catch (GateioException e) { + return gateioV4Authenticated.getDepositAddress( + apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currencyCode); + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } - } - public List getWithdrawStatus(Currency currency) throws IOException { String currencyCode = currency == null ? null : currency.getCurrencyCode(); try { - return gateioV4Authenticated.getWithdrawStatus(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currencyCode); - } - catch (GateioException e) { + return gateioV4Authenticated.getWithdrawStatus( + apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currencyCode); + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } - } - public List getSpotBalances(Currency currency) throws IOException { String currencyCode = currency == null ? null : currency.getCurrencyCode(); - return gateioV4Authenticated.getSpotAccounts(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currencyCode); + return gateioV4Authenticated.getSpotAccounts( + apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currencyCode); } - - public List getWithdrawals(GateioWithdrawalsParams params) throws IOException { + public List getWithdrawals(GateioWithdrawalsParams params) + throws IOException { String currency = params.getCurrency() != null ? params.getCurrency().toString() : null; Long from = params.getStartTime() != null ? params.getStartTime().getEpochSecond() : null; Long to = params.getEndTime() != null ? params.getEndTime().getEpochSecond() : null; - return gateioV4Authenticated.getWithdrawals(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, - currency, from, to, params.getPageLength(), params.getZeroBasedPageNumber()); + return gateioV4Authenticated.getWithdrawals( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + currency, + from, + to, + params.getPageLength(), + params.getZeroBasedPageNumber()); } - public List getDeposits(GateioDepositsParams params) throws IOException { String currency = params.getCurrency() != null ? params.getCurrency().toString() : null; Long from = params.getStartTime() != null ? params.getStartTime().getEpochSecond() : null; Long to = params.getEndTime() != null ? params.getEndTime().getEpochSecond() : null; - return gateioV4Authenticated.getDeposits(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, - currency, from, to, params.getPageLength(), params.getZeroBasedPageNumber()); + return gateioV4Authenticated.getDeposits( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + currency, + from, + to, + params.getPageLength(), + params.getZeroBasedPageNumber()); } - - public GateioWithdrawalRecord withdraw(GateioWithdrawalRequest gateioWithdrawalRequest) throws IOException { - return gateioV4Authenticated.withdraw(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, gateioWithdrawalRequest); + public GateioWithdrawalRecord withdraw(GateioWithdrawalRequest gateioWithdrawalRequest) + throws IOException { + return gateioV4Authenticated.withdraw( + apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, gateioWithdrawalRequest); } - public List getSavedAddresses(Currency currency) throws IOException { Objects.requireNonNull(currency); - return gateioV4Authenticated.getSavedAddresses(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currency.getCurrencyCode()); + return gateioV4Authenticated.getSavedAddresses( + apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, currency.getCurrencyCode()); } - - public List getAccountBookRecords(TradeHistoryParams params) throws IOException { + public List getAccountBookRecords(TradeHistoryParams params) + throws IOException { // get arguments - Currency currency = params instanceof GateioFundingHistoryParams ? ((GateioFundingHistoryParams) params).getCurrency() : null; + Currency currency = + params instanceof GateioFundingHistoryParams + ? ((GateioFundingHistoryParams) params).getCurrency() + : null; String currencyCode = currency != null ? currency.toString() : null; - String type = params instanceof GateioFundingHistoryParams ? ((GateioFundingHistoryParams) params).getType() : null; - Integer pageLength = params instanceof TradeHistoryParamPaging ? ((TradeHistoryParamPaging) params).getPageLength() : null; - Integer pageNumber = params instanceof TradeHistoryParamPaging ? ((TradeHistoryParamPaging) params).getPageNumber() : null; + String type = + params instanceof GateioFundingHistoryParams + ? ((GateioFundingHistoryParams) params).getType() + : null; + Integer pageLength = + params instanceof TradeHistoryParamPaging + ? ((TradeHistoryParamPaging) params).getPageLength() + : null; + Integer pageNumber = + params instanceof TradeHistoryParamPaging + ? ((TradeHistoryParamPaging) params).getPageNumber() + : null; Long from = null; Long to = null; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan paramsTimeSpan = ((TradeHistoryParamsTimeSpan) params); - from = paramsTimeSpan.getStartTime() != null ? paramsTimeSpan.getStartTime().getTime() / 1000 : null; - to = paramsTimeSpan.getEndTime() != null ? paramsTimeSpan.getEndTime().getTime() / 1000 : null; + from = + paramsTimeSpan.getStartTime() != null + ? paramsTimeSpan.getStartTime().getTime() / 1000 + : null; + to = + paramsTimeSpan.getEndTime() != null ? paramsTimeSpan.getEndTime().getTime() / 1000 : null; } - return gateioV4Authenticated.getAccountBookRecords(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, - currencyCode, from, to, pageLength, pageNumber, type); + return gateioV4Authenticated.getAccountBookRecords( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + currencyCode, + from, + to, + pageLength, + pageNumber, + type); } - - public List getSubAccountTransfers(GateioSubAccountTransfersParams params) throws IOException { + public List getSubAccountTransfers( + GateioSubAccountTransfersParams params) throws IOException { Long from = params.getStartTime() != null ? params.getStartTime().getEpochSecond() : null; Long to = params.getEndTime() != null ? params.getEndTime().getEpochSecond() : null; - return gateioV4Authenticated.getSubAccountTransfers(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, - params.getSubAccountId(), from, to, params.getPageLength(), params.getZeroBasedPageNumber()); + return gateioV4Authenticated.getSubAccountTransfers( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + params.getSubAccountId(), + from, + to, + params.getPageLength(), + params.getZeroBasedPageNumber()); } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioBaseService.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioBaseService.java index 9be973588ef..03f530d391f 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioBaseService.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioBaseService.java @@ -18,26 +18,39 @@ public class GateioBaseService extends BaseExchangeService imple protected final GateioV4Authenticated gateioV4Authenticated; protected final ParamsDigest gateioV4ParamsDigest; - @SneakyThrows public GateioBaseService(GateioExchange exchange) { super(exchange); - gateio = ExchangeRestProxyBuilder - .forInterface(Gateio.class, exchange.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.setJacksonObjectMapperFactory(new GateioJacksonObjectMapperFactory())) - .restProxyFactory(Config.getInstance().getRestProxyFactoryClass().getDeclaredConstructor().newInstance()) - .build(); + gateio = + ExchangeRestProxyBuilder.forInterface(Gateio.class, exchange.getExchangeSpecification()) + .clientConfigCustomizer( + clientConfig -> + clientConfig.setJacksonObjectMapperFactory( + new GateioJacksonObjectMapperFactory())) + .restProxyFactory( + Config.getInstance() + .getRestProxyFactoryClass() + .getDeclaredConstructor() + .newInstance()) + .build(); apiKey = exchange.getExchangeSpecification().getApiKey(); - gateioV4Authenticated = ExchangeRestProxyBuilder - .forInterface(GateioV4Authenticated.class, exchange.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.setJacksonObjectMapperFactory(new GateioJacksonObjectMapperFactory())) - .restProxyFactory(Config.getInstance().getRestProxyFactoryClass().getDeclaredConstructor().newInstance()) - .build(); + gateioV4Authenticated = + ExchangeRestProxyBuilder.forInterface( + GateioV4Authenticated.class, exchange.getExchangeSpecification()) + .clientConfigCustomizer( + clientConfig -> + clientConfig.setJacksonObjectMapperFactory( + new GateioJacksonObjectMapperFactory())) + .restProxyFactory( + Config.getInstance() + .getRestProxyFactoryClass() + .getDeclaredConstructor() + .newInstance()) + .build(); gateioV4ParamsDigest = GateioV4Digest.createInstance(exchange.getExchangeSpecification().getSecretKey()); } - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataService.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataService.java index 3f6c6f62ec0..745b4834f4c 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataService.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataService.java @@ -28,7 +28,8 @@ import org.knowm.xchange.service.marketdata.MarketDataService; import org.knowm.xchange.service.marketdata.params.Params; -public class GateioMarketDataService extends GateioMarketDataServiceRaw implements MarketDataService { +public class GateioMarketDataService extends GateioMarketDataServiceRaw + implements MarketDataService { public GateioMarketDataService(GateioExchange exchange) { super(exchange); @@ -69,15 +70,12 @@ public Ticker getTicker(Instrument instrument, Object... args) throws IOExceptio } } - @Override public List getTickers(Params params) throws IOException { try { List tickers = getGateioTickers(null); - return tickers.stream() - .map(GateioAdapters::toTicker) - .collect(Collectors.toList()); + return tickers.stream().map(GateioAdapters::toTicker).collect(Collectors.toList()); } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } @@ -98,7 +96,6 @@ public OrderBook getOrderBook(Instrument instrument, Object... args) throws IOEx } } - public List getCurrencies() throws IOException { try { List currencyInfos = getGateioCurrencyInfos(); @@ -113,7 +110,6 @@ public List getCurrencies() throws IOException { } } - public List getCurrencyPairs() throws IOException { try { List metadata = getCurrencyPairDetails(); @@ -122,27 +118,25 @@ public List getCurrencyPairs() throws IOException { .filter(details -> "tradable".equals(details.getTradeStatus())) .map(details -> new CurrencyPair(details.getAsset(), details.getQuote())) .collect(Collectors.toList()); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - public Map getMetaDataByInstrument() throws IOException { try { List metadata = getCurrencyPairDetails(); return metadata.stream() - .collect(Collectors.toMap( - gateioCurrencyPairDetails -> new CurrencyPair(gateioCurrencyPairDetails.getAsset(), gateioCurrencyPairDetails.getQuote()), - GateioAdapters::toInstrumentMetaData - )); - } - catch (GateioException e) { + .collect( + Collectors.toMap( + gateioCurrencyPairDetails -> + new CurrencyPair( + gateioCurrencyPairDetails.getAsset(), + gateioCurrencyPairDetails.getQuote()), + GateioAdapters::toInstrumentMetaData)); + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRaw.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRaw.java index 3b01b6e8d57..3affd6ba5c0 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRaw.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRaw.java @@ -19,40 +19,32 @@ public GateioMarketDataServiceRaw(GateioExchange exchange) { super(exchange); } - public GateioServerTime getGateioServerTime() throws IOException { return gateio.getServerTime(); } - public List getGateioTickers(Instrument instrument) throws IOException { return gateio.getTickers(GateioAdapters.toString(instrument)); } - public List getGateioCurrencyInfos() throws IOException { return gateio.getCurrencies(); } - public GateioOrderBook getGateioOrderBook(Instrument instrument) throws IOException { return gateio.getOrderBook(GateioAdapters.toString(instrument), false); } - public List getCurrencyChains(Currency currency) throws IOException { return gateio.getCurrencyChains(currency.getCurrencyCode()); } - public List getCurrencyPairDetails() throws IOException { - return gateio.getCurrencyPairDetails(); + return gateio.getCurrencyPairDetails(); } - - public GateioCurrencyPairDetails getCurrencyPairDetails(Instrument instrument) throws IOException { + public GateioCurrencyPairDetails getCurrencyPairDetails(Instrument instrument) + throws IOException { return gateio.getCurrencyPairDetails(GateioAdapters.toString(instrument)); } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeService.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeService.java index 44e55432b64..4cd26795ad8 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeService.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeService.java @@ -33,31 +33,26 @@ public GateioTradeService(GateioExchange exchange) { super(exchange); } - @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { try { GateioOrder order = createOrder(GateioAdapters.toGateioOrder(marketOrder)); return order.getId(); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { try { GateioOrder order = createOrder(GateioAdapters.toGateioOrder(limitOrder)); return order.getId(); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - @Override public Collection getOrder(OrderQueryParams... orderQueryParams) throws IOException { // todo: implement getting of several orders @@ -69,34 +64,30 @@ public Collection getOrder(OrderQueryParams... orderQueryParams) throws I try { GateioOrder gateioOrder = getOrder(params.getOrderId(), params.getInstrument()); return Collections.singletonList(GateioAdapters.toOrder(gateioOrder)); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - public Order cancelOrder(String orderId, Instrument instrument) throws IOException { try { GateioOrder gateioOrder = cancelOrderRaw(orderId, instrument); return GateioAdapters.toOrder(gateioOrder); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } - @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { Validate.isInstanceOf(DefaultCancelOrderByInstrumentAndIdParams.class, orderParams); - DefaultCancelOrderByInstrumentAndIdParams params = (DefaultCancelOrderByInstrumentAndIdParams) orderParams; + DefaultCancelOrderByInstrumentAndIdParams params = + (DefaultCancelOrderByInstrumentAndIdParams) orderParams; try { Order order = cancelOrder(params.getOrderId(), params.getInstrument()); return order.getStatus() == OrderStatus.CANCELED; - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } @@ -104,12 +95,12 @@ public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { try { - List userTradeList = getGateioUserTrades(params).stream() - .map(GateioAdapters::toUserTrade) - .collect(Collectors.toList()); + List userTradeList = + getGateioUserTrades(params).stream() + .map(GateioAdapters::toUserTrade) + .collect(Collectors.toList()); return new UserTrades(userTradeList, TradeSortType.SortByID); - } - catch (GateioException e) { + } catch (GateioException e) { throw GateioErrorAdapter.adapt(e); } } @@ -119,11 +110,8 @@ public Class[] getRequiredCancelOrderParamClasses() { return new Class[] {DefaultCancelOrderByInstrumentAndIdParams.class}; } - @Override public TradeHistoryParams createTradeHistoryParams() { return GateioTradeHistoryParams.builder().build(); } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeServiceRaw.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeServiceRaw.java index 16e889ac1cb..10776e8a3aa 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeServiceRaw.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioTradeServiceRaw.java @@ -28,33 +28,54 @@ public GateioTradeServiceRaw(GateioExchange exchange) { super(exchange); } - - public List listOrders(Instrument instrument, OrderStatus orderStatus) throws IOException { + public List listOrders(Instrument instrument, OrderStatus orderStatus) + throws IOException { // validate arguments Objects.requireNonNull(orderStatus); Set allowedOrderStatuses = EnumSet.of(OrderStatus.OPEN, OrderStatus.CLOSED); - Validate.validState(allowedOrderStatuses.contains(orderStatus), "Allowed order statuses are: {}", allowedOrderStatuses); + Validate.validState( + allowedOrderStatuses.contains(orderStatus), + "Allowed order statuses are: {}", + allowedOrderStatuses); Objects.requireNonNull(instrument); - return gateioV4Authenticated.listOrders(apiKey, exchange.getNonceFactory(), - gateioV4ParamsDigest, GateioAdapters.toString(instrument), GateioAdapters.toString(orderStatus) - ); - + return gateioV4Authenticated.listOrders( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + GateioAdapters.toString(instrument), + GateioAdapters.toString(orderStatus)); } - - public List getGateioUserTrades(TradeHistoryParams params) throws IOException { + public List getGateioUserTrades(TradeHistoryParams params) + throws IOException { // get arguments - CurrencyPair currencyPair = params instanceof TradeHistoryParamCurrencyPair ? ((CurrencyPairParam) params).getCurrencyPair() : null; - Integer pageLength = params instanceof TradeHistoryParamPaging ? ((TradeHistoryParamPaging) params).getPageLength() : null; - Integer pageNumber = params instanceof TradeHistoryParamPaging ? ((TradeHistoryParamPaging) params).getPageNumber() : null; - String orderId = params instanceof TradeHistoryParamTransactionId ? ((TradeHistoryParamTransactionId) params).getTransactionId() : null; + CurrencyPair currencyPair = + params instanceof TradeHistoryParamCurrencyPair + ? ((CurrencyPairParam) params).getCurrencyPair() + : null; + Integer pageLength = + params instanceof TradeHistoryParamPaging + ? ((TradeHistoryParamPaging) params).getPageLength() + : null; + Integer pageNumber = + params instanceof TradeHistoryParamPaging + ? ((TradeHistoryParamPaging) params).getPageNumber() + : null; + String orderId = + params instanceof TradeHistoryParamTransactionId + ? ((TradeHistoryParamTransactionId) params).getTransactionId() + : null; Long from = null; Long to = null; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan paramsTimeSpan = ((TradeHistoryParamsTimeSpan) params); - from = paramsTimeSpan.getStartTime() != null ? paramsTimeSpan.getStartTime().getTime() / 1000 : null; - to = paramsTimeSpan.getEndTime() != null ? paramsTimeSpan.getEndTime().getTime() / 1000 : null; + from = + paramsTimeSpan.getStartTime() != null + ? paramsTimeSpan.getStartTime().getTime() / 1000 + : null; + to = + paramsTimeSpan.getEndTime() != null ? paramsTimeSpan.getEndTime().getTime() / 1000 : null; } // if no pagination is given, get all records in chunks @@ -64,38 +85,58 @@ public List getGateioUserTrades(TradeHistoryParams params) t Integer currentPageNumber = 1; do { - chunk = gateioV4Authenticated.getTradingHistory(apiKey, exchange.getNonceFactory(), - gateioV4ParamsDigest, GateioAdapters.toString(currencyPair), - 1000, currentPageNumber, orderId, null, from, to); + chunk = + gateioV4Authenticated.getTradingHistory( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + GateioAdapters.toString(currencyPair), + 1000, + currentPageNumber, + orderId, + null, + from, + to); currentPageNumber++; result.addAll(chunk); - } - while (!chunk.isEmpty()); + } while (!chunk.isEmpty()); return result; } - return gateioV4Authenticated.getTradingHistory(apiKey, exchange.getNonceFactory(), - gateioV4ParamsDigest, GateioAdapters.toString(currencyPair), - pageLength, pageNumber, orderId, null, from, to); + return gateioV4Authenticated.getTradingHistory( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + GateioAdapters.toString(currencyPair), + pageLength, + pageNumber, + orderId, + null, + from, + to); } - public GateioOrder createOrder(GateioOrder gateioOrder) throws IOException { - return gateioV4Authenticated.createOrder(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, gateioOrder); + return gateioV4Authenticated.createOrder( + apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, gateioOrder); } - public GateioOrder getOrder(String orderId, Instrument instrument) throws IOException { - return gateioV4Authenticated.getOrder(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, - orderId, GateioAdapters.toString(instrument)); + return gateioV4Authenticated.getOrder( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + orderId, + GateioAdapters.toString(instrument)); } - public GateioOrder cancelOrderRaw(String orderId, Instrument instrument) throws IOException { - return gateioV4Authenticated.cancelOrder(apiKey, exchange.getNonceFactory(), gateioV4ParamsDigest, - orderId, GateioAdapters.toString(instrument)); + return gateioV4Authenticated.cancelOrder( + apiKey, + exchange.getNonceFactory(), + gateioV4ParamsDigest, + orderId, + GateioAdapters.toString(instrument)); } - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioV4Digest.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioV4Digest.java index 3625ccc6ff1..f7b439ac247 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioV4Digest.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/GateioV4Digest.java @@ -28,11 +28,13 @@ public String digestParams(RestInvocation restInvocation) { String query = restInvocation.getQueryString(); String body = restInvocation.getRequestBody(); MessageDigest md = MessageDigest.getInstance("SHA-512"); - String hexedHashedBody = DigestUtils.bytesToHex(md.digest(body.getBytes(StandardCharsets.UTF_8))); + String hexedHashedBody = + DigestUtils.bytesToHex(md.digest(body.getBytes(StandardCharsets.UTF_8))); String timestamp = restInvocation.getHttpHeadersFromParams().get("Timestamp"); - String payloadToSign = String.format("%s\n/%s\n%s\n%s\n%s", method, path, query, hexedHashedBody, timestamp); + String payloadToSign = + String.format("%s\n/%s\n%s\n%s\n%s", method, path, query, hexedHashedBody, timestamp); Mac mac = getMac(); mac.update(payloadToSign.getBytes(StandardCharsets.UTF_8)); diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioDepositsParams.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioDepositsParams.java index 88678aecc4b..932fdaccaff 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioDepositsParams.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioDepositsParams.java @@ -22,5 +22,4 @@ public class GateioDepositsParams { private Instant startTime; private Instant endTime; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioFundingHistoryParams.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioFundingHistoryParams.java index 8980c09239c..916b3808406 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioFundingHistoryParams.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioFundingHistoryParams.java @@ -9,7 +9,8 @@ @Data @Builder -public class GateioFundingHistoryParams implements TradeHistoryParamPaging, TradeHistoryParamsTimeSpan { +public class GateioFundingHistoryParams + implements TradeHistoryParamPaging, TradeHistoryParamsTimeSpan { private Currency currency; @@ -22,5 +23,4 @@ public class GateioFundingHistoryParams implements TradeHistoryParamPaging, Trad private Date endTime; private String type; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioTradeHistoryParams.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioTradeHistoryParams.java index d0f708c4b46..033530ef24e 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioTradeHistoryParams.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioTradeHistoryParams.java @@ -11,8 +11,11 @@ @Data @SuperBuilder -public class GateioTradeHistoryParams implements TradeHistoryParamCurrencyPair, - TradeHistoryParamPaging, TradeHistoryParamTransactionId, TradeHistoryParamsTimeSpan { +public class GateioTradeHistoryParams + implements TradeHistoryParamCurrencyPair, + TradeHistoryParamPaging, + TradeHistoryParamTransactionId, + TradeHistoryParamsTimeSpan { private CurrencyPair currencyPair; @@ -25,6 +28,4 @@ public class GateioTradeHistoryParams implements TradeHistoryParamCurrencyPair, private Date startTime; private Date endTime; - - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawFundsParams.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawFundsParams.java index 1ebcb3b235a..59fcb4a0dac 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawFundsParams.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawFundsParams.java @@ -11,5 +11,4 @@ public class GateioWithdrawFundsParams extends DefaultWithdrawFundsParams { String clientRecordId; String chain; - } diff --git a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawalsParams.java b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawalsParams.java index ce906635abb..9beb196f7aa 100644 --- a/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawalsParams.java +++ b/xchange-gateio-v4/src/main/java/org/knowm/xchange/gateio/service/params/GateioWithdrawalsParams.java @@ -22,5 +22,4 @@ public class GateioWithdrawalsParams { private Instant startTime; private Instant endTime; - } diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeTest.java index 2f76b5e060c..1ce5ddb85c5 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeTest.java @@ -11,18 +11,19 @@ public class GateioExchangeTest extends GateioExchangeWiremock { @Test void metadata_present() { - InstrumentMetaData expected = new InstrumentMetaData.Builder() - .tradingFee(new BigDecimal("0.2")) - .minimumAmount(new BigDecimal("0.0001")) - .counterMinimumAmount(BigDecimal.ONE) - .volumeScale(4) - .priceScale(1) - .marketOrderEnabled(false) - .build(); + InstrumentMetaData expected = + new InstrumentMetaData.Builder() + .tradingFee(new BigDecimal("0.2")) + .minimumAmount(new BigDecimal("0.0001")) + .counterMinimumAmount(BigDecimal.ONE) + .volumeScale(4) + .priceScale(1) + .marketOrderEnabled(false) + .build(); - InstrumentMetaData actual = exchange.getExchangeMetaData().getInstruments().get(CurrencyPair.BTC_USDT); + InstrumentMetaData actual = + exchange.getExchangeMetaData().getInstruments().get(CurrencyPair.BTC_USDT); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeWiremock.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeWiremock.java index 2ddf34b0d82..02b0d2fcb5a 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeWiremock.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/GateioExchangeWiremock.java @@ -9,19 +9,16 @@ import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.ExchangeSpecification; -/** - * Sets up the wiremock for exchange - */ +/** Sets up the wiremock for exchange */ public abstract class GateioExchangeWiremock { protected static GateioExchange exchange; -// private static final boolean IS_RECORDING = true; + // private static final boolean IS_RECORDING = true; private static final boolean IS_RECORDING = false; private static WireMockServer wireMockServer; - @BeforeAll public static void initExchange() { wireMockServer = new WireMockServer(options().dynamicPort()); @@ -32,7 +29,6 @@ public static void initExchange() { exSpec.setApiKey("a"); exSpec.setSecretKey("b"); - if (IS_RECORDING) { // use default url and record the requests wireMockServer.startRecording( @@ -40,16 +36,12 @@ public static void initExchange() { .forTarget("https://api.gateio.ws") .matchRequestBodyWithEqualToJson() .extractTextBodiesOver(1L) - .chooseBodyMatchTypeAutomatically() - ); - + .chooseBodyMatchTypeAutomatically()); } exchange = (GateioExchange) ExchangeFactory.INSTANCE.createExchange(exSpec); - } - @AfterAll public static void stop() { if (IS_RECORDING) { @@ -57,6 +49,4 @@ public static void stop() { } wireMockServer.stop(); } - - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChainTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChainTest.java index 10e0f6506da..c645e8cf100 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChainTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyChainTest.java @@ -25,4 +25,4 @@ void valid_isDepositEnabled() { gateioCurrencyChain.setDepositDisabled(false); assertThat(gateioCurrencyChain.isDepositEnabled()).isTrue(); } -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfoTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfoTest.java index 4dd47e5eb50..f49411e367b 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfoTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/dto/marketdata/GateioCurrencyInfoTest.java @@ -15,7 +15,6 @@ void valid_isWithdrawEnabled() { assertThat(gateioCurrencyInfo.isWithdrawEnabled()).isTrue(); } - @Test void valid_isDepositEnabled() { GateioCurrencyInfo gateioCurrencyInfo = GateioCurrencyInfo.builder().build(); @@ -24,4 +23,4 @@ void valid_isDepositEnabled() { gateioCurrencyInfo.setDepositDisabled(false); assertThat(gateioCurrencyInfo.isDepositEnabled()).isTrue(); } -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceRawTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceRawTest.java index 93e7c0c44bb..f6aa3bd1a4e 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceRawTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceRawTest.java @@ -30,26 +30,28 @@ public class GateioAccountServiceRawTest extends GateioExchangeWiremock { - GateioAccountServiceRaw gateioAccountServiceRaw = ((GateioAccountServiceRaw) exchange.getAccountService()); + GateioAccountServiceRaw gateioAccountServiceRaw = + ((GateioAccountServiceRaw) exchange.getAccountService()); @Test void getWithdrawStatus_valid() throws IOException { Map expectedWithdrawFeeByChain = new HashMap<>(); expectedWithdrawFeeByChain.put("ETH", new BigDecimal("0.93")); expectedWithdrawFeeByChain.put("GTEVM", new BigDecimal("0.0049")); - GateioWithdrawStatus expected = GateioWithdrawStatus.builder() - .currency(Currency.getInstance("GT")) - .name("GateToken") - .nameCN("狗头") - .depositFee(BigDecimal.ZERO) - .withdrawPercent("0%") - .withdrawFee(new BigDecimal("0.02")) - .withdrawDailyLimit(new BigDecimal("500000")) - .withdrawDailyLimitLeft(new BigDecimal("499999")) - .minWithdrawAmount(new BigDecimal("0.12")) - .maxWithdrawAmount(new BigDecimal("499999")) - .withdrawFeeByChain(expectedWithdrawFeeByChain) - .build(); + GateioWithdrawStatus expected = + GateioWithdrawStatus.builder() + .currency(Currency.getInstance("GT")) + .name("GateToken") + .nameCN("狗头") + .depositFee(BigDecimal.ZERO) + .withdrawPercent("0%") + .withdrawFee(new BigDecimal("0.02")) + .withdrawDailyLimit(new BigDecimal("500000")) + .withdrawDailyLimitLeft(new BigDecimal("499999")) + .minWithdrawAmount(new BigDecimal("0.12")) + .maxWithdrawAmount(new BigDecimal("499999")) + .withdrawFeeByChain(expectedWithdrawFeeByChain) + .build(); List status = gateioAccountServiceRaw.getWithdrawStatus(null); @@ -57,188 +59,198 @@ void getWithdrawStatus_valid() throws IOException { GateioWithdrawStatus actualGt = status.get(0); assertThat(actualGt).isEqualTo(expected); assertThat(actualGt.getWithdrawRate()).isEqualTo(new BigDecimal("0.00")); - } - @Test void http_401_exception_mapped() { assertThatExceptionOfType(ExchangeSecurityException.class) - .isThrownBy(() -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("THROW_401"))); + .isThrownBy( + () -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("THROW_401"))); assertThatExceptionOfType(ExchangeSecurityException.class) - .isThrownBy(() -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("INVALID_KEY"))); + .isThrownBy( + () -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("INVALID_KEY"))); } - @Test void http_403_exception_mapped() { assertThatExceptionOfType(ExchangeSecurityException.class) - .isThrownBy(() -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("RETURN-FORBIDDEN"))); + .isThrownBy( + () -> + gateioAccountServiceRaw.getWithdrawStatus( + Currency.getInstance("RETURN-FORBIDDEN"))); } - @Test void http_500_exception_mapped() { assertThatExceptionOfType(InternalServerException.class) - .isThrownBy(() -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("INTERNAL-SERVER-ERROR"))); + .isThrownBy( + () -> + gateioAccountServiceRaw.getWithdrawStatus( + Currency.getInstance("INTERNAL-SERVER-ERROR"))); } - @Test void invalid_currency_exception_mapped() { assertThatExceptionOfType(InstrumentNotValidException.class) - .isThrownBy(() -> gateioAccountServiceRaw.getWithdrawStatus(Currency.getInstance("invalid-currency"))); + .isThrownBy( + () -> + gateioAccountServiceRaw.getWithdrawStatus( + Currency.getInstance("invalid-currency"))); } - @Test void pending_deposit_address() throws IOException { GateioDepositAddress a = gateioAccountServiceRaw.getDepositAddress(Currency.getInstance("ITA")); - MultichainAddress expected = MultichainAddress.builder() - .chain("CHZ") - .failed(true) - .address("") - .memo("") - .memoType("") - .build(); + MultichainAddress expected = + MultichainAddress.builder() + .chain("CHZ") + .failed(true) + .address("") + .memo("") + .memoType("") + .build(); assertThat(a.getMultichainAddresses()).hasSize(1); assertThat(a.getMultichainAddresses().get(0)).isEqualTo(expected); } - @Test void valid_deposit_address() throws IOException { - GateioDepositAddress a = gateioAccountServiceRaw.getDepositAddress(Currency.getInstance("ABBC")); - - MultichainAddress expected = MultichainAddress.builder() - .chain("ABBC") - .failed(false) - .address("gateioioabbc") - .memo("00cceed3f9cb5069") - .memoType("Memo") - .build(); + GateioDepositAddress a = + gateioAccountServiceRaw.getDepositAddress(Currency.getInstance("ABBC")); + + MultichainAddress expected = + MultichainAddress.builder() + .chain("ABBC") + .failed(false) + .address("gateioioabbc") + .memo("00cceed3f9cb5069") + .memoType("Memo") + .build(); assertThat(a.getMultichainAddresses()).hasSize(1); assertThat(a.getMultichainAddresses().get(0)).isEqualTo(expected); } - @Test void withdrawal_records() throws IOException { - List actual = gateioAccountServiceRaw.getWithdrawals(GateioWithdrawalsParams.builder().build()); - - GateioWithdrawalRecord expected = GateioWithdrawalRecord.builder() - .id("w35874123") - .currency(Currency.getInstance("LUFFY")) - .address("0x3dca2ae4d1d065220a731cf69f5a934914afc435") - .amount(new BigDecimal("1030645.8587")) - .fee(new BigDecimal("10000")) - .txId("0x8f72d42b016a2b7b543149e707ff37fadded2ff3ef6767bee30b6003330f604b") - .chain("ETH") - .createdAt(Instant.parse("2023-06-01T11:34:15Z")) - .status(GateioWithdrawalRecord.Status.DONE) - .clientRecordId("a") - .tag("b") - .build(); + List actual = + gateioAccountServiceRaw.getWithdrawals(GateioWithdrawalsParams.builder().build()); + + GateioWithdrawalRecord expected = + GateioWithdrawalRecord.builder() + .id("w35874123") + .currency(Currency.getInstance("LUFFY")) + .address("0x3dca2ae4d1d065220a731cf69f5a934914afc435") + .amount(new BigDecimal("1030645.8587")) + .fee(new BigDecimal("10000")) + .txId("0x8f72d42b016a2b7b543149e707ff37fadded2ff3ef6767bee30b6003330f604b") + .chain("ETH") + .createdAt(Instant.parse("2023-06-01T11:34:15Z")) + .status(GateioWithdrawalRecord.Status.DONE) + .clientRecordId("a") + .tag("b") + .build(); assertThat(actual).hasSize(1); assertThat(actual).first().usingRecursiveComparison().isEqualTo(expected); } - @Test void deposit_records() throws IOException { - List actual = gateioAccountServiceRaw.getDeposits(GateioDepositsParams.builder() - .startTime(Instant.ofEpochSecond(1685833987)) - .endTime(Instant.ofEpochSecond(1688339587)) - .build()); - - GateioDepositRecord expected = GateioDepositRecord.builder() - .id("d95198946") - .currency(Currency.getInstance("OMN")) - .address("0x04A09F5712F527584BAC0C7be40Ae7946f9A9587") - .amount(new BigDecimal("2353")) - .txId("0x34a89edf400a85a9a6a2747ebc2074ef65895345b9b7400f164602085e9b4a2e") - .chain("OMN") - .createdAt(Instant.parse("2023-07-01T14:12:26Z")) - .status(Status.DONE) - .tag("") - .build(); + List actual = + gateioAccountServiceRaw.getDeposits( + GateioDepositsParams.builder() + .startTime(Instant.ofEpochSecond(1685833987)) + .endTime(Instant.ofEpochSecond(1688339587)) + .build()); + + GateioDepositRecord expected = + GateioDepositRecord.builder() + .id("d95198946") + .currency(Currency.getInstance("OMN")) + .address("0x04A09F5712F527584BAC0C7be40Ae7946f9A9587") + .amount(new BigDecimal("2353")) + .txId("0x34a89edf400a85a9a6a2747ebc2074ef65895345b9b7400f164602085e9b4a2e") + .chain("OMN") + .createdAt(Instant.parse("2023-07-01T14:12:26Z")) + .status(Status.DONE) + .tag("") + .build(); assertThat(actual).hasSize(2); assertThat(actual).first().usingRecursiveComparison().isEqualTo(expected); } - @Test void withdraw() throws IOException { - GateioWithdrawalRequest gateioWithdrawalRequest = GateioWithdrawalRequest.builder() - .clientRecordId("valid-withdrawal-id") - .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") - .tag("") - .chain("SOL") - .amount(BigDecimal.valueOf(3)) - .currency(Currency.USDT) - .build(); + GateioWithdrawalRequest gateioWithdrawalRequest = + GateioWithdrawalRequest.builder() + .clientRecordId("valid-withdrawal-id") + .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") + .tag("") + .chain("SOL") + .amount(BigDecimal.valueOf(3)) + .currency(Currency.USDT) + .build(); GateioWithdrawalRecord actual = gateioAccountServiceRaw.withdraw(gateioWithdrawalRequest); - GateioWithdrawalRecord expected = GateioWithdrawalRecord.builder() - .id("w35980955") - .clientRecordId("valid-withdrawal-id") - .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA ") - .tag("") - .chain("SOL") - .amount(BigDecimal.valueOf(3)) - .currency(Currency.USDT) - .status(GateioWithdrawalRecord.Status.REQUEST) - .build(); + GateioWithdrawalRecord expected = + GateioWithdrawalRecord.builder() + .id("w35980955") + .clientRecordId("valid-withdrawal-id") + .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA ") + .tag("") + .chain("SOL") + .amount(BigDecimal.valueOf(3)) + .currency(Currency.USDT) + .status(GateioWithdrawalRecord.Status.REQUEST) + .build(); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); - } - @Test void saved_addresses() throws IOException { List actual = gateioAccountServiceRaw.getSavedAddresses(Currency.USDT); - GateioAddressRecord expected = GateioAddressRecord.builder() - .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") - .tag("") - .chain("SOL") - .currency(Currency.USDT) - .name("stuff") - .verified(true) - .build(); + GateioAddressRecord expected = + GateioAddressRecord.builder() + .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") + .tag("") + .chain("SOL") + .currency(Currency.USDT) + .name("stuff") + .verified(true) + .build(); assertThat(actual).hasSize(1); assertThat(actual).first().usingRecursiveComparison().isEqualTo(expected); } - @Test void sub_account_transfers() throws IOException { - List actual = gateioAccountServiceRaw.getSubAccountTransfers( - GateioSubAccountTransfersParams.builder().build()); - - GateioSubAccountTransfer expected = GateioSubAccountTransfer.builder() - .mainAccountId(10001) - .timestamp(Instant.ofEpochSecond(1592809000)) - .source("web") - .clientOrderId("da3ce7a088c8b0372b741419c7829033") - .currency(Currency.BTC) - .subAccountId(10002) - .direction("to") - .amount(BigDecimal.ONE) - .subAccountType("spot") - .build(); + List actual = + gateioAccountServiceRaw.getSubAccountTransfers( + GateioSubAccountTransfersParams.builder().build()); + + GateioSubAccountTransfer expected = + GateioSubAccountTransfer.builder() + .mainAccountId(10001) + .timestamp(Instant.ofEpochSecond(1592809000)) + .source("web") + .clientOrderId("da3ce7a088c8b0372b741419c7829033") + .currency(Currency.BTC) + .subAccountId(10002) + .direction("to") + .amount(BigDecimal.ONE) + .subAccountType("spot") + .build(); assertThat(actual).hasSize(1); assertThat(actual).first().usingRecursiveComparison().isEqualTo(expected); } - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceTest.java index 1107887502e..6dbc08ff851 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioAccountServiceTest.java @@ -25,14 +25,12 @@ class GateioAccountServiceTest extends GateioExchangeWiremock { - static { Config.getInstance().setRestProxyFactoryClass(CustomRestProxyFactoryImpl.class); } GateioAccountService gateioAccountService = ((GateioAccountService) exchange.getAccountService()); - @Test void getAccountInfo() throws IOException { @@ -48,92 +46,93 @@ void getAccountInfo() throws IOException { @Test void normal_withdraw() throws IOException { - GateioWithdrawFundsParams params = GateioWithdrawFundsParams.builder() - .clientRecordId("valid-withdrawal-id") - .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") - .addressTag("") - .chain("SOL") - .amount(BigDecimal.valueOf(3)) - .currency(Currency.USDT) - .build(); + GateioWithdrawFundsParams params = + GateioWithdrawFundsParams.builder() + .clientRecordId("valid-withdrawal-id") + .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") + .addressTag("") + .chain("SOL") + .amount(BigDecimal.valueOf(3)) + .currency(Currency.USDT) + .build(); String withdrawalId = gateioAccountService.withdrawFunds(params); assertThat(withdrawalId).isEqualTo("w35980955"); } - @Test void rate_limited_withdraw() { - GateioWithdrawFundsParams params = GateioWithdrawFundsParams.builder() - .clientRecordId("rate-limited-id") - .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") - .addressTag("") - .chain("SOL") - .amount(BigDecimal.valueOf(3)) - .currency(Currency.USDT) - .build(); + GateioWithdrawFundsParams params = + GateioWithdrawFundsParams.builder() + .clientRecordId("rate-limited-id") + .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") + .addressTag("") + .chain("SOL") + .amount(BigDecimal.valueOf(3)) + .currency(Currency.USDT) + .build(); assertThatExceptionOfType(RateLimitExceededException.class) .isThrownBy(() -> gateioAccountService.withdrawFunds(params)); } - @Test void zero_amount_withdraw() { - GateioWithdrawFundsParams params = GateioWithdrawFundsParams.builder() - .clientRecordId("zero-amount-id") - .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") - .addressTag("") - .chain("SOL") - .amount(BigDecimal.ZERO) - .currency(Currency.USDT) - .build(); + GateioWithdrawFundsParams params = + GateioWithdrawFundsParams.builder() + .clientRecordId("zero-amount-id") + .address("6vLyxJ9dBziamyaw2vDcs9n2NwQdW1uk3aooJwrEscnA") + .addressTag("") + .chain("SOL") + .amount(BigDecimal.ZERO) + .currency(Currency.USDT) + .build(); assertThatExceptionOfType(OrderAmountUnderMinimumException.class) .isThrownBy(() -> gateioAccountService.withdrawFunds(params)); } - @Test void invalid_address_withdraw() { - GateioWithdrawFundsParams params = GateioWithdrawFundsParams.builder() - .clientRecordId("invalid-address-id") - .address("invalid-address") - .addressTag("") - .chain("SOL") - .amount(BigDecimal.ZERO) - .currency(Currency.USDT) - .build(); + GateioWithdrawFundsParams params = + GateioWithdrawFundsParams.builder() + .clientRecordId("invalid-address-id") + .address("invalid-address") + .addressTag("") + .chain("SOL") + .amount(BigDecimal.ZERO) + .currency(Currency.USDT) + .build(); assertThatExceptionOfType(OrderNotValidException.class) .isThrownBy(() -> gateioAccountService.withdrawFunds(params)); } - @Test void funding_history() throws IOException { - List actual = gateioAccountService.getFundingHistory(GateioFundingHistoryParams.builder() - .currency(Currency.USDT) - .startTime(Date.from(Instant.ofEpochSecond(1691447482))) - .endTime(Date.from(Instant.ofEpochSecond(1691533882))) - .pageLength(2) - .pageNumber(1) - .type("order_fee") - .build()); - - FundingRecord expected = new FundingRecord.Builder() - .setInternalId("40558668441") - .setDate(Date.from(Instant.ofEpochMilli(1691510538067L))) - .setCurrency(Currency.USDT) - .setBalance(new BigDecimal("16.00283141582979715942")) - .setType(Type.OTHER_OUTFLOW) - .setAmount(new BigDecimal("0.0113918056")) - .setDescription("order_fee") - .build(); + List actual = + gateioAccountService.getFundingHistory( + GateioFundingHistoryParams.builder() + .currency(Currency.USDT) + .startTime(Date.from(Instant.ofEpochSecond(1691447482))) + .endTime(Date.from(Instant.ofEpochSecond(1691533882))) + .pageLength(2) + .pageNumber(1) + .type("order_fee") + .build()); + + FundingRecord expected = + new FundingRecord.Builder() + .setInternalId("40558668441") + .setDate(Date.from(Instant.ofEpochMilli(1691510538067L))) + .setCurrency(Currency.USDT) + .setBalance(new BigDecimal("16.00283141582979715942")) + .setType(Type.OTHER_OUTFLOW) + .setAmount(new BigDecimal("0.0113918056")) + .setDescription("order_fee") + .build(); assertThat(actual).hasSize(2); assertThat(actual).first().usingRecursiveComparison().isEqualTo(expected); } - - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioBaseServiceTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioBaseServiceTest.java index e7b7fbb410d..74998df5103 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioBaseServiceTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioBaseServiceTest.java @@ -10,9 +10,7 @@ import si.mazi.rescu.BodyLoggingRestInvocationHandler; import si.mazi.rescu.CustomRestProxyFactoryImpl; -/** - * Contains the example of overriding of RestProxyFactory for exchange for some specific logic - */ +/** Contains the example of overriding of RestProxyFactory for exchange for some specific logic */ class GateioBaseServiceTest extends GateioExchangeWiremock { // set custom proxy factory before creating the exchange @@ -20,13 +18,12 @@ class GateioBaseServiceTest extends GateioExchangeWiremock { Config.getInstance().setRestProxyFactoryClass(CustomRestProxyFactoryImpl.class); } - @Disabled @Test void correct_proxy_factory() { GateioBaseService service = ((GateioBaseService) exchange.getAccountService()); - assertThat(Proxy.getInvocationHandler(service.gateio) instanceof BodyLoggingRestInvocationHandler).isTrue(); + assertThat( + Proxy.getInvocationHandler(service.gateio) instanceof BodyLoggingRestInvocationHandler) + .isTrue(); } - - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceIntegration.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceIntegration.java index cdff7ac9114..c4c5ad214be 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceIntegration.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceIntegration.java @@ -24,22 +24,24 @@ void exchange_health() { assertThat(actual).isEqualTo(ExchangeHealth.ONLINE); } - @Test void valid_tickers() throws IOException { List tickers = exchange.getMarketDataService().getTickers(null); assertThat(tickers).isNotEmpty(); - assertThat(tickers).allSatisfy(ticker -> { - assertThat(ticker.getInstrument()).isNotNull(); - assertThat(ticker.getLast()).isNotNull(); - if (ObjectUtils.allNotNull(ticker.getBid(), ticker.getAsk()) && ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { - assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); - } - }); + assertThat(tickers) + .allSatisfy( + ticker -> { + assertThat(ticker.getInstrument()).isNotNull(); + assertThat(ticker.getLast()).isNotNull(); + if (ObjectUtils.allNotNull(ticker.getBid(), ticker.getAsk()) + && ticker.getBid().signum() > 0 + && ticker.getAsk().signum() > 0) { + assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); + } + }); } - @Test void valid_orderbook() throws IOException { OrderBook orderBook = exchange.getMarketDataService().getOrderBook(CurrencyPair.BTC_USDT); @@ -47,19 +49,21 @@ void valid_orderbook() throws IOException { assertThat(orderBook.getBids()).isNotEmpty(); assertThat(orderBook.getAsks()).isNotEmpty(); - assertThat(orderBook.getAsks().get(0).getLimitPrice()).isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); - - assertThat(orderBook.getBids()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); - }); - - assertThat(orderBook.getAsks()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); - }); - + assertThat(orderBook.getAsks().get(0).getLimitPrice()) + .isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); + + assertThat(orderBook.getBids()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); + }); + + assertThat(orderBook.getAsks()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); + }); } - - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRawTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRawTest.java index b2b00fc470f..6061f3eb027 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRawTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceRawTest.java @@ -20,8 +20,8 @@ public class GateioMarketDataServiceRawTest extends GateioExchangeWiremock { - GateioMarketDataServiceRaw gateioMarketDataServiceRaw = (GateioMarketDataServiceRaw) exchange.getMarketDataService(); - + GateioMarketDataServiceRaw gateioMarketDataServiceRaw = + (GateioMarketDataServiceRaw) exchange.getMarketDataService(); @Test public void getCurrencies_valid() throws IOException { @@ -31,123 +31,116 @@ public void getCurrencies_valid() throws IOException { GateioCurrencyInfo actualBtc = actual.get(0); - GateioCurrencyInfo expectedBtc = GateioCurrencyInfo.builder() - .currencyWithChain("BTC") - .delisted(false) - .withdrawDisabled(false) - .withdrawDelayed(false) - .depositDisabled(false) - .tradeDisabled(false) - .chain("BTC") - .build(); + GateioCurrencyInfo expectedBtc = + GateioCurrencyInfo.builder() + .currencyWithChain("BTC") + .delisted(false) + .withdrawDisabled(false) + .withdrawDelayed(false) + .depositDisabled(false) + .tradeDisabled(false) + .chain("BTC") + .build(); assertThat(actualBtc).usingRecursiveComparison().isEqualTo(expectedBtc); } - @Test public void getGateioOrderBook_valid() throws IOException { List expectedAsks = new ArrayList<>(); - expectedAsks.add(PriceSizeEntry.builder() - .price(new BigDecimal("200")) - .size(BigDecimal.ONE) - .build()); - expectedAsks.add(PriceSizeEntry.builder() - .price(new BigDecimal("250")) - .size(BigDecimal.TEN) - .build()); + expectedAsks.add( + PriceSizeEntry.builder().price(new BigDecimal("200")).size(BigDecimal.ONE).build()); + expectedAsks.add( + PriceSizeEntry.builder().price(new BigDecimal("250")).size(BigDecimal.TEN).build()); List expectedBids = new ArrayList<>(); - expectedBids.add(PriceSizeEntry.builder() - .price(new BigDecimal("150")) - .size(BigDecimal.ONE) - .build()); - expectedBids.add(PriceSizeEntry.builder() - .price(new BigDecimal("100")) - .size(BigDecimal.TEN) - .build()); - - GateioOrderBook expected = GateioOrderBook.builder() - .generatedAt(Instant.parse("2023-05-14T22:10:10.493Z")) - .updatedAt(Instant.parse("2023-05-14T22:10:10.263Z")) - .asks(expectedAsks) - .bids(expectedBids) - .build(); + expectedBids.add( + PriceSizeEntry.builder().price(new BigDecimal("150")).size(BigDecimal.ONE).build()); + expectedBids.add( + PriceSizeEntry.builder().price(new BigDecimal("100")).size(BigDecimal.TEN).build()); + + GateioOrderBook expected = + GateioOrderBook.builder() + .generatedAt(Instant.parse("2023-05-14T22:10:10.493Z")) + .updatedAt(Instant.parse("2023-05-14T22:10:10.263Z")) + .asks(expectedAsks) + .bids(expectedBids) + .build(); GateioOrderBook actual = gateioMarketDataServiceRaw.getGateioOrderBook(CurrencyPair.BTC_USDT); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - @Test public void getCurrencyChains_valid_result() throws IOException { - List expected = Arrays.asList( - GateioCurrencyChain.builder() - .chain("BTC") - .chainNameCN("比特币 BRC20/Ordinals") - .chainNameEN("Bitcoin BRC20/Ordinals") - .disabled(false) - .depositDisabled(false) - .withdrawDisabled(false) - .contractAddress("") - .build(), - GateioCurrencyChain.builder() - .chain("HT") - .chainNameCN("Heco") - .chainNameEN("Heco") - .disabled(true) - .depositDisabled(true) - .withdrawDisabled(true) - .contractAddress("0x66a79d23e58475d2738179ca52cd0b41d73f0bea") - .build() - ); + List expected = + Arrays.asList( + GateioCurrencyChain.builder() + .chain("BTC") + .chainNameCN("比特币 BRC20/Ordinals") + .chainNameEN("Bitcoin BRC20/Ordinals") + .disabled(false) + .depositDisabled(false) + .withdrawDisabled(false) + .contractAddress("") + .build(), + GateioCurrencyChain.builder() + .chain("HT") + .chainNameCN("Heco") + .chainNameEN("Heco") + .disabled(true) + .depositDisabled(true) + .withdrawDisabled(true) + .contractAddress("0x66a79d23e58475d2738179ca52cd0b41d73f0bea") + .build()); List actual = gateioMarketDataServiceRaw.getCurrencyChains(Currency.BTC); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - @Test void valid_currencypairs_details() throws IOException { List details = gateioMarketDataServiceRaw.getCurrencyPairDetails(); assertThat(details).hasSize(3); - GateioCurrencyPairDetails expectedChz = GateioCurrencyPairDetails.builder() - .id("CHZ_USDT") - .asset("CHZ") - .quote("USDT") - .fee(new BigDecimal("0.2")) - .minQuoteAmount(BigDecimal.ONE) - .assetScale(2) - .quoteScale(5) - .tradeStatus("tradable") - .startOfSells(Instant.parse("2020-12-24T04:00:00.000Z")) - .startOfBuys(Instant.parse("2020-12-24T06:00:00.000Z")) - .build(); + GateioCurrencyPairDetails expectedChz = + GateioCurrencyPairDetails.builder() + .id("CHZ_USDT") + .asset("CHZ") + .quote("USDT") + .fee(new BigDecimal("0.2")) + .minQuoteAmount(BigDecimal.ONE) + .assetScale(2) + .quoteScale(5) + .tradeStatus("tradable") + .startOfSells(Instant.parse("2020-12-24T04:00:00.000Z")) + .startOfBuys(Instant.parse("2020-12-24T06:00:00.000Z")) + .build(); GateioCurrencyPairDetails actualChz = details.get(1); assertThat(actualChz).isEqualTo(expectedChz); } - @Test void valid_single_currencypair_details() throws IOException { - GateioCurrencyPairDetails actualChz = gateioMarketDataServiceRaw.getCurrencyPairDetails(new CurrencyPair("CHZ/USDT")); - GateioCurrencyPairDetails expectedChz = GateioCurrencyPairDetails.builder() - .id("CHZ_USDT") - .asset("CHZ") - .quote("USDT") - .fee(new BigDecimal("0.2")) - .minQuoteAmount(BigDecimal.ONE) - .assetScale(2) - .quoteScale(5) - .tradeStatus("tradable") - .startOfSells(Instant.parse("2020-12-24T04:00:00.000Z")) - .startOfBuys(Instant.parse("2020-12-24T06:00:00.000Z")) - .build(); + GateioCurrencyPairDetails actualChz = + gateioMarketDataServiceRaw.getCurrencyPairDetails(new CurrencyPair("CHZ/USDT")); + GateioCurrencyPairDetails expectedChz = + GateioCurrencyPairDetails.builder() + .id("CHZ_USDT") + .asset("CHZ") + .quote("USDT") + .fee(new BigDecimal("0.2")) + .minQuoteAmount(BigDecimal.ONE) + .assetScale(2) + .quoteScale(5) + .tradeStatus("tradable") + .startOfSells(Instant.parse("2020-12-24T04:00:00.000Z")) + .startOfBuys(Instant.parse("2020-12-24T06:00:00.000Z")) + .build(); assertThat(actualChz).isEqualTo(expectedChz); } -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java index bd653c8dadc..007eacdf07a 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java @@ -19,48 +19,52 @@ public class GateioMarketDataServiceTest extends GateioExchangeWiremock { - GateioMarketDataService gateioMarketDataService = (GateioMarketDataService) exchange.getMarketDataService(); - + GateioMarketDataService gateioMarketDataService = + (GateioMarketDataService) exchange.getMarketDataService(); @Test void getOrderBook_valid() throws IOException { OrderBook actual = gateioMarketDataService.getOrderBook(CurrencyPair.BTC_USDT); List expectedAsks = new ArrayList<>(); - expectedAsks.add(new LimitOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) - .limitPrice(new BigDecimal("200")) - .originalAmount(BigDecimal.ONE) - .build()); - expectedAsks.add(new LimitOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) - .limitPrice(new BigDecimal("250")) - .originalAmount(BigDecimal.TEN) - .build()); + expectedAsks.add( + new LimitOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) + .limitPrice(new BigDecimal("200")) + .originalAmount(BigDecimal.ONE) + .build()); + expectedAsks.add( + new LimitOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) + .limitPrice(new BigDecimal("250")) + .originalAmount(BigDecimal.TEN) + .build()); List expectedBids = new ArrayList<>(); - expectedBids.add(new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) - .limitPrice(new BigDecimal("150")) - .originalAmount(BigDecimal.ONE) - .build()); - expectedBids.add(new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) - .limitPrice(new BigDecimal("100")) - .originalAmount(BigDecimal.TEN) - .build()); + expectedBids.add( + new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) + .limitPrice(new BigDecimal("150")) + .originalAmount(BigDecimal.ONE) + .build()); + expectedBids.add( + new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) + .limitPrice(new BigDecimal("100")) + .originalAmount(BigDecimal.TEN) + .build()); Date expectedTimestamp = Date.from(Instant.parse("2023-05-14T22:10:10.493Z")); OrderBook expected = new OrderBook(expectedTimestamp, expectedAsks, expectedBids); assertThat(actual) .usingRecursiveComparison() - .ignoringFieldsMatchingRegexes(".*userReference",".*lock") + .ignoringFieldsMatchingRegexes(".*userReference", ".*lock") .isEqualTo(expected); } - @Test void getTicker_valid() throws IOException { Ticker actual = gateioMarketDataService.getTicker(CurrencyPair.BTC_USDT); - Ticker expected = new Ticker.Builder() + Ticker expected = + new Ticker.Builder() .instrument(CurrencyPair.BTC_USDT) .last(new BigDecimal("26028.7")) .ask(new BigDecimal("26026.8")) @@ -75,7 +79,6 @@ void getTicker_valid() throws IOException { assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - @Test void getTickers_valid() throws IOException { List actual = gateioMarketDataService.getTickers(null); @@ -83,7 +86,6 @@ void getTickers_valid() throws IOException { assertThat(actual).hasSize(2); } - @Test void getCurrencies_valid() throws IOException { List actual = gateioMarketDataService.getCurrencies(); @@ -91,13 +93,11 @@ void getCurrencies_valid() throws IOException { assertThat(actual).containsOnly(Currency.BTC, Currency.ETH); } - @Test void getCurrencyPairs_valid() throws IOException { List actual = gateioMarketDataService.getCurrencyPairs(); - assertThat(actual).containsOnly(CurrencyPair.BTC_USDT, CurrencyPair.ETH_USDT, new CurrencyPair("CHZ/USDT")); + assertThat(actual) + .containsOnly(CurrencyPair.BTC_USDT, CurrencyPair.ETH_USDT, new CurrencyPair("CHZ/USDT")); } - - } diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceRawTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceRawTest.java index 19271898ae0..130221821be 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceRawTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceRawTest.java @@ -18,123 +18,118 @@ class GateioTradeServiceRawTest extends GateioExchangeWiremock { GateioTradeServiceRaw gateioTradeServiceRaw = (GateioTradeServiceRaw) exchange.getTradeService(); - GateioOrder sampleMarketOrder = GateioOrder.builder() - .id("342251629898") - .currencyPair(CurrencyPair.BTC_USDT) - .clientOrderId("t-valid-market-buy-order") - .amendText("-") - .type("market") - .account("spot") - .side(OrderType.BID) - .timeInForce("ioc") - .amount(BigDecimal.valueOf(20)) - .createdAt(Instant.parse("2023-06-03T22:07:38.451Z")) - .updatedAt(Instant.parse("2023-06-03T22:07:38.451Z")) - .status("closed") - .icebergAmount(BigDecimal.ZERO) - .amountLeftToFill(new BigDecimal("1.07319")) - .filledTotalQuote(new BigDecimal("18.92681")) - .avgDealPrice(new BigDecimal("27038.3")) - .fee(new BigDecimal("0.0000014")) - .price(BigDecimal.ZERO) - .feeCurrency(Currency.BTC) - .pointFee(BigDecimal.ZERO) - .gtFee(BigDecimal.ZERO) - .gtMakerFee(BigDecimal.ZERO) - .gtTakerFee(BigDecimal.ZERO) - .rebatedFee(BigDecimal.ZERO) - .gtDiscount(false) - .rebatedFeeCurrency(Currency.USDT) - .finishAs("filled") - .build(); - - + GateioOrder sampleMarketOrder = + GateioOrder.builder() + .id("342251629898") + .currencyPair(CurrencyPair.BTC_USDT) + .clientOrderId("t-valid-market-buy-order") + .amendText("-") + .type("market") + .account("spot") + .side(OrderType.BID) + .timeInForce("ioc") + .amount(BigDecimal.valueOf(20)) + .createdAt(Instant.parse("2023-06-03T22:07:38.451Z")) + .updatedAt(Instant.parse("2023-06-03T22:07:38.451Z")) + .status("closed") + .icebergAmount(BigDecimal.ZERO) + .amountLeftToFill(new BigDecimal("1.07319")) + .filledTotalQuote(new BigDecimal("18.92681")) + .avgDealPrice(new BigDecimal("27038.3")) + .fee(new BigDecimal("0.0000014")) + .price(BigDecimal.ZERO) + .feeCurrency(Currency.BTC) + .pointFee(BigDecimal.ZERO) + .gtFee(BigDecimal.ZERO) + .gtMakerFee(BigDecimal.ZERO) + .gtTakerFee(BigDecimal.ZERO) + .rebatedFee(BigDecimal.ZERO) + .gtDiscount(false) + .rebatedFeeCurrency(Currency.USDT) + .finishAs("filled") + .build(); @Test void listOrders() throws IOException { - List orders = gateioTradeServiceRaw.listOrders(CurrencyPair.BTC_USDT, OrderStatus.OPEN); + List orders = + gateioTradeServiceRaw.listOrders(CurrencyPair.BTC_USDT, OrderStatus.OPEN); assertThat(orders).hasSize(1); assertThat(orders.get(0).getId()).isEqualTo("339440374909"); assertThat(orders.get(0).getStatus()).isEqualTo("open"); - } - @Test void valid_market_buy_order() throws IOException { - GateioOrder gateioOrder = GateioOrder.builder() - .currencyPair(CurrencyPair.BTC_USDT) - .clientOrderId("t-valid-market-buy-order") - .type("market") - .account("spot") - .side(OrderType.BID) - .timeInForce("ioc") - .amount(BigDecimal.valueOf(20)) - .build(); + GateioOrder gateioOrder = + GateioOrder.builder() + .currencyPair(CurrencyPair.BTC_USDT) + .clientOrderId("t-valid-market-buy-order") + .type("market") + .account("spot") + .side(OrderType.BID) + .timeInForce("ioc") + .amount(BigDecimal.valueOf(20)) + .build(); GateioOrder actualResponse = gateioTradeServiceRaw.createOrder(gateioOrder); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(sampleMarketOrder); - } - @Test void valid_market_sell_order() throws IOException { - GateioOrder gateioOrder = GateioOrder.builder() - .currencyPair(CurrencyPair.BTC_USDT) - .clientOrderId("t-valid-market-sell-order") - .type("market") - .account("spot") - .side(OrderType.ASK) - .timeInForce("ioc") - .amount(new BigDecimal("0.0007")) - .build(); - + GateioOrder gateioOrder = + GateioOrder.builder() + .currencyPair(CurrencyPair.BTC_USDT) + .clientOrderId("t-valid-market-sell-order") + .type("market") + .account("spot") + .side(OrderType.ASK) + .timeInForce("ioc") + .amount(new BigDecimal("0.0007")) + .build(); GateioOrder actualResponse = gateioTradeServiceRaw.createOrder(gateioOrder); - GateioOrder expectedResponse = GateioOrder.builder() - .id("342260949533") - .currencyPair(CurrencyPair.BTC_USDT) - .clientOrderId("t-valid-market-sell-order") - .amendText("-") - .type("market") - .account("spot") - .side(OrderType.ASK) - .timeInForce("ioc") - .amount(new BigDecimal("0.0007")) - .createdAt(Instant.parse("2023-06-03T22:33:21.743Z")) - .updatedAt(Instant.parse("2023-06-03T22:33:21.743Z")) - .status("closed") - .icebergAmount(BigDecimal.ZERO) - .amountLeftToFill(BigDecimal.ZERO) - .filledTotalQuote(new BigDecimal("18.94382")) - .avgDealPrice(new BigDecimal("27062.6")) - .fee(new BigDecimal("0.03788764")) - .price(BigDecimal.ZERO) - .feeCurrency(Currency.USDT) - .pointFee(BigDecimal.ZERO) - .gtFee(BigDecimal.ZERO) - .gtMakerFee(BigDecimal.ZERO) - .gtTakerFee(BigDecimal.ZERO) - .rebatedFee(BigDecimal.ZERO) - .gtDiscount(false) - .rebatedFeeCurrency(Currency.BTC) - .finishAs("filled") - .build(); + GateioOrder expectedResponse = + GateioOrder.builder() + .id("342260949533") + .currencyPair(CurrencyPair.BTC_USDT) + .clientOrderId("t-valid-market-sell-order") + .amendText("-") + .type("market") + .account("spot") + .side(OrderType.ASK) + .timeInForce("ioc") + .amount(new BigDecimal("0.0007")) + .createdAt(Instant.parse("2023-06-03T22:33:21.743Z")) + .updatedAt(Instant.parse("2023-06-03T22:33:21.743Z")) + .status("closed") + .icebergAmount(BigDecimal.ZERO) + .amountLeftToFill(BigDecimal.ZERO) + .filledTotalQuote(new BigDecimal("18.94382")) + .avgDealPrice(new BigDecimal("27062.6")) + .fee(new BigDecimal("0.03788764")) + .price(BigDecimal.ZERO) + .feeCurrency(Currency.USDT) + .pointFee(BigDecimal.ZERO) + .gtFee(BigDecimal.ZERO) + .gtMakerFee(BigDecimal.ZERO) + .gtTakerFee(BigDecimal.ZERO) + .rebatedFee(BigDecimal.ZERO) + .gtDiscount(false) + .rebatedFeeCurrency(Currency.BTC) + .finishAs("filled") + .build(); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); - } - @Test void order_details() throws IOException { - GateioOrder actualResponse = gateioTradeServiceRaw.getOrder("342251629898", CurrencyPair.BTC_USDT); + GateioOrder actualResponse = + gateioTradeServiceRaw.getOrder("342251629898", CurrencyPair.BTC_USDT); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(sampleMarketOrder); } - - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceTest.java index 87af88e91f5..4fba1c32c26 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioTradeServiceTest.java @@ -30,136 +30,148 @@ class GateioTradeServiceTest extends GateioExchangeWiremock { GateioTradeService gateioTradeService = (GateioTradeService) exchange.getTradeService(); - @Test void place_order_not_enough_balance() { - MarketOrder marketOrder = new MarketOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) - .userReference("t-balance-test") - .originalAmount(BigDecimal.valueOf(100)) - .build(); + MarketOrder marketOrder = + new MarketOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) + .userReference("t-balance-test") + .originalAmount(BigDecimal.valueOf(100)) + .build(); assertThatExceptionOfType(FundsExceededException.class) .isThrownBy(() -> gateioTradeService.placeMarketOrder(marketOrder)); } - @Test void valid_market_buy_order() throws IOException { - MarketOrder marketOrder = new MarketOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) - .userReference("t-valid-market-buy-order") - .originalAmount(BigDecimal.valueOf(20)) - .build(); + MarketOrder marketOrder = + new MarketOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) + .userReference("t-valid-market-buy-order") + .originalAmount(BigDecimal.valueOf(20)) + .build(); String actualResponse = gateioTradeService.placeMarketOrder(marketOrder); assertThat(actualResponse).isEqualTo("342251629898"); - } - @Test void valid_market_sell_order() throws IOException { - MarketOrder marketOrder = new MarketOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) - .userReference("t-valid-market-sell-order") - .originalAmount(new BigDecimal("0.0007")) - .build(); + MarketOrder marketOrder = + new MarketOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) + .userReference("t-valid-market-sell-order") + .originalAmount(new BigDecimal("0.0007")) + .build(); String actualResponse = gateioTradeService.placeMarketOrder(marketOrder); assertThat(actualResponse).isEqualTo("342260949533"); - } - @Test void valid_limit_sell_order() throws IOException { - LimitOrder limitOrder = new LimitOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) - .userReference("t-valid-limit-sell-order") - .originalAmount(new BigDecimal("0.00068")) - .limitPrice(new BigDecimal("29240.7")) - .build(); + LimitOrder limitOrder = + new LimitOrder.Builder(OrderType.ASK, CurrencyPair.BTC_USDT) + .userReference("t-valid-limit-sell-order") + .originalAmount(new BigDecimal("0.00068")) + .limitPrice(new BigDecimal("29240.7")) + .build(); String actualResponse = gateioTradeService.placeLimitOrder(limitOrder); assertThat(actualResponse).isEqualTo("373824296029"); } - @Test void valid_cancel_order() throws IOException { - boolean actual = gateioTradeService.cancelOrder(new DefaultCancelOrderByInstrumentAndIdParams(CurrencyPair.BTC_USDT, "376835979523")); + boolean actual = + gateioTradeService.cancelOrder( + new DefaultCancelOrderByInstrumentAndIdParams(CurrencyPair.BTC_USDT, "376835979523")); assertThat(actual).isTrue(); } - @Test void valid_limit_buy_order() throws IOException { - LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) - .userReference("t-valid-limit-buy-order") - .originalAmount(new BigDecimal("0.00068")) - .limitPrice(new BigDecimal("10000.7")) - .build(); + LimitOrder limitOrder = + new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) + .userReference("t-valid-limit-buy-order") + .originalAmount(new BigDecimal("0.00068")) + .limitPrice(new BigDecimal("10000.7")) + .build(); String actualResponse = gateioTradeService.placeLimitOrder(limitOrder); assertThat(actualResponse).isEqualTo("376835979523"); } - @Test void buy_order_details() throws IOException { - MarketOrder expected = new MarketOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) - .id("342251629898") - .userReference("t-valid-market-buy-order") - .timestamp(Date.from(Instant.parse("2023-06-03T22:07:38.451Z"))) - .originalAmount(BigDecimal.valueOf(20)) - .orderStatus(OrderStatus.FILLED) - .cumulativeAmount(new BigDecimal("18.92681")) - .averagePrice(new BigDecimal("27038.3")) - .fee(new BigDecimal("0.0000014")) - .build(); - - Collection orders = gateioTradeService.getOrder(new DefaultQueryOrderParamInstrument(CurrencyPair.BTC_USDT, "342251629898")); + MarketOrder expected = + new MarketOrder.Builder(OrderType.BID, CurrencyPair.BTC_USDT) + .id("342251629898") + .userReference("t-valid-market-buy-order") + .timestamp(Date.from(Instant.parse("2023-06-03T22:07:38.451Z"))) + .originalAmount(BigDecimal.valueOf(20)) + .orderStatus(OrderStatus.FILLED) + .cumulativeAmount(new BigDecimal("18.92681")) + .averagePrice(new BigDecimal("27038.3")) + .fee(new BigDecimal("0.0000014")) + .build(); + + Collection orders = + gateioTradeService.getOrder( + new DefaultQueryOrderParamInstrument(CurrencyPair.BTC_USDT, "342251629898")); assertThat(orders).hasSize(1); assertThat(orders).first().usingRecursiveComparison().isEqualTo(expected); } - @Test void sell_order_details() throws IOException { - MarketOrder expected = new MarketOrder.Builder(OrderType.ASK, new CurrencyPair("VAI/USDT")) - .id("425539509181") - .userReference("t-valid-market-sell-order") - .timestamp(Date.from(Instant.parse("2023-10-28T18:40:02.006Z"))) - .originalAmount(new BigDecimal("105.58")) - .orderStatus(OrderStatus.FILLED) - .cumulativeAmount(new BigDecimal("105.58")) - .averagePrice(new BigDecimal("0.079888")) - .fee(new BigDecimal("0.01686915008")) - .build(); - - Collection orders = gateioTradeService.getOrder(new DefaultQueryOrderParamInstrument(new CurrencyPair("VAI/USDT"), "425539509181")); + MarketOrder expected = + new MarketOrder.Builder(OrderType.ASK, new CurrencyPair("VAI/USDT")) + .id("425539509181") + .userReference("t-valid-market-sell-order") + .timestamp(Date.from(Instant.parse("2023-10-28T18:40:02.006Z"))) + .originalAmount(new BigDecimal("105.58")) + .orderStatus(OrderStatus.FILLED) + .cumulativeAmount(new BigDecimal("105.58")) + .averagePrice(new BigDecimal("0.079888")) + .fee(new BigDecimal("0.01686915008")) + .build(); + + Collection orders = + gateioTradeService.getOrder( + new DefaultQueryOrderParamInstrument(new CurrencyPair("VAI/USDT"), "425539509181")); assertThat(orders).hasSize(1); assertThat(orders).first().usingRecursiveComparison().isEqualTo(expected); } - @Test void trade_history() throws IOException { - UserTrades userTrades = gateioTradeService.getTradeHistory(GateioTradeHistoryParams.builder() - .currencyPair(CurrencyPair.BTC_USDT) - .pageLength(2) - .pageNumber(2) - .startTime(Date.from(Instant.ofEpochSecond(1691617924))) - .endTime(Date.from(Instant.ofEpochSecond(1691704324))) - .build()); + UserTrades userTrades = + gateioTradeService.getTradeHistory( + GateioTradeHistoryParams.builder() + .currencyPair(CurrencyPair.BTC_USDT) + .pageLength(2) + .pageNumber(2) + .startTime(Date.from(Instant.ofEpochSecond(1691617924))) + .endTime(Date.from(Instant.ofEpochSecond(1691704324))) + .build()); assertThat(userTrades.getUserTrades()).hasSize(2); - GateioUserTrade expected = new GateioUserTrade(OrderType.ASK, new BigDecimal("0.00005"), CurrencyPair.BTC_USDT, - new BigDecimal("29447.2"), Date.from(Instant.ofEpochMilli(1691702286356L)), "6068789332", - "381064942553", new BigDecimal("0.00294472"), Currency.USDT, "-", Role.TAKER); + GateioUserTrade expected = + new GateioUserTrade( + OrderType.ASK, + new BigDecimal("0.00005"), + CurrencyPair.BTC_USDT, + new BigDecimal("29447.2"), + Date.from(Instant.ofEpochMilli(1691702286356L)), + "6068789332", + "381064942553", + new BigDecimal("0.00294472"), + Currency.USDT, + "-", + Role.TAKER); UserTrade actual = userTrades.getUserTrades().get(0); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioV4DigestTest.java b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioV4DigestTest.java index 472a6c6cb73..9f9594c7231 100644 --- a/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioV4DigestTest.java +++ b/xchange-gateio-v4/src/test/java/org/knowm/xchange/gateio/service/GateioV4DigestTest.java @@ -14,8 +14,7 @@ @ExtendWith(MockitoExtension.class) class GateioV4DigestTest { - @Mock - RestInvocation restInvocation; + @Mock RestInvocation restInvocation; @Test void signature() { @@ -30,9 +29,9 @@ void signature() { when(restInvocation.getHttpHeadersFromParams()).thenReturn(headers); String actual = gateioV4Digest.digestParams(restInvocation); - String expected = "de31e211a60623ba2c41e65a3c21e550400ffccfef55578173e09f2b34cf46b426c587f01b4c12474608dc856b1ba226a71004f7989603236c885c23275d5577"; + String expected = + "de31e211a60623ba2c41e65a3c21e550400ffccfef55578173e09f2b34cf46b426c587f01b4c12474608dc856b1ba226a71004f7989603236c885c23275d5577"; assertThat(actual).isEqualTo(expected); } - -} \ No newline at end of file +} diff --git a/xchange-gateio-v4/src/test/java/si/mazi/rescu/BodyLoggingRestInvocationHandler.java b/xchange-gateio-v4/src/test/java/si/mazi/rescu/BodyLoggingRestInvocationHandler.java index d955cd17b8c..f3cc539b730 100644 --- a/xchange-gateio-v4/src/test/java/si/mazi/rescu/BodyLoggingRestInvocationHandler.java +++ b/xchange-gateio-v4/src/test/java/si/mazi/rescu/BodyLoggingRestInvocationHandler.java @@ -3,22 +3,21 @@ import java.io.IOException; import lombok.extern.slf4j.Slf4j; -/** - * Invocation handler that logs the raw textual response body - */ +/** Invocation handler that logs the raw textual response body */ @Slf4j public class BodyLoggingRestInvocationHandler extends RestInvocationHandler { - BodyLoggingRestInvocationHandler(Class restInterface, String url, ClientConfig config) { - super(restInterface, url, config); - } + BodyLoggingRestInvocationHandler(Class restInterface, String url, ClientConfig config) { + super(restInterface, url, config); + } - @Override - protected Object mapInvocationResult(InvocationResult invocationResult, RestMethodMetadata methodMetadata) throws IOException { - // log the body - log.info(invocationResult.getHttpBody()); + @Override + protected Object mapInvocationResult( + InvocationResult invocationResult, RestMethodMetadata methodMetadata) throws IOException { + // log the body + log.info(invocationResult.getHttpBody()); - // do the normal processing - return super.mapInvocationResult(invocationResult, methodMetadata); - } + // do the normal processing + return super.mapInvocationResult(invocationResult, methodMetadata); + } } diff --git a/xchange-gateio-v4/src/test/java/si/mazi/rescu/CustomRestProxyFactoryImpl.java b/xchange-gateio-v4/src/test/java/si/mazi/rescu/CustomRestProxyFactoryImpl.java index 6594f8ec2d1..62747371b97 100644 --- a/xchange-gateio-v4/src/test/java/si/mazi/rescu/CustomRestProxyFactoryImpl.java +++ b/xchange-gateio-v4/src/test/java/si/mazi/rescu/CustomRestProxyFactoryImpl.java @@ -1,13 +1,18 @@ package si.mazi.rescu; /** - * The implementation of {@link IRestProxyFactory} that instantiates {@link BodyLoggingRestInvocationHandler} + * The implementation of {@link IRestProxyFactory} that instantiates {@link + * BodyLoggingRestInvocationHandler} */ public class CustomRestProxyFactoryImpl implements IRestProxyFactory { @Override - public I createProxy(Class restInterface, String baseUrl, ClientConfig config, Interceptor... interceptors) { - return RestProxyFactory.createProxy(restInterface, RestProxyFactory.wrap(new BodyLoggingRestInvocationHandler(restInterface, baseUrl, config), interceptors)); + public I createProxy( + Class restInterface, String baseUrl, ClientConfig config, Interceptor... interceptors) { + return RestProxyFactory.createProxy( + restInterface, + RestProxyFactory.wrap( + new BodyLoggingRestInvocationHandler(restInterface, baseUrl, config), interceptors)); } @Override diff --git a/xchange-gateio/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java b/xchange-gateio/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java index e23c9d051db..88c8b18a590 100644 --- a/xchange-gateio/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java +++ b/xchange-gateio/src/test/java/org/knowm/xchange/gateio/service/GateioMarketDataServiceTest.java @@ -55,7 +55,7 @@ public void valid_orderbook() throws IOException { assertThat(actual) .usingRecursiveComparison() - .ignoringFieldsMatchingRegexes(".*userReference",".*lock") + .ignoringFieldsMatchingRegexes(".*userReference", ".*lock") .isEqualTo(expected); } } diff --git a/xchange-globitex/src/main/java/org/knowm/xchange/globitex/service/GlobitexAccountService.java b/xchange-globitex/src/main/java/org/knowm/xchange/globitex/service/GlobitexAccountService.java index 6a0203b5b60..5d9d386d91a 100644 --- a/xchange-globitex/src/main/java/org/knowm/xchange/globitex/service/GlobitexAccountService.java +++ b/xchange-globitex/src/main/java/org/knowm/xchange/globitex/service/GlobitexAccountService.java @@ -23,5 +23,4 @@ public AccountInfo getAccountInfo() throws IOException { public TradeHistoryParams createFundingHistoryParams() { return new TradeHistoryParamsAll(); } - } diff --git a/xchange-kraken/src/test/java/org/knowm/xchange/kraken/service/KrakenMarketDataServiceIntegration.java b/xchange-kraken/src/test/java/org/knowm/xchange/kraken/service/KrakenMarketDataServiceIntegration.java index fdb695f278c..f211bee2175 100644 --- a/xchange-kraken/src/test/java/org/knowm/xchange/kraken/service/KrakenMarketDataServiceIntegration.java +++ b/xchange-kraken/src/test/java/org/knowm/xchange/kraken/service/KrakenMarketDataServiceIntegration.java @@ -1,6 +1,5 @@ package org.knowm.xchange.kraken.service; - import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; @@ -22,16 +21,17 @@ public void valid_tickers() throws IOException { List tickers = exchange.getMarketDataService().getTickers(null); assertThat(tickers).isNotEmpty(); - assertThat(tickers).allSatisfy(ticker -> { - assertThat(ticker.getInstrument()).isNotNull(); - assertThat(ticker.getLast()).isNotNull(); - if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { - assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); - } - }); + assertThat(tickers) + .allSatisfy( + ticker -> { + assertThat(ticker.getInstrument()).isNotNull(); + assertThat(ticker.getLast()).isNotNull(); + if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { + assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); + } + }); } - @Test public void valid_single_ticker() throws IOException { Ticker ticker = exchange.getMarketDataService().getTicker(CurrencyPair.BTC_USDT); @@ -42,10 +42,8 @@ public void valid_single_ticker() throws IOException { if (ticker.getBid().signum() > 0 && ticker.getAsk().signum() > 0) { assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); } - } - @Test public void valid_orderbook() throws IOException { OrderBook orderBook = exchange.getMarketDataService().getOrderBook(CurrencyPair.BTC_USDT); @@ -53,18 +51,21 @@ public void valid_orderbook() throws IOException { assertThat(orderBook.getBids()).isNotEmpty(); assertThat(orderBook.getAsks()).isNotEmpty(); - assertThat(orderBook.getAsks().get(0).getLimitPrice()).isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); - - assertThat(orderBook.getBids()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); - }); - - assertThat(orderBook.getAsks()).allSatisfy(limitOrder -> { - assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); - }); - + assertThat(orderBook.getAsks().get(0).getLimitPrice()) + .isGreaterThan(orderBook.getBids().get(0).getLimitPrice()); + + assertThat(orderBook.getBids()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.BID); + }); + + assertThat(orderBook.getAsks()) + .allSatisfy( + limitOrder -> { + assertThat(limitOrder.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); + assertThat(limitOrder.getType()).isEqualTo(OrderType.ASK); + }); } - -} \ No newline at end of file +} diff --git a/xchange-kucoin/src/test/java/org/knowm/xchange/kucoin/KucoinMarketDataServiceIntegration.java b/xchange-kucoin/src/test/java/org/knowm/xchange/kucoin/KucoinMarketDataServiceIntegration.java index 569e6de48dc..8743cdd7c30 100644 --- a/xchange-kucoin/src/test/java/org/knowm/xchange/kucoin/KucoinMarketDataServiceIntegration.java +++ b/xchange-kucoin/src/test/java/org/knowm/xchange/kucoin/KucoinMarketDataServiceIntegration.java @@ -77,23 +77,24 @@ public void testGetTicker() throws Exception { checkTimestamp(ticker.getTimestamp()); } - @Test public void valid_tickers() throws IOException { List tickers = exchange().getMarketDataService().getTickers(null); assertThat(tickers).isNotEmpty(); - assertThat(tickers).allSatisfy(ticker -> { - assertThat(ticker.getInstrument()).isNotNull(); - assertThat(ticker.getLast()).isPositive(); + assertThat(tickers) + .allSatisfy( + ticker -> { + assertThat(ticker.getInstrument()).isNotNull(); + assertThat(ticker.getLast()).isPositive(); - assertThat(ticker.getBidSize()).isPositive(); - assertThat(ticker.getAskSize()).isPositive(); + assertThat(ticker.getBidSize()).isPositive(); + assertThat(ticker.getAskSize()).isPositive(); - assertThat(ticker.getAsk()).isPositive(); - assertThat(ticker.getBid()).isPositive(); - assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); - }); + assertThat(ticker.getAsk()).isPositive(); + assertThat(ticker.getBid()).isPositive(); + assertThat(ticker.getBid()).isLessThan(ticker.getAsk()); + }); } @Test diff --git a/xchange-lykke/src/main/java/org/knowm/xchange/lykke/service/LykkeAccountService.java b/xchange-lykke/src/main/java/org/knowm/xchange/lykke/service/LykkeAccountService.java index 11397a675fb..b9cebfbc368 100644 --- a/xchange-lykke/src/main/java/org/knowm/xchange/lykke/service/LykkeAccountService.java +++ b/xchange-lykke/src/main/java/org/knowm/xchange/lykke/service/LykkeAccountService.java @@ -16,5 +16,4 @@ public LykkeAccountService(Exchange exchange) { public AccountInfo getAccountInfo() throws IOException { return LykkeAdapter.adaptAccountInfo(getWallets()); } - } diff --git a/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinFuturesAccountService.java b/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinFuturesAccountService.java index 25fe103ebf0..35f189b3e2b 100644 --- a/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinFuturesAccountService.java +++ b/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinFuturesAccountService.java @@ -45,5 +45,4 @@ public String requestDepositAddress(Currency currency, String... args) throws IO public TradeHistoryParams createFundingHistoryParams() { throw new NotAvailableFromExchangeException(); } - } diff --git a/xchange-okex/src/main/java/org/knowm/xchange/okex/Okex.java b/xchange-okex/src/main/java/org/knowm/xchange/okex/Okex.java index 30312eec2d3..cfbd4cae7a0 100644 --- a/xchange-okex/src/main/java/org/knowm/xchange/okex/Okex.java +++ b/xchange-okex/src/main/java/org/knowm/xchange/okex/Okex.java @@ -65,9 +65,9 @@ OkexResponse> getTicker( @Path("/market/tickers") @Consumes(MediaType.APPLICATION_JSON) OkexResponse> getTickers( - @QueryParam("instType") String instType, - @HeaderParam("X-SIMULATED-TRADING") String simulatedTrading) - throws IOException, OkexException; + @QueryParam("instType") String instType, + @HeaderParam("X-SIMULATED-TRADING") String simulatedTrading) + throws IOException, OkexException; @GET @Path("/market/books") diff --git a/xchange-okex/src/main/java/org/knowm/xchange/okex/OkexAdapters.java b/xchange-okex/src/main/java/org/knowm/xchange/okex/OkexAdapters.java index 33ab822c15c..cc7a36b6316 100644 --- a/xchange-okex/src/main/java/org/knowm/xchange/okex/OkexAdapters.java +++ b/xchange-okex/src/main/java/org/knowm/xchange/okex/OkexAdapters.java @@ -192,7 +192,7 @@ public static OkexOrderRequest adaptOrder( public static LimitOrder adaptLimitOrder( OkexPublicOrder okexPublicOrder, Instrument instrument, OrderType orderType, Date timestamp) { return adaptOrderbookOrder( - okexPublicOrder.getVolume(), okexPublicOrder.getPrice(), instrument, orderType,timestamp); + okexPublicOrder.getVolume(), okexPublicOrder.getPrice(), instrument, orderType, timestamp); } public static OrderBook adaptOrderBook( @@ -204,12 +204,14 @@ public static OrderBook adaptOrderBook( okexOrderbooks .get(0) .getAsks() - .forEach(okexAsk -> asks.add(adaptLimitOrder(okexAsk, instrument, OrderType.ASK, timeStamp))); + .forEach( + okexAsk -> asks.add(adaptLimitOrder(okexAsk, instrument, OrderType.ASK, timeStamp))); okexOrderbooks .get(0) .getBids() - .forEach(okexBid -> bids.add(adaptLimitOrder(okexBid, instrument, OrderType.BID, timeStamp))); + .forEach( + okexBid -> bids.add(adaptLimitOrder(okexBid, instrument, OrderType.BID, timeStamp))); return new OrderBook(timeStamp, asks, bids); } @@ -220,7 +222,11 @@ public static OrderBook adaptOrderBook( } public static LimitOrder adaptOrderbookOrder( - BigDecimal amount, BigDecimal price, Instrument instrument, Order.OrderType orderType, Date timestamp) { + BigDecimal amount, + BigDecimal price, + Instrument instrument, + Order.OrderType orderType, + Date timestamp) { return new LimitOrder(orderType, amount, instrument, "", timestamp, price); } @@ -235,10 +241,16 @@ public static Ticker adaptTicker(OkexTicker okexTicker) { .high(okexTicker.getHigh24h()) .low(okexTicker.getLow24h()) // .vwap(null) - .volume((okexTicker.getInstrumentType().equals("SWAP") || okexTicker.getInstrumentType().equals("FUTURES")) ? - okexTicker.getVolumeCurrency24h() : okexTicker.getVolume24h()) - .quoteVolume((okexTicker.getInstrumentType().equals("SWAP") || okexTicker.getInstrumentType().equals("FUTURES")) ? - okexTicker.getVolumeCurrency24h().multiply(okexTicker.getLast()) : okexTicker.getVolumeCurrency24h()) + .volume( + (okexTicker.getInstrumentType().equals("SWAP") + || okexTicker.getInstrumentType().equals("FUTURES")) + ? okexTicker.getVolumeCurrency24h() + : okexTicker.getVolume24h()) + .quoteVolume( + (okexTicker.getInstrumentType().equals("SWAP") + || okexTicker.getInstrumentType().equals("FUTURES")) + ? okexTicker.getVolumeCurrency24h().multiply(okexTicker.getLast()) + : okexTicker.getVolumeCurrency24h()) .timestamp(okexTicker.getTimestamp()) .bidSize(okexTicker.getBidSize()) .askSize(okexTicker.getAskSize()) diff --git a/xchange-okex/src/main/java/org/knowm/xchange/okex/dto/OkexInstType.java b/xchange-okex/src/main/java/org/knowm/xchange/okex/dto/OkexInstType.java index ba94482836f..677a1ee7802 100644 --- a/xchange-okex/src/main/java/org/knowm/xchange/okex/dto/OkexInstType.java +++ b/xchange-okex/src/main/java/org/knowm/xchange/okex/dto/OkexInstType.java @@ -3,6 +3,10 @@ import org.knowm.xchange.service.marketdata.params.Params; public enum OkexInstType implements Params { - - SPOT, MARGIN, SWAP, FUTURES, OPTION, ANY + SPOT, + MARGIN, + SWAP, + FUTURES, + OPTION, + ANY } diff --git a/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataService.java b/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataService.java index e11b7f1d243..30159f34ece 100644 --- a/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataService.java +++ b/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataService.java @@ -86,12 +86,13 @@ public FundingRate getFundingRate(Instrument instrument) throws IOException { getOkexFundingRate(OkexAdapters.adaptInstrument(instrument)).getData()); } - public List getTickers(Params params) throws IOException { if (!(params instanceof OkexInstType)) { throw new IllegalArgumentException("Params must be instance of OkexInstType"); } OkexInstType instType = (OkexInstType) params; - return getOkexTickers(instType).getData().stream().map(OkexAdapters::adaptTicker).collect(Collectors.toList()); + return getOkexTickers(instType).getData().stream() + .map(OkexAdapters::adaptTicker) + .collect(Collectors.toList()); } } diff --git a/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataServiceRaw.java b/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataServiceRaw.java index dca03faf4aa..21ef7f91501 100644 --- a/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataServiceRaw.java +++ b/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexMarketDataServiceRaw.java @@ -55,32 +55,32 @@ public OkexResponse> getOkexTicker(String instrumentId) try { return decorateApiCall( () -> - okex.getTicker( - instrumentId, - (String) - exchange - .getExchangeSpecification() - .getExchangeSpecificParametersItem(PARAM_SIMULATED))) - .withRateLimiter(rateLimiter(Okex.tickerPath)) - .call(); + okex.getTicker( + instrumentId, + (String) + exchange + .getExchangeSpecification() + .getExchangeSpecificParametersItem(PARAM_SIMULATED))) + .withRateLimiter(rateLimiter(Okex.tickerPath)) + .call(); } catch (OkexException e) { throw handleError(e); } } public OkexResponse> getOkexTickers(OkexInstType instType) - throws OkexException, IOException { + throws OkexException, IOException { try { return decorateApiCall( () -> - okex.getTickers( - instType.toString(), - (String) - exchange - .getExchangeSpecification() - .getExchangeSpecificParametersItem(PARAM_SIMULATED))) - .withRateLimiter(rateLimiter(Okex.tickersPath)) - .call(); + okex.getTickers( + instType.toString(), + (String) + exchange + .getExchangeSpecification() + .getExchangeSpecificParametersItem(PARAM_SIMULATED))) + .withRateLimiter(rateLimiter(Okex.tickersPath)) + .call(); } catch (OkexException e) { throw handleError(e); } diff --git a/xchange-okex/src/test/java/org/knowm/xchange/okex/OkexPublicDataIntegration.java b/xchange-okex/src/test/java/org/knowm/xchange/okex/OkexPublicDataIntegration.java index e2cc298ef9d..ed64a1fa4fa 100644 --- a/xchange-okex/src/test/java/org/knowm/xchange/okex/OkexPublicDataIntegration.java +++ b/xchange-okex/src/test/java/org/knowm/xchange/okex/OkexPublicDataIntegration.java @@ -7,7 +7,6 @@ import java.math.BigDecimal; import java.util.List; import java.util.Objects; -import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -79,8 +78,11 @@ public void checkTickers() throws IOException { List spotTickers = exchange.getMarketDataService().getTickers(OkexInstType.SPOT); List swapTickers = exchange.getMarketDataService().getTickers(OkexInstType.SWAP); - assertTrue(spotTickers.stream().anyMatch(f->f.getInstrument().equals(new CurrencyPair("BTC/USDT")))); - assertTrue(swapTickers.stream().anyMatch(f -> f.getInstrument().equals(new FuturesContract("BTC/USDT/SWAP")))); + assertTrue( + spotTickers.stream().anyMatch(f -> f.getInstrument().equals(new CurrencyPair("BTC/USDT")))); + assertTrue( + swapTickers.stream() + .anyMatch(f -> f.getInstrument().equals(new FuturesContract("BTC/USDT/SWAP")))); } @Test diff --git a/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceStreamingMarketDataService.java b/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceStreamingMarketDataService.java index 9606e13dffa..61cf2b7f3e2 100644 --- a/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceStreamingMarketDataService.java +++ b/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceStreamingMarketDataService.java @@ -171,7 +171,8 @@ public Observable getTicker(Instrument instrument, Object... args) { return getRawBookTicker(instrument) .map(raw -> raw.toTicker(instrument instanceof FuturesContract)); } - return getRawTicker(instrument).map(raw -> BinanceAdapters.toTicker(raw, instrument instanceof FuturesContract)); + return getRawTicker(instrument) + .map(raw -> BinanceAdapters.toTicker(raw, instrument instanceof FuturesContract)); } @Override @@ -274,8 +275,8 @@ private Observable klinesStream(Instrument instrument, KlineInterv * subscribe to this api and {@link #getOrderBook(Instrument, Object...)} at the same time. */ @Override - public Observable> getOrderBookUpdates(Instrument instrument, - Object... args) { + public Observable> getOrderBookUpdates( + Instrument instrument, Object... args) { if (!service.isLiveSubscriptionEnabled() && !service.getProductSubscription().getOrderBook().contains(instrument)) { throw new UpFrontSubscriptionRequiredException(); diff --git a/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceUserDataStreamingService.java b/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceUserDataStreamingService.java index 27545efff80..2354da0c25a 100644 --- a/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceUserDataStreamingService.java +++ b/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceUserDataStreamingService.java @@ -6,7 +6,6 @@ import info.bitrich.xchangestream.service.netty.WebSocketClientCompressionAllowClientNoContextAndServerNoContextHandler; import io.netty.handler.codec.http.websocketx.extensions.WebSocketClientExtensionHandler; import io.reactivex.rxjava3.core.Observable; -import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceFuturesPublicStreamsTest.java b/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceFuturesPublicStreamsTest.java index 034477edd80..445f553b1ac 100644 --- a/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceFuturesPublicStreamsTest.java +++ b/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceFuturesPublicStreamsTest.java @@ -30,8 +30,7 @@ public void setup() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(BinanceFutureStreamingExchange.class); exchangeSpecification.setExchangeSpecificParametersItem(EXCHANGE_TYPE, FUTURES); - exchange = - StreamingExchangeFactory.INSTANCE.createExchange(exchangeSpecification); + exchange = StreamingExchangeFactory.INSTANCE.createExchange(exchangeSpecification); exchange .connect( diff --git a/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceManualExample.java b/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceManualExample.java index cf11e3efe93..49579ac6571 100644 --- a/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceManualExample.java +++ b/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceManualExample.java @@ -142,8 +142,7 @@ private static Disposable orderbooks(StreamingExchange exchange, String identifi throwable -> LOG.error("ERROR in getting order book: ", throwable)); } - private static Disposable orderbooksIncremental( - StreamingExchange exchange, String identifier) { + private static Disposable orderbooksIncremental(StreamingExchange exchange, String identifier) { return exchange .getStreamingMarketDataService() .getOrderBookUpdates(CurrencyPair.LTC_BTC) diff --git a/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceStreamExchangeTypeIntegration.java b/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceStreamExchangeTypeIntegration.java index 847e3be6b07..78655cc0145 100644 --- a/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceStreamExchangeTypeIntegration.java +++ b/xchange-stream-binance/src/test/java/info/bitrich/xchangestream/binance/BinanceStreamExchangeTypeIntegration.java @@ -29,42 +29,44 @@ public class BinanceStreamExchangeTypeIntegration { @Test public void testConnections() throws InterruptedException, IOException { - testConnection(new CurrencyPair("ETH/USDT"), getSpec(SPOT, false)); + testConnection(new CurrencyPair("ETH/USDT"), getSpec(SPOT, false)); testConnection(new CurrencyPair("ETH/USDT"), getSpec1(SPOT, true)); testConnection(new FuturesContract("ETH/USDT/PERP"), getSpec1(FUTURES, false)); - testConnection(new FuturesContract("ETH/USDT/PERP"), getSpec(FUTURES, true)); + testConnection(new FuturesContract("ETH/USDT/PERP"), getSpec(FUTURES, true)); } private static void testConnection(Instrument instrument, ExchangeSpecification spec) throws InterruptedException, IOException { - StreamingExchange exchange = - StreamingExchangeFactory.INSTANCE.createExchange(spec); - ProductSubscription subscription = ProductSubscription.create() - .addOrderbook(instrument) - .addTicker(instrument) - .addFundingRates(instrument) - .addTrades(instrument) - .build(); + StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange(spec); + ProductSubscription subscription = + ProductSubscription.create() + .addOrderbook(instrument) + .addTicker(instrument) + .addFundingRates(instrument) + .addTrades(instrument) + .build(); exchange.connect(subscription).blockingAwait(); Trades trades = exchange.getMarketDataService().getTrades(instrument); - for(Trade trade : trades.getTrades()) - tradeCheck(trade,instrument); - Disposable disposable = exchange.getStreamingMarketDataService().getTicker(instrument) - .subscribe(t -> tickerCheck(t, instrument)); + for (Trade trade : trades.getTrades()) tradeCheck(trade, instrument); + Disposable disposable = + exchange + .getStreamingMarketDataService() + .getTicker(instrument) + .subscribe(t -> tickerCheck(t, instrument)); Thread.sleep(3000L); disposable.dispose(); Thread.sleep(500L); exchange.disconnect().blockingAwait(); } - private static void tickerCheck(Ticker ticker, Instrument instrument) { + private static void tickerCheck(Ticker ticker, Instrument instrument) { assertThat(ticker.getInstrument()).isEqualTo(instrument); assertThat(ticker.getHigh()).isNotNull(); assertThat(ticker.getVolume()).isNotNull(); assertThat(ticker.getTimestamp()).isNotNull(); } - private static void tradeCheck(Trade trade, Instrument instrument) { + private static void tradeCheck(Trade trade, Instrument instrument) { assertThat(trade.getInstrument()).isEqualTo(instrument); assertThat(trade.getOriginalAmount()).isNotNull(); assertThat(trade.getPrice()).isNotNull(); @@ -76,7 +78,8 @@ private static ExchangeSpecification getSpec(ExchangeType exchangeType, boolean if (exchangeType == SPOT) { exchangeSpecification = new BinanceStreamingExchange().getDefaultExchangeSpecification(); } else { - exchangeSpecification = new BinanceFutureStreamingExchange().getDefaultExchangeSpecification(); + exchangeSpecification = + new BinanceFutureStreamingExchange().getDefaultExchangeSpecification(); } exchangeSpecification.setExchangeSpecificParametersItem(EXCHANGE_TYPE, exchangeType); if (useSandbox) { @@ -88,11 +91,9 @@ private static ExchangeSpecification getSpec(ExchangeType exchangeType, boolean private static ExchangeSpecification getSpec1(ExchangeType exchangeType, boolean useSandbox) { ExchangeSpecification exchangeSpecification; if (exchangeType == SPOT) { - exchangeSpecification = - new ExchangeSpecification(BinanceStreamingExchange.class); + exchangeSpecification = new ExchangeSpecification(BinanceStreamingExchange.class); } else { - exchangeSpecification = - new ExchangeSpecification(BinanceFutureStreamingExchange.class); + exchangeSpecification = new ExchangeSpecification(BinanceFutureStreamingExchange.class); } exchangeSpecification.setExchangeSpecificParametersItem(EXCHANGE_TYPE, exchangeType); if (useSandbox) { diff --git a/xchange-stream-bitmex/src/test/java/info/bitrich/xchangestream/bitmex/BitmexTest.java b/xchange-stream-bitmex/src/test/java/info/bitrich/xchangestream/bitmex/BitmexTest.java index f181a84a340..7425982e2d4 100644 --- a/xchange-stream-bitmex/src/test/java/info/bitrich/xchangestream/bitmex/BitmexTest.java +++ b/xchange-stream-bitmex/src/test/java/info/bitrich/xchangestream/bitmex/BitmexTest.java @@ -49,11 +49,7 @@ private void awaitCompletable(Completable completable) { } private void awaitDataCount(Observable observable) { - observable - .test() - .assertNoErrors() - .awaitCount(BitmexTest.MIN_DATA_COUNT) - .dispose(); + observable.test().assertNoErrors().awaitCount(BitmexTest.MIN_DATA_COUNT).dispose(); } @Test diff --git a/xchange-stream-bitstamp/src/test/java/info/bitrich/xchangestream/bitstamp/BitstampStreamingMarketDataServiceV2Test.java b/xchange-stream-bitstamp/src/test/java/info/bitrich/xchangestream/bitstamp/BitstampStreamingMarketDataServiceV2Test.java index 29b982025d6..24473d3444e 100644 --- a/xchange-stream-bitstamp/src/test/java/info/bitrich/xchangestream/bitstamp/BitstampStreamingMarketDataServiceV2Test.java +++ b/xchange-stream-bitstamp/src/test/java/info/bitrich/xchangestream/bitstamp/BitstampStreamingMarketDataServiceV2Test.java @@ -26,10 +26,10 @@ import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) -public class BitstampStreamingMarketDataServiceV2Test extends BitstampStreamingMarketDataServiceBaseTest { +public class BitstampStreamingMarketDataServiceV2Test + extends BitstampStreamingMarketDataServiceBaseTest { - @Mock - private BitstampStreamingService streamingService; + @Mock private BitstampStreamingService streamingService; private BitstampStreamingMarketDataService marketDataService; diff --git a/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/BTCMarketsStreamingAdapters.java b/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/BTCMarketsStreamingAdapters.java index d14ab616ed4..f8de36dc648 100644 --- a/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/BTCMarketsStreamingAdapters.java +++ b/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/BTCMarketsStreamingAdapters.java @@ -76,5 +76,4 @@ public static Trade adaptTradeMessageToTrade(BTCMarketsWebSocketTradeMessage mes .type(BTCMarketsAdapters.adaptOrderType(message.getSide())) .build(); } - } diff --git a/xchange-stream-bybit/src/main/java/dto/BybitSubscribeMessage.java b/xchange-stream-bybit/src/main/java/dto/BybitSubscribeMessage.java index e3c01595d52..3dc25dc5af3 100644 --- a/xchange-stream-bybit/src/main/java/dto/BybitSubscribeMessage.java +++ b/xchange-stream-bybit/src/main/java/dto/BybitSubscribeMessage.java @@ -7,7 +7,6 @@ @Data @AllArgsConstructor public class BybitSubscribeMessage { - private final String op; - private final List args; - } - + private final String op; + private final List args; +} diff --git a/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbook.java b/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbook.java index 7ba6df89560..1af9886b6bd 100644 --- a/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbook.java +++ b/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbook.java @@ -11,12 +11,11 @@ public class BybitOrderbook { private final String ts; private final BybitOrderbookData data; - @ConstructorProperties({"topic","type","ts","data"}) + @ConstructorProperties({"topic", "type", "ts", "data"}) public BybitOrderbook(String topic, String dataType, String ts, BybitOrderbookData data) { this.topic = topic; this.dataType = dataType; this.ts = ts; this.data = data; } - } diff --git a/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbookData.java b/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbookData.java index fc613a392ce..6c0fd66f917 100644 --- a/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbookData.java +++ b/xchange-stream-bybit/src/main/java/dto/marketdata/BybitOrderbookData.java @@ -20,7 +20,9 @@ public class BybitOrderbookData { private final Long seq; @ConstructorProperties({"s", "b", "a", "u", "seq"}) - public BybitOrderbookData(String symbolName, List bid, + public BybitOrderbookData( + String symbolName, + List bid, List ask, Integer u, Long seq) { diff --git a/xchange-stream-bybit/src/main/java/dto/marketdata/BybitPublicOrder.java b/xchange-stream-bybit/src/main/java/dto/marketdata/BybitPublicOrder.java index 55954ca82a1..72d508b9781 100644 --- a/xchange-stream-bybit/src/main/java/dto/marketdata/BybitPublicOrder.java +++ b/xchange-stream-bybit/src/main/java/dto/marketdata/BybitPublicOrder.java @@ -15,4 +15,3 @@ public BybitPublicOrder(String[] data) { this.size = data[1]; } } - diff --git a/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexOrderChanges.java b/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexOrderChanges.java index f25e891e695..909d96eb21e 100644 --- a/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexOrderChanges.java +++ b/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexOrderChanges.java @@ -7,7 +7,6 @@ import lombok.Getter; import lombok.Setter; import org.knowm.xchange.bybit.dto.BybitCategory; -import org.knowm.xchange.bybit.dto.trade.BybitOrderStatus; import org.knowm.xchange.bybit.dto.trade.BybitOrderType; import org.knowm.xchange.bybit.dto.trade.BybitSide; import org.knowm.xchange.dto.Order; @@ -28,22 +27,63 @@ public class BybitComplexOrderChanges extends Order { private boolean reduceOnly; private Date updatedTime; - public BybitComplexOrderChanges(OrderType type, BigDecimal originalAmount, - Instrument instrument, String id, Date timestamp, - BigDecimal averagePrice, BigDecimal cumulativeAmount, - BigDecimal fee, OrderStatus status, String userReference) { - super(type, originalAmount, instrument, id, timestamp, averagePrice, cumulativeAmount, fee, - status, userReference); + public BybitComplexOrderChanges( + OrderType type, + BigDecimal originalAmount, + Instrument instrument, + String id, + Date timestamp, + BigDecimal averagePrice, + BigDecimal cumulativeAmount, + BigDecimal fee, + OrderStatus status, + String userReference) { + super( + type, + originalAmount, + instrument, + id, + timestamp, + averagePrice, + cumulativeAmount, + fee, + status, + userReference); } - public BybitComplexOrderChanges(OrderType type, BigDecimal originalAmount, Instrument instrument, - String id, Date timestamp, BigDecimal averagePrice, BigDecimal cumulativeAmount, - BigDecimal fee, OrderStatus status, String userReference, BybitCategory category, - BigDecimal price, BybitSide side, BigDecimal leavesQty, BigDecimal leavesValue, - BigDecimal cumExecValue, String feeCurrency, TimeInForce timeInForce, - BybitOrderType orderType, boolean reduceOnly, Date updatedTime) { - super(type, originalAmount, instrument, id, timestamp, averagePrice, cumulativeAmount, fee, - status, userReference); + public BybitComplexOrderChanges( + OrderType type, + BigDecimal originalAmount, + Instrument instrument, + String id, + Date timestamp, + BigDecimal averagePrice, + BigDecimal cumulativeAmount, + BigDecimal fee, + OrderStatus status, + String userReference, + BybitCategory category, + BigDecimal price, + BybitSide side, + BigDecimal leavesQty, + BigDecimal leavesValue, + BigDecimal cumExecValue, + String feeCurrency, + TimeInForce timeInForce, + BybitOrderType orderType, + boolean reduceOnly, + Date updatedTime) { + super( + type, + originalAmount, + instrument, + id, + timestamp, + averagePrice, + cumulativeAmount, + fee, + status, + userReference); this.category = category; this.price = price; this.side = side; @@ -64,7 +104,6 @@ public enum TimeInForce { IOC("IOC"), FOK("FOK"), POSTONLY("PostOnly"); - @JsonValue - private final String value; + @JsonValue private final String value; } } diff --git a/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexPositionChanges.java b/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexPositionChanges.java index d89e5b1fd6d..2081300805f 100644 --- a/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexPositionChanges.java +++ b/xchange-stream-bybit/src/main/java/dto/trade/BybitComplexPositionChanges.java @@ -3,7 +3,6 @@ import java.math.BigDecimal; import lombok.Getter; import lombok.Setter; -import org.knowm.xchange.bybit.dto.BybitCategory; import org.knowm.xchange.dto.account.OpenPosition; import org.knowm.xchange.instrument.Instrument; @@ -13,16 +12,26 @@ public class BybitComplexPositionChanges extends OpenPosition { private BigDecimal positionValue; private BigDecimal leverage; private BigDecimal takeProfit; - private BigDecimal stopLoss; + private BigDecimal stopLoss; private BigDecimal curRealisedPnl; private long createdTime; private long updatedTime; private long seq; - public BybitComplexPositionChanges(Instrument instrument, Type type, BigDecimal size, - BigDecimal liquidationPrice, BigDecimal unRealisedPnl, - BigDecimal positionValue, BigDecimal entryPrice, BigDecimal leverage, BigDecimal takeProfit, - BigDecimal stopLoss, BigDecimal curRealisedPnl, long createdTime, long updatedTime, + public BybitComplexPositionChanges( + Instrument instrument, + Type type, + BigDecimal size, + BigDecimal liquidationPrice, + BigDecimal unRealisedPnl, + BigDecimal positionValue, + BigDecimal entryPrice, + BigDecimal leverage, + BigDecimal takeProfit, + BigDecimal stopLoss, + BigDecimal curRealisedPnl, + long createdTime, + long updatedTime, long seq) { super(instrument, type, size, entryPrice, liquidationPrice, unRealisedPnl); this.positionValue = positionValue; @@ -35,15 +44,24 @@ public BybitComplexPositionChanges(Instrument instrument, Type type, BigDecimal this.seq = seq; } - public BybitComplexPositionChanges(Instrument instrument, Type type, BigDecimal size, - BigDecimal price, BigDecimal liquidationPrice, + public BybitComplexPositionChanges( + Instrument instrument, + Type type, + BigDecimal size, + BigDecimal price, + BigDecimal liquidationPrice, BigDecimal unRealisedPnl) { super(instrument, type, size, price, liquidationPrice, unRealisedPnl); } public BybitComplexPositionChanges(BybitComplexPositionChanges changes) { - super(changes.getInstrument(), changes.getType(), changes.getSize(), changes.getPrice(), - changes.getLiquidationPrice(), changes.getUnRealisedPnl()); + super( + changes.getInstrument(), + changes.getType(), + changes.getSize(), + changes.getPrice(), + changes.getLiquidationPrice(), + changes.getUnRealisedPnl()); this.positionValue = changes.positionValue; this.leverage = changes.leverage; this.takeProfit = changes.takeProfit; @@ -53,5 +71,4 @@ public BybitComplexPositionChanges(BybitComplexPositionChanges changes) { this.updatedTime = changes.updatedTime; this.seq = changes.seq; } - } diff --git a/xchange-stream-bybit/src/main/java/dto/trade/BybitOrderChangesResponse.java b/xchange-stream-bybit/src/main/java/dto/trade/BybitOrderChangesResponse.java index b5967ff78c4..1981a60a9a7 100644 --- a/xchange-stream-bybit/src/main/java/dto/trade/BybitOrderChangesResponse.java +++ b/xchange-stream-bybit/src/main/java/dto/trade/BybitOrderChangesResponse.java @@ -67,4 +67,3 @@ public static class BybitOrderChanges { private String updatedTime; } } - diff --git a/xchange-stream-bybit/src/main/java/dto/trade/BybitPositionChangesResponse.java b/xchange-stream-bybit/src/main/java/dto/trade/BybitPositionChangesResponse.java index ac622edd7d6..437cb80149d 100644 --- a/xchange-stream-bybit/src/main/java/dto/trade/BybitPositionChangesResponse.java +++ b/xchange-stream-bybit/src/main/java/dto/trade/BybitPositionChangesResponse.java @@ -4,8 +4,6 @@ import java.util.List; import lombok.Getter; import org.knowm.xchange.bybit.dto.BybitCategory; -import org.knowm.xchange.bybit.dto.trade.BybitSide; - @Getter public class BybitPositionChangesResponse { @@ -59,8 +57,5 @@ public static class BybitPositionChanges { String createdTime; String updatedTime; long seq; - } } - - diff --git a/xchange-stream-bybit/src/main/java/dto/trade/BybitTrade.java b/xchange-stream-bybit/src/main/java/dto/trade/BybitTrade.java index a0ac503f2ef..99816e1aafd 100644 --- a/xchange-stream-bybit/src/main/java/dto/trade/BybitTrade.java +++ b/xchange-stream-bybit/src/main/java/dto/trade/BybitTrade.java @@ -9,26 +9,30 @@ @Getter public class BybitTrade { - //https://bybit-exchange.github.io/docs/v5/websocket/public/trad - //The timestamp (ms) that the order is filled + // https://bybit-exchange.github.io/docs/v5/websocket/public/trad + // The timestamp (ms) that the order is filled private final Date timestamp; - //Symbol name + // Symbol name private final String instId; - //Side of taker. Buy,Sell + // Side of taker. Buy,Sell private final BybitSide side; private final BigDecimal tradeSize; private final BigDecimal tradePrice; - //L string Direction of price change. Unique field for future + // L string Direction of price change. Unique field for future private final String direction; private final String tradeId; - //boolean Whether it is a block trade order or not + // boolean Whether it is a block trade order or not private final boolean bT; - - public BybitTrade(@JsonProperty("T") Date timestamp, @JsonProperty("s") String instId, - @JsonProperty("S") String side, @JsonProperty("v") BigDecimal tradeSize, - @JsonProperty("p") BigDecimal tradePrice, @JsonProperty("L") String direction, - @JsonProperty("i") String tradeId, @JsonProperty("BT") boolean bT) { + public BybitTrade( + @JsonProperty("T") Date timestamp, + @JsonProperty("s") String instId, + @JsonProperty("S") String side, + @JsonProperty("v") BigDecimal tradeSize, + @JsonProperty("p") BigDecimal tradePrice, + @JsonProperty("L") String direction, + @JsonProperty("i") String tradeId, + @JsonProperty("BT") boolean bT) { this.timestamp = timestamp; this.instId = instId; this.side = BybitSide.valueOf(side.toUpperCase()); @@ -39,4 +43,3 @@ public BybitTrade(@JsonProperty("T") Date timestamp, @JsonProperty("s") String i this.bT = bT; } } - diff --git a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamAdapters.java b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamAdapters.java index 7cfceb4749d..bd02f94de63 100644 --- a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamAdapters.java +++ b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamAdapters.java @@ -1,25 +1,21 @@ package info.bitrich.xchangestream.bybit; import static org.knowm.xchange.bybit.BybitAdapters.adaptBybitOrderStatus; - import static org.knowm.xchange.bybit.BybitAdapters.getOrderType; import static org.knowm.xchange.bybit.BybitAdapters.guessSymbol; +import dto.marketdata.BybitOrderbook; import dto.marketdata.BybitPublicOrder; import dto.trade.BybitComplexOrderChanges; import dto.trade.BybitComplexOrderChanges.TimeInForce; import dto.trade.BybitComplexPositionChanges; -import dto.trade.BybitOrderChangesResponse; import dto.trade.BybitOrderChangesResponse.BybitOrderChanges; import dto.trade.BybitPositionChangesResponse.BybitPositionChanges; import dto.trade.BybitTrade; import java.math.BigDecimal; -import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; -import dto.marketdata.BybitOrderbook; -import org.knowm.xchange.bybit.dto.trade.BybitSide; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.account.OpenPosition; @@ -39,13 +35,19 @@ public static OrderBook adaptOrderBook(BybitOrderbook bybitOrderbooks, Instrumen List asks = new ArrayList<>(); List bids = new ArrayList<>(); Date timestamp = new Date(Long.parseLong(bybitOrderbooks.getTs())); - bybitOrderbooks.getData().getAsk() - .forEach(bybitAsk -> asks.add( - adaptOrderBookOrder(bybitAsk, instrument, OrderType.ASK, timestamp))); - - bybitOrderbooks.getData().getBid() - .forEach(bybitBid -> bids.add( - adaptOrderBookOrder(bybitBid, instrument, OrderType.BID, timestamp))); + bybitOrderbooks + .getData() + .getAsk() + .forEach( + bybitAsk -> + asks.add(adaptOrderBookOrder(bybitAsk, instrument, OrderType.ASK, timestamp))); + + bybitOrderbooks + .getData() + .getBid() + .forEach( + bybitBid -> + bids.add(adaptOrderBookOrder(bybitBid, instrument, OrderType.BID, timestamp))); return new OrderBook(timestamp, asks, bids); } @@ -68,11 +70,19 @@ public static Trades adaptTrades(List bybitTrades, Instrument instru return new Trades(trades); } - public static LimitOrder adaptOrderBookOrder(BybitPublicOrder bybitPublicOrder, - Instrument instrument, OrderType orderType, Date timestamp) { - - return new LimitOrder(orderType, new BigDecimal(bybitPublicOrder.getSize()), instrument, "", - timestamp, new BigDecimal(bybitPublicOrder.getPrice())); + public static LimitOrder adaptOrderBookOrder( + BybitPublicOrder bybitPublicOrder, + Instrument instrument, + OrderType orderType, + Date timestamp) { + + return new LimitOrder( + orderType, + new BigDecimal(bybitPublicOrder.getSize()), + instrument, + "", + timestamp, + new BigDecimal(bybitPublicOrder.getPrice())); } public static List adaptOrdersChanges(List bybitOrderChanges) { @@ -84,9 +94,11 @@ public static List adaptOrdersChanges(List bybitOrderC Order.Builder builder = null; switch (bybitOrderChange.getOrderType()) { case LIMIT: - builder = new LimitOrder.Builder(orderType, guessSymbol(bybitOrderChange.getSymbol(), - bybitOrderChange.getCategory())).limitPrice( - new BigDecimal(bybitOrderChange.getPrice())); + builder = + new LimitOrder.Builder( + orderType, + guessSymbol(bybitOrderChange.getSymbol(), bybitOrderChange.getCategory())) + .limitPrice(new BigDecimal(bybitOrderChange.getPrice())); break; case MARKET: builder = new MarketOrder.Builder(orderType, guessSymbol(bybitOrderChange.getSymbol())); @@ -95,10 +107,13 @@ public static List adaptOrdersChanges(List bybitOrderC if (!bybitOrderChange.getAvgPrice().isEmpty()) { builder.averagePrice(new BigDecimal(bybitOrderChange.getAvgPrice())); } - builder.fee(new BigDecimal(bybitOrderChange.getCumExecFee())). - leverage(bybitOrderChange.getIsLeverage()).id(bybitOrderChange.getOrderId()) + builder + .fee(new BigDecimal(bybitOrderChange.getCumExecFee())) + .leverage(bybitOrderChange.getIsLeverage()) + .id(bybitOrderChange.getOrderId()) .orderStatus(adaptBybitOrderStatus(bybitOrderChange.getOrderStatus())) - .timestamp(date).cumulativeAmount(new BigDecimal(bybitOrderChange.getCumExecQty())) + .timestamp(date) + .cumulativeAmount(new BigDecimal(bybitOrderChange.getCumExecQty())) .originalAmount(new BigDecimal(bybitOrderChange.getQty())) .id(bybitOrderChange.getOrderId()) .userReference(bybitOrderChange.getOrderLinkId()); @@ -119,10 +134,14 @@ public static OpenPositions adaptPositionChanges( if (!position.getLiqPrice().isEmpty()) { liqPrice = new BigDecimal(position.getLiqPrice()); } - OpenPosition openPosition = new OpenPosition(guessSymbol(position.getSymbol(), - position.getCategory()), type, new BigDecimal(position.getSize()), - new BigDecimal(position.getEntryPrice()), liqPrice, - new BigDecimal(position.getUnrealisedPnl())); + OpenPosition openPosition = + new OpenPosition( + guessSymbol(position.getSymbol(), position.getCategory()), + type, + new BigDecimal(position.getSize()), + new BigDecimal(position.getEntryPrice()), + liqPrice, + new BigDecimal(position.getUnrealisedPnl())); openPositions.getOpenPositions().add(openPosition); } return openPositions; @@ -140,16 +159,22 @@ public static List adaptComplexPositionChanges( if (!position.getLiqPrice().isEmpty()) { liqPrice = new BigDecimal(position.getLiqPrice()); } - BybitComplexPositionChanges positionChanges = new BybitComplexPositionChanges( - guessSymbol(position.getSymbol(), - position.getCategory()), type, new BigDecimal(position.getSize()), liqPrice, - new BigDecimal(position.getUnrealisedPnl()), - new BigDecimal(position.getPositionValue()), new BigDecimal(position.getEntryPrice()), - new BigDecimal(position.getLeverage()), - new BigDecimal(position.getTakeProfit()), new BigDecimal(position.getStopLoss()), - new BigDecimal(position.getCurRealisedPnl()), - Long.parseLong(position.getCreatedTime()), Long.parseLong(position.getUpdatedTime()), - position.getSeq()); + BybitComplexPositionChanges positionChanges = + new BybitComplexPositionChanges( + guessSymbol(position.getSymbol(), position.getCategory()), + type, + new BigDecimal(position.getSize()), + liqPrice, + new BigDecimal(position.getUnrealisedPnl()), + new BigDecimal(position.getPositionValue()), + new BigDecimal(position.getEntryPrice()), + new BigDecimal(position.getLeverage()), + new BigDecimal(position.getTakeProfit()), + new BigDecimal(position.getStopLoss()), + new BigDecimal(position.getCurRealisedPnl()), + Long.parseLong(position.getCreatedTime()), + Long.parseLong(position.getUpdatedTime()), + position.getSeq()); result.add(positionChanges); } return result; @@ -160,20 +185,33 @@ public static List adaptComplexOrdersChanges( List result = new ArrayList<>(); for (BybitOrderChanges change : data) { Order.OrderType orderType = getOrderType(change.getSide()); - BigDecimal avgPrice = change.getAvgPrice().isEmpty() ? null : new BigDecimal(change.getAvgPrice()); - BybitComplexOrderChanges orderChanges = new BybitComplexOrderChanges(orderType, - new BigDecimal(change.getQty()), guessSymbol(change.getSymbol(),change.getCategory()), change.getOrderId(), - new Date(Long.parseLong(change.getCreatedTime())), avgPrice, - new BigDecimal(change.getCumExecQty()), new BigDecimal(change.getCumExecFee()), - adaptBybitOrderStatus(change.getOrderStatus()), change.getOrderLinkId(), - change.getCategory(), new BigDecimal(change.getPrice()), change.getSide(), - new BigDecimal(change.getLeavesQty()), new BigDecimal(change.getLeavesValue()), - new BigDecimal(change.getCumExecValue()), change.getFeeCurrency(), - TimeInForce.valueOf(change.getTimeInForce().toUpperCase()), change.getOrderType(), - change.isReduceOnly(), new Date(Long.parseLong(change.getUpdatedTime()))); + BigDecimal avgPrice = + change.getAvgPrice().isEmpty() ? null : new BigDecimal(change.getAvgPrice()); + BybitComplexOrderChanges orderChanges = + new BybitComplexOrderChanges( + orderType, + new BigDecimal(change.getQty()), + guessSymbol(change.getSymbol(), change.getCategory()), + change.getOrderId(), + new Date(Long.parseLong(change.getCreatedTime())), + avgPrice, + new BigDecimal(change.getCumExecQty()), + new BigDecimal(change.getCumExecFee()), + adaptBybitOrderStatus(change.getOrderStatus()), + change.getOrderLinkId(), + change.getCategory(), + new BigDecimal(change.getPrice()), + change.getSide(), + new BigDecimal(change.getLeavesQty()), + new BigDecimal(change.getLeavesValue()), + new BigDecimal(change.getCumExecValue()), + change.getFeeCurrency(), + TimeInForce.valueOf(change.getTimeInForce().toUpperCase()), + change.getOrderType(), + change.isReduceOnly(), + new Date(Long.parseLong(change.getUpdatedTime()))); result.add(orderChanges); } return result; } - } diff --git a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingExchange.java b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingExchange.java index ec80a62a578..15bd1e2a469 100644 --- a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingExchange.java +++ b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingExchange.java @@ -12,7 +12,7 @@ public class BybitStreamingExchange extends BybitExchange implements StreamingEx private final Logger LOG = LoggerFactory.getLogger(BybitStreamingExchange.class); - //https://bybit-exchange.github.io/docs/v5/ws/connect + // https://bybit-exchange.github.io/docs/v5/ws/connect public static final String URI = "wss://stream.bybit.com/v5/public"; public static final String TESTNET_URI = "wss://stream-testnet.bybit.com/v5/public"; // DEMO_URI websocket not worked(401 error) @@ -22,7 +22,7 @@ public class BybitStreamingExchange extends BybitExchange implements StreamingEx public static final String TESTNET_AUTH_URI = "wss://stream-testnet.bybit.com/v5/private"; public static final String DEMO_AUTH_URI = "wss://stream-demo.bybit.com/v5/private"; - //spot, linear, inverse or option + // spot, linear, inverse or option public static final String EXCHANGE_TYPE = "Exchange_Type"; private BybitStreamingService streamingService; @@ -46,7 +46,11 @@ private String getApiUrl() { } else { apiUrl = URI; } - apiUrl += "/" + ((BybitCategory)exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE)).getValue(); + apiUrl += + "/" + + ((BybitCategory) + exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE)) + .getValue(); } else { if (Boolean.TRUE.equals( exchangeSpecification.getExchangeSpecificParametersItem(USE_SANDBOX))) { @@ -89,5 +93,4 @@ public BybitStreamingMarketDataService getStreamingMarketDataService() { public BybitStreamingTradeService getStreamingTradeService() { return streamingTradeService; } - } diff --git a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingMarketDataService.java b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingMarketDataService.java index d50effc2def..21ad1dd6d59 100644 --- a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingMarketDataService.java +++ b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingMarketDataService.java @@ -3,7 +3,9 @@ import static org.knowm.xchange.bybit.BybitAdapters.convertToBybitSymbol; import com.fasterxml.jackson.databind.ObjectMapper; +import dto.marketdata.BybitOrderbook; import dto.marketdata.BybitPublicOrder; +import dto.trade.BybitTrade; import info.bitrich.xchangestream.core.StreamingMarketDataService; import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper; import io.reactivex.rxjava3.core.Observable; @@ -16,8 +18,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import dto.marketdata.BybitOrderbook; -import dto.trade.BybitTrade; import java.util.concurrent.atomic.AtomicLong; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.marketdata.OrderBook; @@ -51,7 +51,7 @@ public BybitStreamingMarketDataService(BybitStreamingService streamingService) { * frequency: 10ms Level 50 data, push frequency: 20ms Level 200 data, push frequency: 200ms * * @param args - orderbook depth - **/ + */ @Override public Observable getOrderBook(Instrument instrument, Object... args) { String depth = "50"; @@ -59,36 +59,41 @@ public Observable getOrderBook(Instrument instrument, Object... args) if (args.length > 0 && args[0] != null) { depth = args[0].toString(); } - String channelUniqueId = - ORDERBOOK + depth + "." + convertToBybitSymbol(instrument); + String channelUniqueId = ORDERBOOK + depth + "." + convertToBybitSymbol(instrument); return streamingService .subscribeChannel(channelUniqueId) .flatMap( jsonNode -> { - BybitOrderbook bybitOrderbooks = - mapper.treeToValue(jsonNode, BybitOrderbook.class); + BybitOrderbook bybitOrderbooks = mapper.treeToValue(jsonNode, BybitOrderbook.class); String type = bybitOrderbooks.getDataType(); if (type.equalsIgnoreCase("snapshot")) { - OrderBook orderBook = BybitStreamAdapters.adaptOrderBook(bybitOrderbooks, instrument); + OrderBook orderBook = + BybitStreamAdapters.adaptOrderBook(bybitOrderbooks, instrument); orderBookUpdateIdPrev.set(bybitOrderbooks.getData().getU()); orderBookMap.put(channelUniqueId, orderBook); return Observable.just(orderBook); } else if (type.equalsIgnoreCase("delta")) { - return applyDeltaSnapshot(channelUniqueId, instrument, bybitOrderbooks, orderBookUpdateIdPrev); + return applyDeltaSnapshot( + channelUniqueId, instrument, bybitOrderbooks, orderBookUpdateIdPrev); } return Observable.fromIterable(new LinkedList<>()); }); } - private Observable applyDeltaSnapshot(String channelUniqueId, Instrument instrument, - BybitOrderbook bybitOrderBookUpdate,AtomicLong orderBookUpdateIdPrev) { + private Observable applyDeltaSnapshot( + String channelUniqueId, + Instrument instrument, + BybitOrderbook bybitOrderBookUpdate, + AtomicLong orderBookUpdateIdPrev) { OrderBook orderBook = orderBookMap.getOrDefault(channelUniqueId, null); if (orderBook == null) { LOG.error("Failed to get orderBook, channelUniqueId= {}", channelUniqueId); return Observable.fromIterable(new LinkedList<>()); } if (orderBookUpdateIdPrev.incrementAndGet() == bybitOrderBookUpdate.getData().getU()) { - LOG.debug("orderBookUpdate id {}, seq {} ", bybitOrderBookUpdate.getData().getU(), + LOG.debug( + "orderBookUpdate id {}, seq {} ", + bybitOrderBookUpdate.getData().getU(), bybitOrderBookUpdate.getData().getSeq()); List asks = bybitOrderBookUpdate.getData().getAsk(); List bids = bybitOrderBookUpdate.getData().getBid(); @@ -108,7 +113,8 @@ private Observable applyDeltaSnapshot(String channelUniqueId, Instrum } return Observable.just(orderBook); } else { - LOG.error("orderBookUpdate id sequence failed, expected {}, in fact {}", + LOG.error( + "orderBookUpdate id sequence failed, expected {}, in fact {}", orderBookUpdateIdPrev, bybitOrderBookUpdate.getData().getU()); // resubscribe or what here? @@ -117,7 +123,8 @@ private Observable applyDeltaSnapshot(String channelUniqueId, Instrum } @Override - public Observable> getOrderBookUpdates(Instrument instrument,Object... args) { + public Observable> getOrderBookUpdates( + Instrument instrument, Object... args) { return orderBookUpdatesSubscriptions.computeIfAbsent(instrument, v -> PublishSubject.create()); } @@ -151,8 +158,7 @@ private void orderBookUpdatesSubscriptions( @Override public Observable getTrades(Instrument instrument, Object... args) { - String channelUniqueId = - TRADE + convertToBybitSymbol(instrument); + String channelUniqueId = TRADE + convertToBybitSymbol(instrument); return streamingService .subscribeChannel(channelUniqueId) @@ -162,7 +168,8 @@ public Observable getTrades(Instrument instrument, Object... args) { List bybitTradeList = mapper.treeToValue( jsonNode.get("data"), - mapper.getTypeFactory() + mapper + .getTypeFactory() .constructCollectionType(List.class, BybitTrade.class)); return Observable.fromIterable( BybitStreamAdapters.adaptTrades(bybitTradeList, instrument).getTrades()); diff --git a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingService.java b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingService.java index 10386ca320f..be7ece0918d 100644 --- a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingService.java +++ b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingService.java @@ -18,12 +18,8 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.Instant; -import java.util.ArrayList; -import java.util.Base64; import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -31,7 +27,6 @@ import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import lombok.Getter; -import lombok.var; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.bybit.dto.BybitCategory; import org.knowm.xchange.exceptions.ExchangeException; @@ -46,14 +41,14 @@ public class BybitStreamingService extends JsonNettyStreamingService { private final Observable pingPongSrc = Observable.interval(15, 20, TimeUnit.SECONDS); private Disposable pingPongSubscription; private final ExchangeSpecification spec; - @Getter - private boolean isAuthorized = false; + @Getter private boolean isAuthorized = false; public BybitStreamingService(String apiUrl, ExchangeSpecification spec) { super(apiUrl); - this.exchange_type = ((BybitCategory)spec.getExchangeSpecificParametersItem(EXCHANGE_TYPE)).getValue(); + this.exchange_type = + ((BybitCategory) spec.getExchangeSpecificParametersItem(EXCHANGE_TYPE)).getValue(); this.spec = spec; -// this.setEnableLoggingHandler(true); + // this.setEnableLoggingHandler(true); } @Override @@ -66,8 +61,8 @@ public Completable connect() { login(); } pingPongDisconnectIfConnected(); - pingPongSubscription = pingPongSrc.subscribe( - o -> this.sendMessage("{\"op\":\"ping\"}")); + pingPongSubscription = + pingPongSrc.subscribe(o -> this.sendMessage("{\"op\":\"ping\"}")); completable.onComplete(); }); } @@ -83,8 +78,8 @@ private void login() { spec.getSecretKey().getBytes(StandardCharsets.UTF_8), BaseParamsDigest.HMAC_SHA_256); mac.init(secretKey); String signature = bytesToHex(mac.doFinal(_val.getBytes(StandardCharsets.UTF_8))); - List args = Stream.of(key, String.valueOf(expires), signature) - .collect(Collectors.toList()); + List args = + Stream.of(key, String.valueOf(expires), signature).collect(Collectors.toList()); String message = objectMapper.writeValueAsString(new BybitSubscribeMessage("auth", args)); this.sendMessage(message); } catch (NoSuchAlgorithmException | InvalidKeyException e) { @@ -138,13 +133,15 @@ public void messageHandler(String message) { switch (op) { case "pong": case "subscribe": - case "unsubscribe": { - break; - } - case "auth": { - isAuthorized = true; - break; - } + case "unsubscribe": + { + break; + } + case "auth": + { + isAuthorized = true; + break; + } } return; } diff --git a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingTradeService.java b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingTradeService.java index 0f60502f135..8209a5c8267 100644 --- a/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingTradeService.java +++ b/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingTradeService.java @@ -23,60 +23,68 @@ public BybitStreamingTradeService(BybitStreamingService streamingService) { public Observable getOrderChanges(BybitCategory category) { String channelUniqueId = "order"; - if(category != null) { + if (category != null) { channelUniqueId += "." + category.getValue(); } return streamingService - .subscribeChannel(channelUniqueId).flatMap( - node -> { - BybitOrderChangesResponse bybitOrderChangesResponse = mapper.treeToValue(node, BybitOrderChangesResponse.class); - return Observable.fromIterable( - BybitStreamAdapters.adaptOrdersChanges(bybitOrderChangesResponse.getData())); - }); + .subscribeChannel(channelUniqueId) + .flatMap( + node -> { + BybitOrderChangesResponse bybitOrderChangesResponse = + mapper.treeToValue(node, BybitOrderChangesResponse.class); + return Observable.fromIterable( + BybitStreamAdapters.adaptOrdersChanges(bybitOrderChangesResponse.getData())); + }); } public Observable getComplexOrderChanges(BybitCategory category) { String channelUniqueId = "order"; - if(category != null) { + if (category != null) { channelUniqueId += "." + category.getValue(); } return streamingService - .subscribeChannel(channelUniqueId).flatMap( + .subscribeChannel(channelUniqueId) + .flatMap( node -> { - BybitOrderChangesResponse bybitOrderChangesResponse = mapper.treeToValue(node, BybitOrderChangesResponse.class); + BybitOrderChangesResponse bybitOrderChangesResponse = + mapper.treeToValue(node, BybitOrderChangesResponse.class); return Observable.fromIterable( - BybitStreamAdapters.adaptComplexOrdersChanges(bybitOrderChangesResponse.getData())); + BybitStreamAdapters.adaptComplexOrdersChanges( + bybitOrderChangesResponse.getData())); }); } public Observable getPositionChanges(BybitCategory category) { String channelUniqueId = "position"; - if(category != null) { + if (category != null) { channelUniqueId += "." + category.getValue(); } return streamingService - .subscribeChannel(channelUniqueId).flatMap( + .subscribeChannel(channelUniqueId) + .flatMap( node -> { - BybitPositionChangesResponse bybitPositionChangesResponse = mapper.treeToValue(node, - BybitPositionChangesResponse.class); + BybitPositionChangesResponse bybitPositionChangesResponse = + mapper.treeToValue(node, BybitPositionChangesResponse.class); return Observable.fromIterable( - BybitStreamAdapters.adaptPositionChanges(bybitPositionChangesResponse.getData()). - getOpenPositions()); + BybitStreamAdapters.adaptPositionChanges(bybitPositionChangesResponse.getData()) + .getOpenPositions()); }); } public Observable getBybitPositionChanges(BybitCategory category) { String channelUniqueId = "position"; - if(category != null) { + if (category != null) { channelUniqueId += "." + category.getValue(); } return streamingService - .subscribeChannel(channelUniqueId).flatMap( + .subscribeChannel(channelUniqueId) + .flatMap( node -> { - BybitPositionChangesResponse bybitPositionChangesResponse = mapper.treeToValue(node, - BybitPositionChangesResponse.class); + BybitPositionChangesResponse bybitPositionChangesResponse = + mapper.treeToValue(node, BybitPositionChangesResponse.class); return Observable.fromIterable( - BybitStreamAdapters.adaptComplexPositionChanges(bybitPositionChangesResponse.getData())); + BybitStreamAdapters.adaptComplexPositionChanges( + bybitPositionChangesResponse.getData())); }); } } diff --git a/xchange-stream-bybit/src/test/java/info/bitrich/xchangestream/bybit/BybitStreamExample.java b/xchange-stream-bybit/src/test/java/info/bitrich/xchangestream/bybit/BybitStreamExample.java index 8db32a34d12..a6cea09d71d 100644 --- a/xchange-stream-bybit/src/test/java/info/bitrich/xchangestream/bybit/BybitStreamExample.java +++ b/xchange-stream-bybit/src/test/java/info/bitrich/xchangestream/bybit/BybitStreamExample.java @@ -27,18 +27,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class BybitStreamExample { private static final Logger log = LoggerFactory.getLogger(BybitStreamExample.class); public static void main(String[] args) { try { -// spot(); + // spot(); auth(); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } -// futures(); + // futures(); } @@ -48,74 +47,84 @@ public static void main(String[] args) { private static final Instrument BTC_SPOT = new CurrencyPair("BTC/USDT"); private static final Instrument ETH_SPOT = new CurrencyPair("ETH/USDT"); - private static void auth() throws IOException, InterruptedException { ExchangeSpecification exchangeSpecification = new BybitStreamingExchange().getDefaultExchangeSpecification(); exchangeSpecification.setApiKey(System.getProperty("test_api_key")); exchangeSpecification.setSecretKey(System.getProperty("test_secret_key")); - exchangeSpecification.setExchangeSpecificParametersItem(SPECIFIC_PARAM_ACCOUNT_TYPE, - BybitAccountType.UNIFIED); - exchangeSpecification.setExchangeSpecificParametersItem(BybitStreamingExchange.EXCHANGE_TYPE, - BybitCategory.LINEAR); + exchangeSpecification.setExchangeSpecificParametersItem( + SPECIFIC_PARAM_ACCOUNT_TYPE, BybitAccountType.UNIFIED); + exchangeSpecification.setExchangeSpecificParametersItem( + BybitStreamingExchange.EXCHANGE_TYPE, BybitCategory.LINEAR); exchangeSpecification.setExchangeSpecificParametersItem(USE_SANDBOX, true); - StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange( - exchangeSpecification); + StreamingExchange exchange = + StreamingExchangeFactory.INSTANCE.createExchange(exchangeSpecification); exchange.connect().blockingAwait(); Ticker ticker = (exchange.getMarketDataService().getTicker(DOGE_PERP)); - BigDecimal amount = exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getMinimumAmount(); - if(amount.multiply(ticker.getLast()).compareTo(new BigDecimal("5.0")) <= 0) { - amount = new BigDecimal("5").divide(ticker.getAsk(), exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getVolumeScale(), UP); + BigDecimal amount = + exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getMinimumAmount(); + if (amount.multiply(ticker.getLast()).compareTo(new BigDecimal("5.0")) <= 0) { + amount = + new BigDecimal("5") + .divide( + ticker.getAsk(), + exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getVolumeScale(), + UP); } - LimitOrder limitOrder = new LimitOrder(OrderType.BID,amount, DOGE_PERP, "", new Date(), ticker.getAsk()); + LimitOrder limitOrder = + new LimitOrder(OrderType.BID, amount, DOGE_PERP, "", new Date(), ticker.getAsk()); Thread.sleep(2000L); AtomicReference order = new AtomicReference<>(); - Disposable disposableOrderChanges = ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getOrderChanges(BybitCategory.LINEAR) - .doOnError( - error -> log.error("OrderChanges error {}",error.getMessage())) - .subscribe( c -> { - log.info("Order Changes {}", c); - order.set(c); - }, - throwable -> log.error("OrderChanges throwable,{}",throwable.getMessage())); -// Disposable disposablePositionChanges = ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getPositionChanges(BybitCategory.LINEAR) -// .doOnError( -// error -> log.error("PositionChanges error {}",error.getMessage())) -// .subscribe( p -> log.info("PositionChanges Changes {}", p), -// throwable -> log.error("Position throwable,{}",throwable.getMessage())); - - Disposable disposableComplexPositionChanges = ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getBybitPositionChanges(BybitCategory.LINEAR) - .doOnError( - error -> log.error("ComplexPositionChanges error {}",error.getMessage())) - .subscribe( p -> log.info("ComplexPositionChanges Changes {}", p), - throwable -> log.error("ComplexPosition throwable,{}",throwable.getMessage())); + Disposable disposableOrderChanges = + ((BybitStreamingTradeService) exchange.getStreamingTradeService()) + .getOrderChanges(BybitCategory.LINEAR) + .doOnError(error -> log.error("OrderChanges error {}", error.getMessage())) + .subscribe( + c -> { + log.info("Order Changes {}", c); + order.set(c); + }, + throwable -> log.error("OrderChanges throwable,{}", throwable.getMessage())); + // Disposable disposablePositionChanges = + // ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getPositionChanges(BybitCategory.LINEAR) + // .doOnError( + // error -> log.error("PositionChanges error {}",error.getMessage())) + // .subscribe( p -> log.info("PositionChanges Changes {}", p), + // throwable -> log.error("Position throwable,{}",throwable.getMessage())); + + Disposable disposableComplexPositionChanges = + ((BybitStreamingTradeService) exchange.getStreamingTradeService()) + .getBybitPositionChanges(BybitCategory.LINEAR) + .doOnError(error -> log.error("ComplexPositionChanges error {}", error.getMessage())) + .subscribe( + p -> log.info("ComplexPositionChanges Changes {}", p), + throwable -> log.error("ComplexPosition throwable,{}", throwable.getMessage())); Thread.sleep(3000L); exchange.getTradeService().placeLimitOrder(limitOrder); Thread.sleep(30000L); disposableOrderChanges.dispose(); -// disposablePositionChanges.dispose(); + // disposablePositionChanges.dispose(); disposableComplexPositionChanges.dispose(); exchange.disconnect().blockingAwait(); - } + } public static void spot() throws IOException { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(BybitStreamingExchange.class); exchangeSpecification.setExchangeSpecificParametersItem(USE_SANDBOX, true); - exchangeSpecification.setExchangeSpecificParametersItem(BybitStreamingExchange.EXCHANGE_TYPE, - BybitCategory.SPOT); - exchangeSpecification.setExchangeSpecificParametersItem(SPECIFIC_PARAM_ACCOUNT_TYPE, - BybitAccountType.UNIFIED); - StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange( - exchangeSpecification); + exchangeSpecification.setExchangeSpecificParametersItem( + BybitStreamingExchange.EXCHANGE_TYPE, BybitCategory.SPOT); + exchangeSpecification.setExchangeSpecificParametersItem( + SPECIFIC_PARAM_ACCOUNT_TYPE, BybitAccountType.UNIFIED); + StreamingExchange exchange = + StreamingExchangeFactory.INSTANCE.createExchange(exchangeSpecification); exchange.connect().blockingAwait(); int count_currencyPair = 0; int count_futureContractPerp = 0; int count_futureContractDate = 0; - List instruments = new ArrayList<>(exchange - .getExchangeMetaData() - .getInstruments().keySet()); + List instruments = + new ArrayList<>(exchange.getExchangeMetaData().getInstruments().keySet()); for (Instrument instrument : instruments) { if (instrument instanceof CurrencyPair) { count_currencyPair++; @@ -135,20 +144,20 @@ public static void spot() throws IOException { System.out.println(exchange.getMarketDataService().getTicker(BTC_PERP)); List tradesDisposable = new ArrayList<>(); Disposable bookDisposable = + exchange.getStreamingMarketDataService().getOrderBook(ETH_SPOT).subscribe(); + tradesDisposable.add( exchange .getStreamingMarketDataService() - .getOrderBook(ETH_SPOT) - .subscribe(); - tradesDisposable.add(exchange - .getStreamingMarketDataService().getTrades(ETH_SPOT).subscribe( - trade -> System.out.println("trade: " + trade))); - tradesDisposable.add(exchange - .getStreamingMarketDataService().getTrades(BTC_SPOT).subscribe( - trade -> System.out.println("trade: " + trade))); + .getTrades(ETH_SPOT) + .subscribe(trade -> System.out.println("trade: " + trade))); + tradesDisposable.add( + exchange + .getStreamingMarketDataService() + .getTrades(BTC_SPOT) + .subscribe(trade -> System.out.println("trade: " + trade))); try { Thread.sleep(2000); - } catch ( - InterruptedException ignored) { + } catch (InterruptedException ignored) { } bookDisposable.dispose(); for (Disposable disposable : tradesDisposable) { @@ -157,53 +166,51 @@ public static void spot() throws IOException { try { Thread.sleep(5000); - } catch ( - InterruptedException ignored) { + } catch (InterruptedException ignored) { } exchange.disconnect().blockingAwait(); } - public static void futures() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(BybitStreamingExchange.class); - exchangeSpecification.setExchangeSpecificParametersItem(SPECIFIC_PARAM_ACCOUNT_TYPE, - BybitAccountType.UNIFIED); - exchangeSpecification.setExchangeSpecificParametersItem(BybitStreamingExchange.EXCHANGE_TYPE, - BybitCategory.LINEAR); + exchangeSpecification.setExchangeSpecificParametersItem( + SPECIFIC_PARAM_ACCOUNT_TYPE, BybitAccountType.UNIFIED); + exchangeSpecification.setExchangeSpecificParametersItem( + BybitStreamingExchange.EXCHANGE_TYPE, BybitCategory.LINEAR); exchangeSpecification.setExchangeSpecificParametersItem(USE_SANDBOX, true); - StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange( - exchangeSpecification); + StreamingExchange exchange = + StreamingExchangeFactory.INSTANCE.createExchange(exchangeSpecification); exchange.connect().blockingAwait(); List tradesDisposable = new ArrayList<>(); List booksDisposable = new ArrayList<>(); List booksUpdatesDisposable = new ArrayList<>(); - booksDisposable.add(exchange - .getStreamingMarketDataService() - .getOrderBook(BTC_PERP) - .subscribe()); - booksDisposable.add(exchange - .getStreamingMarketDataService() - .getOrderBook(ETH_PERP) - .subscribe()); - booksUpdatesDisposable.add(exchange - .getStreamingMarketDataService() - .getOrderBookUpdates(BTC_PERP) - .subscribe( - orderBookUpdates -> System.out.printf("orderBookUpdates: %s\n", orderBookUpdates) - )); - booksUpdatesDisposable.add(exchange - .getStreamingMarketDataService() - .getOrderBookUpdates(ETH_PERP) - .subscribe( - orderBookUpdates -> System.out.printf("orderBookUpdates: %s\n", orderBookUpdates) - )); - tradesDisposable.add(exchange - .getStreamingMarketDataService().getTrades(BTC_PERP).subscribe( - trade -> System.out.println("trade: " + trade))); - tradesDisposable.add(exchange - .getStreamingMarketDataService().getTrades(ETH_PERP).subscribe( - trade -> System.out.println("trade: " + trade))); + booksDisposable.add( + exchange.getStreamingMarketDataService().getOrderBook(BTC_PERP).subscribe()); + booksDisposable.add( + exchange.getStreamingMarketDataService().getOrderBook(ETH_PERP).subscribe()); + booksUpdatesDisposable.add( + exchange + .getStreamingMarketDataService() + .getOrderBookUpdates(BTC_PERP) + .subscribe( + orderBookUpdates -> System.out.printf("orderBookUpdates: %s\n", orderBookUpdates))); + booksUpdatesDisposable.add( + exchange + .getStreamingMarketDataService() + .getOrderBookUpdates(ETH_PERP) + .subscribe( + orderBookUpdates -> System.out.printf("orderBookUpdates: %s\n", orderBookUpdates))); + tradesDisposable.add( + exchange + .getStreamingMarketDataService() + .getTrades(BTC_PERP) + .subscribe(trade -> System.out.println("trade: " + trade))); + tradesDisposable.add( + exchange + .getStreamingMarketDataService() + .getTrades(ETH_PERP) + .subscribe(trade -> System.out.println("trade: " + trade))); try { Thread.sleep(2000); } catch (InterruptedException ignored) { @@ -225,5 +232,4 @@ public static void futures() { } exchange.disconnect().blockingAwait(); } - } diff --git a/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/CexioStreamingMarketDataService.java b/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/CexioStreamingMarketDataService.java index 3814522897f..a3c66730a54 100644 --- a/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/CexioStreamingMarketDataService.java +++ b/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/CexioStreamingMarketDataService.java @@ -112,5 +112,4 @@ public Observable getTicker(CurrencyPair currencyPair, Object... args) { prev.getBid().compareTo(next.getBid()) == 0 && prev.getAsk().compareTo(next.getAsk()) == 0); } - } diff --git a/xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/CoinjarStreamingMarketDataService.java b/xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/CoinjarStreamingMarketDataService.java index 7f8da0e1fe7..39cfdb54b56 100644 --- a/xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/CoinjarStreamingMarketDataService.java +++ b/xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/CoinjarStreamingMarketDataService.java @@ -86,5 +86,4 @@ public Observable getOrderBook(CurrencyPair currencyPair, Object... a }) .filter(orderbook -> !orderbook.getBids().isEmpty() && !orderbook.getAsks().isEmpty()); } - } diff --git a/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarOrderChangesExample.java b/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarOrderChangesExample.java index 43712e1c85e..81c8d644da9 100644 --- a/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarOrderChangesExample.java +++ b/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarOrderChangesExample.java @@ -4,7 +4,6 @@ import info.bitrich.xchangestream.core.StreamingExchangeFactory; import info.bitrich.xchangestream.core.StreamingTradeService; import io.reactivex.rxjava3.disposables.Disposable; -import io.reactivex.rxjava3.observers.BaseTestConsumer; import org.junit.Test; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.utils.AuthUtils; @@ -25,11 +24,7 @@ public void runTest() { StreamingTradeService streamingTradeService = exchange.getStreamingTradeService(); Disposable disposable = - streamingTradeService - .getOrderChanges(null) - .test() - .awaitCount(10) - .assertNoErrors(); + streamingTradeService.getOrderChanges(null).test().awaitCount(10).assertNoErrors(); disposable.dispose(); } } diff --git a/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarUserTradesExample.java b/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarUserTradesExample.java index a69d438f432..f206c9a9857 100644 --- a/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarUserTradesExample.java +++ b/xchange-stream-coinjar/src/test/java/info/bitrich/xchangestream/coinjar/CoinjarUserTradesExample.java @@ -4,7 +4,6 @@ import info.bitrich.xchangestream.core.StreamingExchangeFactory; import info.bitrich.xchangestream.core.StreamingTradeService; import io.reactivex.rxjava3.disposables.Disposable; -import io.reactivex.rxjava3.observers.BaseTestConsumer; import org.junit.Test; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.utils.AuthUtils; @@ -25,11 +24,7 @@ public void runTest() { StreamingTradeService streamingTradeService = exchange.getStreamingTradeService(); Disposable disposable = - streamingTradeService - .getUserTrades(null) - .test() - .awaitCount(1) - .assertNoErrors(); + streamingTradeService.getUserTrades(null).test().awaitCount(1).assertNoErrors(); disposable.dispose(); } } diff --git a/xchange-stream-core/src/main/java/info/bitrich/xchangestream/core/StreamingMarketDataService.java b/xchange-stream-core/src/main/java/info/bitrich/xchangestream/core/StreamingMarketDataService.java index 8a9036ae1ef..ef60c99c58f 100644 --- a/xchange-stream-core/src/main/java/info/bitrich/xchangestream/core/StreamingMarketDataService.java +++ b/xchange-stream-core/src/main/java/info/bitrich/xchangestream/core/StreamingMarketDataService.java @@ -95,14 +95,14 @@ default Observable getFundingRates() { } /** - * Get snapshots of orderBook update separately. - * Work only with {@link #getOrderBook(Instrument, Object...)} subscription. + * Get snapshots of orderBook update separately. Work only with {@link #getOrderBook(Instrument, + * Object...)} subscription. * * @return {@link Observable} that emits {@link OrderBookUpdate} when exchange sends the orderBook - * snapshot. + * snapshot. */ - default Observable> getOrderBookUpdates(Instrument instrument, - Object... args) { + default Observable> getOrderBookUpdates( + Instrument instrument, Object... args) { throw new NotYetImplementedForExchangeException("getOrderBookUpdates"); } } diff --git a/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v1/dydxStreamingMarketDataService.java b/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v1/dydxStreamingMarketDataService.java index eabe54b0856..1ffb474eb64 100644 --- a/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v1/dydxStreamingMarketDataService.java +++ b/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v1/dydxStreamingMarketDataService.java @@ -85,5 +85,4 @@ public Observable getOrderBook(CurrencyPair currencyPair, Object... a } }); } - } diff --git a/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v3/dydxStreamingMarketDataService.java b/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v3/dydxStreamingMarketDataService.java index 5d10c50e2c4..9ed261dc8d4 100644 --- a/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v3/dydxStreamingMarketDataService.java +++ b/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/service/v3/dydxStreamingMarketDataService.java @@ -71,5 +71,4 @@ public Observable getOrderBook(CurrencyPair currencyPair, Object... a } }); } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountService.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountService.java index e18508cf0f9..13ed808f885 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountService.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountService.java @@ -15,13 +15,14 @@ public GateioStreamingAccountService(GateioStreamingService service) { this.service = service; } - @Override public Observable getBalanceChanges(Currency currency, Object... args) { return service .subscribeChannel(Config.SPOT_BALANCES_CHANNEL) .map(GateioSingleSpotBalanceNotification.class::cast) - .filter(notification -> (currency == null) || (notification.getResult().getCurrency().equals(currency))) + .filter( + notification -> + (currency == null) || (notification.getResult().getCurrency().equals(currency))) .map(GateioStreamingAdapters::toBalance); } } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAdapters.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAdapters.java index e3da0b187d4..7709ed67c4a 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAdapters.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAdapters.java @@ -41,11 +41,9 @@ public Ticker toTicker(GateioTickerNotification notification) { .build(); } - public Trade toTrade(GateioTradeNotification notification) { TradePayload tradePayload = notification.getResult(); - return new Trade.Builder() .type(tradePayload.getSide()) .originalAmount(tradePayload.getAmount()) @@ -56,7 +54,6 @@ public Trade toTrade(GateioTradeNotification notification) { .build(); } - public UserTrade toUserTrade(GateioSingleUserTradeNotification notification) { UserTradePayload userTradePayload = notification.getResult(); @@ -74,7 +71,6 @@ public UserTrade toUserTrade(GateioSingleUserTradeNotification notification) { .build(); } - public Balance toBalance(GateioSingleSpotBalanceNotification notification) { BalancePayload balancePayload = notification.getResult(); @@ -87,18 +83,33 @@ public Balance toBalance(GateioSingleSpotBalanceNotification notification) { .build(); } - public OrderBook toOrderBook(GateioOrderBookNotification notification) { OrderBookPayload orderBookPayload = notification.getResult(); - Stream asks = orderBookPayload.getAsks().stream() - .map(priceSizeEntry -> new LimitOrder(OrderType.ASK, priceSizeEntry.getSize(), orderBookPayload.getCurrencyPair(), null, null, priceSizeEntry.getPrice())); - - Stream bids = orderBookPayload.getBids().stream() - .map(priceSizeEntry -> new LimitOrder(OrderType.BID, priceSizeEntry.getSize(), orderBookPayload.getCurrencyPair(), null, null, priceSizeEntry.getPrice())); + Stream asks = + orderBookPayload.getAsks().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.ASK, + priceSizeEntry.getSize(), + orderBookPayload.getCurrencyPair(), + null, + null, + priceSizeEntry.getPrice())); + + Stream bids = + orderBookPayload.getBids().stream() + .map( + priceSizeEntry -> + new LimitOrder( + OrderType.BID, + priceSizeEntry.getSize(), + orderBookPayload.getCurrencyPair(), + null, + null, + priceSizeEntry.getPrice())); return new OrderBook(Date.from(orderBookPayload.getTimestamp()), asks, bids); } - - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelper.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelper.java index 027bc25c7b0..bbab6672ea3 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelper.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelper.java @@ -13,10 +13,7 @@ public GateioStreamingAuthHelper(String apiSecret) { gateioV4Digest = GateioV4Digest.createInstance(apiSecret); } - - /** - * Generates signature based on payload - */ + /** Generates signature based on payload */ public String sign(String channel, String event, String timestamp) { Mac mac = gateioV4Digest.getMac(); @@ -25,5 +22,4 @@ public String sign(String channel, String event, String timestamp) { return DigestUtils.bytesToHex(mac.doFinal()); } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingExchange.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingExchange.java index ae59ffe3eaa..c518244ea64 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingExchange.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingExchange.java @@ -21,7 +21,11 @@ public GateioStreamingExchange() {} @Override public Completable connect(ProductSubscription... args) { - streamingService = new GateioStreamingService(exchangeSpecification.getSslUri(), exchangeSpecification.getApiKey(), exchangeSpecification.getSecretKey()); + streamingService = + new GateioStreamingService( + exchangeSpecification.getSslUri(), + exchangeSpecification.getApiKey(), + exchangeSpecification.getSecretKey()); applyStreamingSpecification(exchangeSpecification, streamingService); streamingMarketDataService = new GateioStreamingMarketDataService(streamingService); streamingTradeService = new GateioStreamingTradeService(streamingService); diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataService.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataService.java index 5cdf43730cc..06c0df09bfe 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataService.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataService.java @@ -23,7 +23,6 @@ public GateioStreamingMarketDataService(GateioStreamingService service) { this.service = service; } - /** * Uses the limited-level snapshot method: * https://www.gate.io/docs/apiv4/ws/index.html#limited-level-full-order-book-snapshot @@ -31,18 +30,17 @@ public GateioStreamingMarketDataService(GateioStreamingService service) { * @param currencyPair Currency pair of the order book * @param args Order book level: {@link Integer}, update speed: {@link Duration} */ - @Override public Observable getOrderBook(CurrencyPair currencyPair, Object... args) { Integer orderBookLevel = (Integer) ArrayUtils.get(args, 0, MAX_DEPTH_DEFAULT); Duration updateSpeed = (Duration) ArrayUtils.get(args, 1, UPDATE_INTERVAL_DEFAULT); return service - .subscribeChannel(Config.SPOT_ORDERBOOK_CHANNEL, new Object[]{currencyPair, orderBookLevel, updateSpeed}) + .subscribeChannel( + Config.SPOT_ORDERBOOK_CHANNEL, new Object[] {currencyPair, orderBookLevel, updateSpeed}) .map(GateioOrderBookNotification.class::cast) .map(GateioStreamingAdapters::toOrderBook); } - @Override public Observable getTicker(CurrencyPair currencyPair, Object... args) { return service @@ -51,7 +49,6 @@ public Observable getTicker(CurrencyPair currencyPair, Object... args) { .map(GateioStreamingAdapters::toTicker); } - @Override public Observable getTrades(CurrencyPair currencyPair, Object... args) { return service diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingService.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingService.java index 3a91a419b96..fe01d4a04f4 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingService.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingService.java @@ -1,6 +1,5 @@ package info.bitrich.xchangestream.gateio; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import info.bitrich.xchangestream.gateio.config.Config; @@ -34,9 +33,11 @@ @Slf4j public class GateioStreamingService extends NettyStreamingService { - private static final String USERTRADES_BROADCAST_CHANNEL_NAME = Config.SPOT_USER_TRADES_CHANNEL + Config.CHANNEL_NAME_DELIMITER + "null"; + private static final String USERTRADES_BROADCAST_CHANNEL_NAME = + Config.SPOT_USER_TRADES_CHANNEL + Config.CHANNEL_NAME_DELIMITER + "null"; - private final Map> subscriptions = new ConcurrentHashMap<>(); + private final Map> subscriptions = + new ConcurrentHashMap<>(); private final ObjectMapper objectMapper = Config.getInstance().getObjectMapper(); @@ -86,20 +87,20 @@ public Observable subscribeChannel(String channelName, Obj @Override public String getSubscribeMessage(String uniqueChannelName, Object... args) throws IOException { String generalChannelName = uniqueChannelName.split(Config.CHANNEL_NAME_DELIMITER)[0]; - GateioWsRequest request = getWsRequest(generalChannelName, Event.SUBSCRIBE , args); + GateioWsRequest request = getWsRequest(generalChannelName, Event.SUBSCRIBE, args); return objectMapper.writeValueAsString(request); } - private GateioWsRequest getWsRequest(String channelName, Event event, Object... args) { // create request common part - GateioWsRequest request = GateioWsRequest.builder() - .id(IdGenerator.getInstance().requestId()) - .channel(channelName) - .event(event) - .time(Instant.now(Config.getInstance().getClock())) - .build(); + GateioWsRequest request = + GateioWsRequest.builder() + .id(IdGenerator.getInstance().requestId()) + .channel(channelName) + .event(event) + .time(Instant.now(Config.getInstance().getClock())) + .build(); // create channel specific payload Object payload; @@ -107,45 +108,43 @@ private GateioWsRequest getWsRequest(String channelName, Event event, Object... // channels require only currency pair in payload case Config.SPOT_TICKERS_CHANNEL: - case Config.SPOT_TRADES_CHANNEL: { - CurrencyPair currencyPair = (CurrencyPair) ArrayUtils.get(args, 0); - Objects.requireNonNull(currencyPair); + case Config.SPOT_TRADES_CHANNEL: + { + CurrencyPair currencyPair = (CurrencyPair) ArrayUtils.get(args, 0); + Objects.requireNonNull(currencyPair); - payload = CurrencyPairPayload.builder() - .currencyPair(currencyPair) - .build(); - break; - } + payload = CurrencyPairPayload.builder().currencyPair(currencyPair).build(); + break; + } // channel requires currency pair, level, interval in payload - case Config.SPOT_ORDERBOOK_CHANNEL: { - CurrencyPair currencyPair = (CurrencyPair) ArrayUtils.get(args, 0); - Integer orderBookLevel = (Integer) ArrayUtils.get(args, 1); - Duration updateSpeed = (Duration) ArrayUtils.get(args, 2); - Validate.noNullElements(new Object[]{currencyPair, orderBookLevel, updateSpeed}); - - payload = CurrencyPairLevelIntervalPayload.builder() - .currencyPair(currencyPair) - .orderBookLevel(orderBookLevel) - .updateSpeed(updateSpeed) - .build(); - break; - } + case Config.SPOT_ORDERBOOK_CHANNEL: + { + CurrencyPair currencyPair = (CurrencyPair) ArrayUtils.get(args, 0); + Integer orderBookLevel = (Integer) ArrayUtils.get(args, 1); + Duration updateSpeed = (Duration) ArrayUtils.get(args, 2); + Validate.noNullElements(new Object[] {currencyPair, orderBookLevel, updateSpeed}); + + payload = + CurrencyPairLevelIntervalPayload.builder() + .currencyPair(currencyPair) + .orderBookLevel(orderBookLevel) + .updateSpeed(updateSpeed) + .build(); + break; + } // channel requires currency pair or default value for all - case Config.SPOT_USER_TRADES_CHANNEL: { - CurrencyPair currencyPair = (CurrencyPair) ArrayUtils.get(args, 0); - if (currencyPair == null) { - payload = StringPayload.builder() - .data("!all") - .build(); - } else { - payload = CurrencyPairPayload.builder() - .currencyPair(currencyPair) - .build(); + case Config.SPOT_USER_TRADES_CHANNEL: + { + CurrencyPair currencyPair = (CurrencyPair) ArrayUtils.get(args, 0); + if (currencyPair == null) { + payload = StringPayload.builder().data("!all").build(); + } else { + payload = CurrencyPairPayload.builder().currencyPair(currencyPair).build(); + } + break; } - break; - } default: payload = EmptyPayload.builder().build(); @@ -153,24 +152,27 @@ private GateioWsRequest getWsRequest(String channelName, Event event, Object... // add auth for private channels if (Config.PRIVATE_CHANNELS.contains(channelName)) { - request.setAuthInfo(AuthInfo.builder() + request.setAuthInfo( + AuthInfo.builder() .method("api_key") .key(apiKey) - .sign(gateioStreamingAuthHelper.sign(channelName, event.getValue(), String.valueOf(request.getTime().getEpochSecond()))) - .build()); + .sign( + gateioStreamingAuthHelper.sign( + channelName, + event.getValue(), + String.valueOf(request.getTime().getEpochSecond()))) + .build()); } request.setPayload(payload); return request; } - @Override protected WebSocketClientExtensionHandler getWebSocketClientExtensionHandler() { return WebSocketClientCompressionAllowClientNoContextAndServerNoContextHandler.INSTANCE; } - /** * Returns a JSON String containing the unsubscribe message. * @@ -199,27 +201,26 @@ public void messageHandler(String message) { return; } - GateioWsNotification notification = objectMapper.treeToValue(jsonNode, GateioWsNotification.class); + GateioWsNotification notification = + objectMapper.treeToValue(jsonNode, GateioWsNotification.class); // process arrays in "result" field -> emit each item separately if (notification instanceof GateioMultipleUserTradeNotification) { - GateioMultipleUserTradeNotification multipleNotification = (GateioMultipleUserTradeNotification) notification; + GateioMultipleUserTradeNotification multipleNotification = + (GateioMultipleUserTradeNotification) notification; multipleNotification.toSingleNotifications().forEach(this::handleMessage); - } - else if (notification instanceof GateioMultipleSpotBalanceNotification) { - GateioMultipleSpotBalanceNotification multipleNotification = (GateioMultipleSpotBalanceNotification) notification; + } else if (notification instanceof GateioMultipleSpotBalanceNotification) { + GateioMultipleSpotBalanceNotification multipleNotification = + (GateioMultipleSpotBalanceNotification) notification; multipleNotification.toSingleNotifications().forEach(this::handleMessage); - } - else { + } else { handleMessage(notification); } } catch (IOException e) { log.error("Error parsing incoming message to JSON: {}", message); } - } - @Override protected void handleChannelMessage(String channel, GateioWsNotification message) { if (channel == null) { @@ -231,8 +232,8 @@ protected void handleChannelMessage(String channel, GateioWsNotification message if (message instanceof GateioSingleUserTradeNotification) { // subscription that listens to all currency pairs - NettyStreamingService.Subscription broadcast = channels.get( - USERTRADES_BROADCAST_CHANNEL_NAME); + NettyStreamingService.Subscription broadcast = + channels.get(USERTRADES_BROADCAST_CHANNEL_NAME); if (broadcast != null && broadcast.getEmitter() != null) { broadcast.getEmitter().onNext(message); } @@ -243,10 +244,8 @@ protected void handleChannelMessage(String channel, GateioWsNotification message specific.getEmitter().onNext(message); } - } - else { + } else { super.handleChannelMessage(channel, message); } - } } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeService.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeService.java index 59e92127ff3..15664abdcbe 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeService.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeService.java @@ -15,7 +15,6 @@ public GateioStreamingTradeService(GateioStreamingService service) { this.service = service; } - @Override public Observable getUserTrades(CurrencyPair currencyPair, Object... args) { return service diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/Config.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/Config.java index 0d373586d85..c40bc2e1974 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/Config.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/Config.java @@ -20,7 +20,8 @@ public final class Config { public static final String SPOT_TICKERS_CHANNEL = "spot.tickers"; public static final String SPOT_BALANCES_CHANNEL = "spot.balances"; public static final String SPOT_USER_TRADES_CHANNEL = "spot.usertrades"; - public static final List PRIVATE_CHANNELS = Arrays.asList(SPOT_BALANCES_CHANNEL, SPOT_USER_TRADES_CHANNEL); + public static final List PRIVATE_CHANNELS = + Arrays.asList(SPOT_BALANCES_CHANNEL, SPOT_USER_TRADES_CHANNEL); public static final String CHANNEL_NAME_DELIMITER = "-"; @@ -48,10 +49,7 @@ private Config() { objectMapper.registerModule(new JavaTimeModule()); } - public static Config getInstance() { return instance; } - - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/IdGenerator.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/IdGenerator.java index 02dfe87df0c..146a398a311 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/IdGenerator.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/IdGenerator.java @@ -6,17 +6,13 @@ public final class IdGenerator { private static IdGenerator instance = new IdGenerator(); - private IdGenerator() { - } + private IdGenerator() {} public static IdGenerator getInstance() { return instance; } - public Long requestId() { return ThreadLocalRandom.current().nextLong(); } } - - diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/converter/InstantToTimestampSecondsConverter.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/converter/InstantToTimestampSecondsConverter.java index ff5e75d0a39..55da78eb7ac 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/converter/InstantToTimestampSecondsConverter.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/config/converter/InstantToTimestampSecondsConverter.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.databind.util.StdConverter; import java.time.Instant; -/** - * Converts {@code Instant} to timestamp in seconds - */ +/** Converts {@code Instant} to timestamp in seconds */ public class InstantToTimestampSecondsConverter extends StdConverter { @Override diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/Event.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/Event.java index 701149e1a90..96dc9b7a9c5 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/Event.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/Event.java @@ -11,8 +11,5 @@ public enum Event { UNSUBSCRIBE("unsubscribe"), UPDATE("update"); - @JsonValue - private final String value; - - + @JsonValue private final String value; } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/GateioWsRequest.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/GateioWsRequest.java index 6c55d44ce4e..0f5d10e9d38 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/GateioWsRequest.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/GateioWsRequest.java @@ -38,7 +38,6 @@ public class GateioWsRequest { @JsonFormat(shape = JsonFormat.Shape.ARRAY) private Object payload; - @Data @SuperBuilder @Jacksonized @@ -52,7 +51,5 @@ public static class AuthInfo { @JsonProperty("sign") private String sign; - } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairLevelIntervalPayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairLevelIntervalPayload.java index 7a4256633f8..a80375f3ac8 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairLevelIntervalPayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairLevelIntervalPayload.java @@ -28,5 +28,4 @@ public class CurrencyPairLevelIntervalPayload { public String renderUpdateSpeed() { return updateSpeed.toMillis() + "ms"; } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairPayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairPayload.java index 6c329092686..c6b7f9a36cb 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairPayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/CurrencyPairPayload.java @@ -14,5 +14,4 @@ public class CurrencyPairPayload { @JsonSerialize(converter = CurrencyPairToStringConverter.class) private CurrencyPair currencyPair; - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/EmptyPayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/EmptyPayload.java index 8481d829958..fe3ab162484 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/EmptyPayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/EmptyPayload.java @@ -7,6 +7,4 @@ @Data @SuperBuilder @Jacksonized -public class EmptyPayload { - -} +public class EmptyPayload {} diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/StringPayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/StringPayload.java index 4e3b484d6e7..3f91248d2cd 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/StringPayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/request/payload/StringPayload.java @@ -10,5 +10,4 @@ public class StringPayload { private String data; - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotification.java index e983b8efea5..efad0a0f516 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotification.java @@ -18,16 +18,13 @@ import lombok.extern.jackson.Jacksonized; import org.knowm.xchange.gateio.config.converter.TimestampSecondsToInstantConverter; -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - property = "channel", - visible = true) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "channel", visible = true) @JsonSubTypes({ - @Type(value = GateioTradeNotification.class, name = Config.SPOT_TRADES_CHANNEL), - @Type(value = GateioTickerNotification.class, name = Config.SPOT_TICKERS_CHANNEL), - @Type(value = GateioOrderBookNotification.class, name = Config.SPOT_ORDERBOOK_CHANNEL), - @Type(value = GateioMultipleSpotBalanceNotification.class, name = Config.SPOT_BALANCES_CHANNEL), - @Type(value = GateioMultipleUserTradeNotification.class, name = Config.SPOT_USER_TRADES_CHANNEL) + @Type(value = GateioTradeNotification.class, name = Config.SPOT_TRADES_CHANNEL), + @Type(value = GateioTickerNotification.class, name = Config.SPOT_TICKERS_CHANNEL), + @Type(value = GateioOrderBookNotification.class, name = Config.SPOT_ORDERBOOK_CHANNEL), + @Type(value = GateioMultipleSpotBalanceNotification.class, name = Config.SPOT_BALANCES_CHANNEL), + @Type(value = GateioMultipleUserTradeNotification.class, name = Config.SPOT_USER_TRADES_CHANNEL) }) @Data @SuperBuilder @@ -50,9 +47,7 @@ public class GateioWsNotification { @JsonProperty("error") private String error; - public String getUniqueChannelName() { return channel; } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/BalancePayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/BalancePayload.java index fc70c5eb980..0232d57f0e3 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/BalancePayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/BalancePayload.java @@ -39,8 +39,6 @@ public class BalancePayload { @JsonProperty("freeze_change") BigDecimal freezeChange; - @JsonProperty("change_type") String changeType; - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioMultipleSpotBalanceNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioMultipleSpotBalanceNotification.java index 3d6e8617ef5..118e5b88327 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioMultipleSpotBalanceNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioMultipleSpotBalanceNotification.java @@ -16,17 +16,18 @@ public class GateioMultipleSpotBalanceNotification extends GateioWsNotification @JsonProperty("result") private List result; - public List toSingleNotifications() { return result.stream() - .map(balancePayload -> GateioSingleSpotBalanceNotification.builder() - .result(balancePayload) - .time(getTime()) - .timeMs(getTimeMs()) - .channel(getChannel()) - .event(getEvent()) - .error(getError()) - .build()) + .map( + balancePayload -> + GateioSingleSpotBalanceNotification.builder() + .result(balancePayload) + .time(getTime()) + .timeMs(getTimeMs()) + .channel(getChannel()) + .event(getEvent()) + .error(getError()) + .build()) .collect(Collectors.toList()); } } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioSingleSpotBalanceNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioSingleSpotBalanceNotification.java index db22e18e605..8558356a6d5 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioSingleSpotBalanceNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/balance/GateioSingleSpotBalanceNotification.java @@ -16,6 +16,4 @@ public String getUniqueChannelName() { // there is no currency specific subscription return super.getUniqueChannelName() + Config.CHANNEL_NAME_DELIMITER + "null"; } - - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/GateioOrderBookNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/GateioOrderBookNotification.java index 2960524f807..1262a58aa98 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/GateioOrderBookNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/GateioOrderBookNotification.java @@ -17,8 +17,10 @@ public class GateioOrderBookNotification extends GateioWsNotification { @Override public String getUniqueChannelName() { - String suffix = result.getCurrencyPair() != null ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() : ""; + String suffix = + result.getCurrencyPair() != null + ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() + : ""; return super.getUniqueChannelName() + suffix; } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/OrderBookPayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/OrderBookPayload.java index ebb8698a5ad..7407d46315c 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/OrderBookPayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/orderbook/OrderBookPayload.java @@ -25,14 +25,12 @@ public class OrderBookPayload { @JsonDeserialize(converter = StringToCurrencyPairConverter.class) CurrencyPair currencyPair; - @JsonProperty("asks") List asks; @JsonProperty("bids") List bids; - @Data @Builder @Jacksonized @@ -42,8 +40,5 @@ public static class PriceSizeEntry { BigDecimal price; BigDecimal size; - } - - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/GateioTickerNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/GateioTickerNotification.java index c75e9141128..43aa9e9f29b 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/GateioTickerNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/GateioTickerNotification.java @@ -17,8 +17,10 @@ public class GateioTickerNotification extends GateioWsNotification { @Override public String getUniqueChannelName() { - String suffix = result.getCurrencyPair() != null ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() : ""; + String suffix = + result.getCurrencyPair() != null + ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() + : ""; return super.getUniqueChannelName() + suffix; } - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/TickerPayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/TickerPayload.java index b182cdf77f8..0cc493e8ca4 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/TickerPayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/ticker/TickerPayload.java @@ -37,5 +37,4 @@ public class TickerPayload { @JsonProperty("low_24h") BigDecimal lowPrice24h; - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/GateioTradeNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/GateioTradeNotification.java index 12eae15ae9d..066f6485426 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/GateioTradeNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/GateioTradeNotification.java @@ -17,7 +17,10 @@ public class GateioTradeNotification extends GateioWsNotification { @Override public String getUniqueChannelName() { - String suffix = result.getCurrencyPair() != null ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() : ""; + String suffix = + result.getCurrencyPair() != null + ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() + : ""; return super.getUniqueChannelName() + suffix; } } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/TradePayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/TradePayload.java index b4e1e8e366f..478d64d7320 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/TradePayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/trade/TradePayload.java @@ -42,5 +42,4 @@ public class TradePayload { @JsonProperty("price") BigDecimal price; - } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioMultipleUserTradeNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioMultipleUserTradeNotification.java index 2ba4bb69064..b756d17a7df 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioMultipleUserTradeNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioMultipleUserTradeNotification.java @@ -16,17 +16,18 @@ public class GateioMultipleUserTradeNotification extends GateioWsNotification { @JsonProperty("result") private List result; - public List toSingleNotifications() { return result.stream() - .map(userTradePayload -> GateioSingleUserTradeNotification.builder() - .result(userTradePayload) - .time(getTime()) - .timeMs(getTimeMs()) - .channel(getChannel()) - .event(getEvent()) - .error(getError()) - .build()) + .map( + userTradePayload -> + GateioSingleUserTradeNotification.builder() + .result(userTradePayload) + .time(getTime()) + .timeMs(getTimeMs()) + .channel(getChannel()) + .event(getEvent()) + .error(getError()) + .build()) .collect(Collectors.toList()); } } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioSingleUserTradeNotification.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioSingleUserTradeNotification.java index be5238c780d..09523c2d866 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioSingleUserTradeNotification.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/GateioSingleUserTradeNotification.java @@ -13,7 +13,10 @@ public class GateioSingleUserTradeNotification extends GateioWsNotification { @Override public String getUniqueChannelName() { - String suffix = result.getCurrencyPair() != null ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() : ""; + String suffix = + result.getCurrencyPair() != null + ? Config.CHANNEL_NAME_DELIMITER + result.getCurrencyPair() + : ""; return super.getUniqueChannelName() + suffix; } } diff --git a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/UserTradePayload.java b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/UserTradePayload.java index adb9f9caf2b..a8c85b4b143 100644 --- a/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/UserTradePayload.java +++ b/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/dto/response/usertrade/UserTradePayload.java @@ -68,5 +68,4 @@ public class UserTradePayload { @JsonProperty("text") String remark; - } diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceIntegration.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceIntegration.java index da6e4f60355..979b6f39a47 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceIntegration.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceIntegration.java @@ -12,32 +12,29 @@ import org.knowm.xchange.currency.Currency; import org.knowm.xchange.dto.account.Balance; -@Disabled("Needs authenticated exchange and real balance change. Set env vars GATEIO_API_KEY/GATEIO_API_SECRET") +@Disabled( + "Needs authenticated exchange and real balance change. Set env vars GATEIO_API_KEY/GATEIO_API_SECRET") class GateioStreamingAccountServiceIntegration extends GateioStreamingExchangeIT { @BeforeEach void authConfigured() { - assumeTrue(StringUtils.isNotEmpty(exchange.getExchangeSpecification().getApiKey()), "Needs auth"); - assumeTrue(StringUtils.isNotEmpty(exchange.getExchangeSpecification().getSecretKey()), "Needs auth"); + assumeTrue( + StringUtils.isNotEmpty(exchange.getExchangeSpecification().getApiKey()), "Needs auth"); + assumeTrue( + StringUtils.isNotEmpty(exchange.getExchangeSpecification().getSecretKey()), "Needs auth"); } - @Test void spot_balances() { - Observable observable = exchange - .getStreamingAccountService() - .getBalanceChanges(Currency.USDT); + Observable observable = + exchange.getStreamingAccountService().getBalanceChanges(Currency.USDT); TestObserver testObserver = observable.test(); - Balance balance = testObserver - .awaitCount(1) - .values().get(0); + Balance balance = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); assertThat(balance).hasNoNullFieldsOrProperties(); } - - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceTest.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceTest.java index 1ddfb36cd30..ee0e6593b33 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceTest.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAccountServiceTest.java @@ -25,24 +25,24 @@ @ExtendWith(MockitoExtension.class) class GateioStreamingAccountServiceTest { - @Mock - GateioStreamingService gateioStreamingService; + @Mock GateioStreamingService gateioStreamingService; GateioStreamingAccountService gateioStreamingAccountService; ObjectMapper objectMapper = Config.getInstance().getObjectMapper(); - @BeforeEach public void setup() { gateioStreamingAccountService = new GateioStreamingAccountService(gateioStreamingService); } - @Test void spot_balances() throws Exception { GateioWsNotification multipleNotification = readNotification("spot.balance.update.json"); assertThat(multipleNotification).isInstanceOf(GateioMultipleSpotBalanceNotification.class); - GateioWsNotification notification = ((GateioMultipleSpotBalanceNotification) multipleNotification).toSingleNotifications().get(0); + GateioWsNotification notification = + ((GateioMultipleSpotBalanceNotification) multipleNotification) + .toSingleNotifications() + .get(0); when(gateioStreamingService.subscribeChannel(eq("spot.balances"))) .thenReturn(Observable.just(notification)); @@ -51,30 +51,24 @@ void spot_balances() throws Exception { TestObserver testObserver = observable.test(); - Balance actual = testObserver - .awaitCount(1) - .values().get(0); + Balance actual = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); - Balance expected = new Balance.Builder() - .available(new BigDecimal("42.06583427604872431142")) - .currency(Currency.USDT) - .frozen(BigDecimal.ONE) - .timestamp(Date.from(Instant.ofEpochMilli(1691707273890L))) - .total(new BigDecimal("43.06583427604872431142")) - .build(); + Balance expected = + new Balance.Builder() + .available(new BigDecimal("42.06583427604872431142")) + .currency(Currency.USDT) + .frozen(BigDecimal.ONE) + .timestamp(Date.from(Instant.ofEpochMilli(1691707273890L))) + .total(new BigDecimal("43.06583427604872431142")) + .build(); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - private GateioWsNotification readNotification(String resourceName) throws IOException { return objectMapper.readValue( - getClass().getClassLoader().getResourceAsStream(resourceName), - GateioWsNotification.class - ); + getClass().getClassLoader().getResourceAsStream(resourceName), GateioWsNotification.class); } - - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelperTest.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelperTest.java index 0bf85f3adf3..5c33ff24637 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelperTest.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelperTest.java @@ -15,8 +15,8 @@ void sign() { GateioStreamingAuthHelper gateioStreamingAuthHelper = new GateioStreamingAuthHelper(apiSecret); String actual = gateioStreamingAuthHelper.sign(channel, event, time); - String expected = "36481b07c37f27bbfda955c312580e70652d856e7626698f7a5250cf31ffb4052be60f2ec42e6e8816c9fb93d7e26d33f8ef245346b7fd2316ad99dd05ad8176"; + String expected = + "36481b07c37f27bbfda955c312580e70652d856e7626698f7a5250cf31ffb4052be60f2ec42e6e8816c9fb93d7e26d33f8ef245346b7fd2316ad99dd05ad8176"; assertThat(actual).isEqualTo(expected); - } -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingExchangeIT.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingExchangeIT.java index 8553614e150..43bfae14870 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingExchangeIT.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingExchangeIT.java @@ -16,37 +16,30 @@ public class GateioStreamingExchangeIT { public static void setup() { try { - ExchangeSpecification spec = - StreamingExchangeFactory.INSTANCE - .createExchangeWithoutSpecification(GateioStreamingExchange.class) - .getDefaultExchangeSpecification(); - spec.setApiKey(System.getenv("GATEIO_API_KEY")); - spec.setSecretKey(System.getenv("GATEIO_API_SECRET")); + ExchangeSpecification spec = + StreamingExchangeFactory.INSTANCE + .createExchangeWithoutSpecification(GateioStreamingExchange.class) + .getDefaultExchangeSpecification(); + spec.setApiKey(System.getenv("GATEIO_API_KEY")); + spec.setSecretKey(System.getenv("GATEIO_API_SECRET")); - exchange = - (GateioStreamingExchange) StreamingExchangeFactory.INSTANCE.createExchange(spec); + exchange = (GateioStreamingExchange) StreamingExchangeFactory.INSTANCE.createExchange(spec); - exchange.connect().blockingAwait(); - } - catch (Exception ignored) { + exchange.connect().blockingAwait(); + } catch (Exception ignored) { } } - @BeforeEach void exchangeReachable() { assumeTrue(exchange.isAlive(), "Exchange is unreachable"); } - @AfterAll public static void cleanup() { if (exchange.isAlive()) { exchange.disconnect().blockingAwait(); } } - - - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceIntegration.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceIntegration.java index 17a46e34641..8f9cc9bddb3 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceIntegration.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceIntegration.java @@ -15,15 +15,14 @@ public class GateioStreamingMarketDataServiceIntegration extends GateioStreaming @Test void order_book() { - Observable observable = exchange - .getStreamingMarketDataService() - .getOrderBook(CurrencyPair.BTC_USDT, 10, Duration.ofMillis(100)); + Observable observable = + exchange + .getStreamingMarketDataService() + .getOrderBook(CurrencyPair.BTC_USDT, 10, Duration.ofMillis(100)); TestObserver testObserver = observable.test(); - OrderBook orderBook = testObserver - .awaitCount(1) - .values().get(0); + OrderBook orderBook = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); @@ -32,48 +31,37 @@ void order_book() { assertThat(orderBook.getAsks()).hasSize(10); // bids should be lower than asks - assertThat(orderBook.getBids().get(0).getLimitPrice()).isLessThan(orderBook.getAsks().get(0).getLimitPrice()); + assertThat(orderBook.getBids().get(0).getLimitPrice()) + .isLessThan(orderBook.getAsks().get(0).getLimitPrice()); } - @Test void trades() { - Observable observable = exchange - .getStreamingMarketDataService() - .getTrades(CurrencyPair.BTC_USDT); + Observable observable = + exchange.getStreamingMarketDataService().getTrades(CurrencyPair.BTC_USDT); TestObserver testObserver = observable.test(); - Trade trade = testObserver - .awaitCount(1) - .values().get(0); + Trade trade = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); assertThat(trade).hasNoNullFieldsOrPropertiesExcept("makerOrderId", "takerOrderId"); assertThat(trade.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); - } - @Test void ticker() { - Observable observable = exchange - .getStreamingMarketDataService() - .getTicker(CurrencyPair.BTC_USDT); + Observable observable = + exchange.getStreamingMarketDataService().getTicker(CurrencyPair.BTC_USDT); TestObserver testObserver = observable.test(); - Ticker ticker = testObserver - .awaitCount(1) - .values() - .get(0); + Ticker ticker = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); assertThat(ticker).hasNoNullFieldsOrPropertiesExcept("open", "vwap", "bidSize", "askSize"); assertThat(ticker.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); } - - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceTest.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceTest.java index f9c4e887bea..5e85a23de12 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceTest.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataServiceTest.java @@ -28,8 +28,7 @@ @ExtendWith(MockitoExtension.class) class GateioStreamingMarketDataServiceTest { - @Mock - GateioStreamingService gateioStreamingService; + @Mock GateioStreamingService gateioStreamingService; GateioStreamingMarketDataService gateioStreamingMarketDataService; ObjectMapper objectMapper = Config.getInstance().getObjectMapper(); @@ -39,21 +38,20 @@ public void setup() { gateioStreamingMarketDataService = new GateioStreamingMarketDataService(gateioStreamingService); } - @Test void order_book() throws Exception { GateioWsNotification notification = readNotification("spot.order_book.update.json"); - when(gateioStreamingService.subscribeChannel(eq("spot.order_book"), eq(CurrencyPair.BTC_USDT), eq(10), eq(Duration.ofMillis(100)))) + when(gateioStreamingService.subscribeChannel( + eq("spot.order_book"), eq(CurrencyPair.BTC_USDT), eq(10), eq(Duration.ofMillis(100)))) .thenReturn(Observable.just(notification)); - Observable observable = gateioStreamingMarketDataService - .getOrderBook(CurrencyPair.BTC_USDT, 10, Duration.ofMillis(100)); + Observable observable = + gateioStreamingMarketDataService.getOrderBook( + CurrencyPair.BTC_USDT, 10, Duration.ofMillis(100)); TestObserver testObserver = observable.test(); - OrderBook actual = testObserver - .awaitCount(1) - .values().get(0); + OrderBook actual = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); @@ -62,35 +60,34 @@ void order_book() throws Exception { assertThat(actual.getAsks()).hasSize(10); } - @Test void ticker() throws Exception { GateioWsNotification notification = readNotification("spot.ticker.update.json"); when(gateioStreamingService.subscribeChannel(eq("spot.tickers"), eq(CurrencyPair.BTC_USDT))) .thenReturn(Observable.just(notification)); - Observable observable = gateioStreamingMarketDataService.getTicker(CurrencyPair.BTC_USDT); + Observable observable = + gateioStreamingMarketDataService.getTicker(CurrencyPair.BTC_USDT); TestObserver testObserver = observable.test(); - Ticker actual = testObserver - .awaitCount(1) - .values().get(0); + Ticker actual = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); - Ticker expected = new Ticker.Builder() - .instrument(CurrencyPair.BTC_USDT) - .timestamp(Date.from(Instant.ofEpochMilli(1691620566926L))) - .ask(new BigDecimal("29573.7")) - .bid(new BigDecimal("29573.6")) - .high(new BigDecimal("30232.8")) - .low(new BigDecimal("29176.1")) - .last(new BigDecimal("29573.7")) - .percentageChange(new BigDecimal("-0.6601")) - .quoteVolume(new BigDecimal("171784719.492586746")) - .volume(new BigDecimal("5777.7777606776")) - .build(); + Ticker expected = + new Ticker.Builder() + .instrument(CurrencyPair.BTC_USDT) + .timestamp(Date.from(Instant.ofEpochMilli(1691620566926L))) + .ask(new BigDecimal("29573.7")) + .bid(new BigDecimal("29573.6")) + .high(new BigDecimal("30232.8")) + .low(new BigDecimal("29176.1")) + .last(new BigDecimal("29573.7")) + .percentageChange(new BigDecimal("-0.6601")) + .quoteVolume(new BigDecimal("171784719.492586746")) + .volume(new BigDecimal("5777.7777606776")) + .build(); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } @@ -101,34 +98,30 @@ void trades() throws Exception { when(gateioStreamingService.subscribeChannel(eq("spot.trades"), eq(CurrencyPair.BTC_USDT))) .thenReturn(Observable.just(notification)); - Observable observable = gateioStreamingMarketDataService.getTrades(CurrencyPair.BTC_USDT); + Observable observable = + gateioStreamingMarketDataService.getTrades(CurrencyPair.BTC_USDT); TestObserver testObserver = observable.test(); - Trade actual = testObserver - .awaitCount(1) - .values().get(0); + Trade actual = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); - Trade expected = new Trade.Builder() - .instrument(CurrencyPair.BTC_USDT) - .id("6064666343") - .originalAmount(new BigDecimal("0.0003009")) - .price(new BigDecimal("29573.7")) - .timestamp(Date.from(Instant.ofEpochMilli(1691620568789L))) - .type(OrderType.BID) - .build(); + Trade expected = + new Trade.Builder() + .instrument(CurrencyPair.BTC_USDT) + .id("6064666343") + .originalAmount(new BigDecimal("0.0003009")) + .price(new BigDecimal("29573.7")) + .timestamp(Date.from(Instant.ofEpochMilli(1691620568789L))) + .type(OrderType.BID) + .build(); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - private GateioWsNotification readNotification(String resourceName) throws IOException { return objectMapper.readValue( - getClass().getClassLoader().getResourceAsStream(resourceName), - GateioWsNotification.class - ); + getClass().getClassLoader().getResourceAsStream(resourceName), GateioWsNotification.class); } - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingServiceTest.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingServiceTest.java index 43dc7a8b4eb..c4b69660e68 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingServiceTest.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingServiceTest.java @@ -1,6 +1,5 @@ package info.bitrich.xchangestream.gateio; - import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.databind.ObjectMapper; @@ -21,7 +20,6 @@ void channel_name_from_orderbook_update() throws Exception { assertThat(actual).isEqualTo("spot.order_book-BTC/USDT"); } - @Test void channel_name_from_ticker_update() throws Exception { GateioWsNotification notification = readNotification("spot.ticker.update.json"); @@ -29,7 +27,6 @@ void channel_name_from_ticker_update() throws Exception { assertThat(actual).isEqualTo("spot.tickers-BTC/USDT"); } - @Test void channel_name_from_trade_update() throws Exception { GateioWsNotification notification = readNotification("spot.trades.update.json"); @@ -37,7 +34,6 @@ void channel_name_from_trade_update() throws Exception { assertThat(actual).isEqualTo("spot.trades-BTC/USDT"); } - @Test void channel_name_from_subscribe_event() throws Exception { GateioWsNotification notification = readNotification("subscribe.event.json"); @@ -45,7 +41,6 @@ void channel_name_from_subscribe_event() throws Exception { assertThat(actual).isEqualTo("spot.order_book"); } - @Test void channel_name_from_unsubscribe_event() throws Exception { GateioWsNotification notification = readNotification("unsubscribe.event.json"); @@ -55,10 +50,6 @@ void channel_name_from_unsubscribe_event() throws Exception { private GateioWsNotification readNotification(String resourceName) throws IOException { return objectMapper.readValue( - getClass().getClassLoader().getResourceAsStream(resourceName), - GateioWsNotification.class - ); + getClass().getClassLoader().getResourceAsStream(resourceName), GateioWsNotification.class); } - - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceIntegration.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceIntegration.java index 2eafde2a0c9..c41e96844e7 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceIntegration.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceIntegration.java @@ -12,27 +12,26 @@ import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.trade.UserTrade; -@Disabled("Needs authenticated exchange and real user trade. Set env vars GATEIO_API_KEY/GATEIO_API_SECRET") +@Disabled( + "Needs authenticated exchange and real user trade. Set env vars GATEIO_API_KEY/GATEIO_API_SECRET") class GateioStreamingTradeServiceIntegration extends GateioStreamingExchangeIT { @BeforeEach void authConfigured() { - assumeTrue(StringUtils.isNotEmpty(exchange.getExchangeSpecification().getApiKey()), "Needs auth"); - assumeTrue(StringUtils.isNotEmpty(exchange.getExchangeSpecification().getSecretKey()), "Needs auth"); + assumeTrue( + StringUtils.isNotEmpty(exchange.getExchangeSpecification().getApiKey()), "Needs auth"); + assumeTrue( + StringUtils.isNotEmpty(exchange.getExchangeSpecification().getSecretKey()), "Needs auth"); } - @Test void user_trades_btc() { - Observable observable = exchange - .getStreamingTradeService() - .getUserTrades(CurrencyPair.BTC_USDT); + Observable observable = + exchange.getStreamingTradeService().getUserTrades(CurrencyPair.BTC_USDT); TestObserver testObserver = observable.test(); - UserTrade userTrade = testObserver - .awaitCount(1) - .values().get(0); + UserTrade userTrade = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); @@ -40,22 +39,16 @@ void user_trades_btc() { assertThat(userTrade.getInstrument()).isEqualTo(CurrencyPair.BTC_USDT); } - @Test void user_trades_all() { - Observable observable = exchange - .getStreamingTradeService() - .getUserTrades(); + Observable observable = exchange.getStreamingTradeService().getUserTrades(); TestObserver testObserver = observable.test(); - UserTrade userTrade = testObserver - .awaitCount(1) - .values().get(0); + UserTrade userTrade = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); assertThat(userTrade).hasNoNullFieldsOrPropertiesExcept("makerOrderId", "takerOrderId"); } - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceTest.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceTest.java index 02607c27ed1..0c8cac6d708 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceTest.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/GateioStreamingTradeServiceTest.java @@ -27,8 +27,7 @@ @ExtendWith(MockitoExtension.class) class GateioStreamingTradeServiceTest { - @Mock - GateioStreamingService gateioStreamingService; + @Mock GateioStreamingService gateioStreamingService; GateioStreamingTradeService gateioStreamingTradeService; ObjectMapper objectMapper = Config.getInstance().getObjectMapper(); @@ -38,49 +37,44 @@ public void setup() { gateioStreamingTradeService = new GateioStreamingTradeService(gateioStreamingService); } - @Test void user_trades_btc() throws Exception { GateioWsNotification multipleNotification = readNotification("spot.usertrades.update.json"); assertThat(multipleNotification).isInstanceOf(GateioMultipleUserTradeNotification.class); - GateioWsNotification notification = ((GateioMultipleUserTradeNotification) multipleNotification).toSingleNotifications().get(0); + GateioWsNotification notification = + ((GateioMultipleUserTradeNotification) multipleNotification).toSingleNotifications().get(0); when(gateioStreamingService.subscribeChannel(eq("spot.usertrades"), eq(CurrencyPair.BTC_USDT))) .thenReturn(Observable.just(notification)); - Observable observable = gateioStreamingTradeService.getUserTrades(CurrencyPair.BTC_USDT); + Observable observable = + gateioStreamingTradeService.getUserTrades(CurrencyPair.BTC_USDT); TestObserver testObserver = observable.test(); - UserTrade actual = testObserver - .awaitCount(1) - .values().get(0); + UserTrade actual = testObserver.awaitCount(1).values().get(0); testObserver.dispose(); - UserTrade expected = new UserTrade.Builder() - .instrument(CurrencyPair.BTC_USDT) - .id("6068323582") - .orderId("381004078014") - .orderUserReference("3") - .originalAmount(new BigDecimal("0.00003")) - .feeAmount(new BigDecimal("0.00000006")) - .feeCurrency(Currency.BTC) - .price(new BigDecimal("29441.1")) - .timestamp(Date.from(Instant.ofEpochMilli(1691692159330L))) - .type(OrderType.BID) - .build(); + UserTrade expected = + new UserTrade.Builder() + .instrument(CurrencyPair.BTC_USDT) + .id("6068323582") + .orderId("381004078014") + .orderUserReference("3") + .originalAmount(new BigDecimal("0.00003")) + .feeAmount(new BigDecimal("0.00000006")) + .feeCurrency(Currency.BTC) + .price(new BigDecimal("29441.1")) + .timestamp(Date.from(Instant.ofEpochMilli(1691692159330L))) + .type(OrderType.BID) + .build(); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); } - private GateioWsNotification readNotification(String resourceName) throws IOException { return objectMapper.readValue( - getClass().getClassLoader().getResourceAsStream(resourceName), - GateioWsNotification.class - ); + getClass().getClassLoader().getResourceAsStream(resourceName), GateioWsNotification.class); } - - -} \ No newline at end of file +} diff --git a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotificationTest.java b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotificationTest.java index d4d615fab28..a0eed9d9a38 100644 --- a/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotificationTest.java +++ b/xchange-stream-gateio/src/test/java/info/bitrich/xchangestream/gateio/dto/response/GateioWsNotificationTest.java @@ -22,41 +22,32 @@ void deserialize_trades() throws Exception { assertThat(notification).isInstanceOf(GateioTradeNotification.class); } - @Test void deserialize_ticker() throws Exception { GateioWsNotification notification = readNotification("spot.ticker.update.json"); assertThat(notification).isInstanceOf(GateioTickerNotification.class); } - @Test void deserialize_orderbook() throws Exception { GateioWsNotification notification = readNotification("spot.order_book.update.json"); assertThat(notification).isInstanceOf(GateioOrderBookNotification.class); } - @Test void deserialize_usertrades() throws Exception { GateioWsNotification notification = readNotification("spot.usertrades.update.json"); assertThat(notification).isInstanceOf(GateioMultipleUserTradeNotification.class); } - @Test void deserialize_balances() throws Exception { GateioWsNotification notification = readNotification("spot.balance.update.json"); assertThat(notification).isInstanceOf(GateioMultipleSpotBalanceNotification.class); } - private GateioWsNotification readNotification(String resourceName) throws IOException { return objectMapper.readValue( - getClass().getClassLoader().getResourceAsStream(resourceName), - GateioWsNotification.class - ); + getClass().getClassLoader().getResourceAsStream(resourceName), GateioWsNotification.class); } - - -} \ No newline at end of file +} diff --git a/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingMarketDataService.java b/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingMarketDataService.java index fc9031744ec..bab9e72aca0 100644 --- a/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingMarketDataService.java +++ b/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingMarketDataService.java @@ -47,5 +47,4 @@ public Observable getOrderBook(CurrencyPair currencyPair, Object... a bids.get(currencyPair), asks.get(currencyPair), maxDepth, currencyPair); }); } - } diff --git a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingAdapters.java b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingAdapters.java index 81ae27fb369..b5d8af2855c 100644 --- a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingAdapters.java +++ b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingAdapters.java @@ -297,4 +297,4 @@ private static Order.OrderType nextNodeAsOrderType(Iterator iterator) } return KrakenAdapters.adaptOrderType(KrakenType.fromString(iterator.next().textValue())); } -} \ No newline at end of file +} diff --git a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingMarketDataService.java b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingMarketDataService.java index 15940657a78..e48b17adeff 100644 --- a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingMarketDataService.java +++ b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingMarketDataService.java @@ -7,17 +7,13 @@ import info.bitrich.xchangestream.kraken.dto.KrakenStreamingOhlc; import info.bitrich.xchangestream.kraken.dto.enums.KrakenSubscriptionName; import io.reactivex.rxjava3.core.Observable; -import java.math.BigDecimal; -import java.util.List; import java.util.TreeSet; -import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang3.ObjectUtils; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.trade.LimitOrder; -import org.knowm.xchange.kraken.dto.marketdata.KrakenOHLC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -94,9 +90,7 @@ public Observable getTrades(CurrencyPair currencyPair, Object... args) { KrakenStreamingAdapters.adaptTrades(currencyPair, arrayNode))); } - - public Observable getOHLC( - CurrencyPair currencyPair, Integer interval) { + public Observable getOHLC(CurrencyPair currencyPair, Integer interval) { String channelName = getChannelName(KrakenSubscriptionName.ohlc, currencyPair); // args[0] is reserved for an optional order boo depth, we'll use args[1] for the interval Object[] args = new Object[2]; @@ -104,10 +98,9 @@ public Observable getOHLC( args[1] = interval; return subscribe(channelName, MIN_DATA_ARRAY_SIZE, args) - .map( arrayNode -> KrakenStreamingAdapters.adaptOhlc(currencyPair, arrayNode)); + .map(arrayNode -> KrakenStreamingAdapters.adaptOhlc(currencyPair, arrayNode)); } - public Observable subscribe(String channelName, int maxItems, Object... args) { return service .subscribeChannel(channelName, args) @@ -131,4 +124,4 @@ public String getChannelName(KrakenSubscriptionName subscriptionName, CurrencyPa String pair = currencyPair.base.toString() + "/" + currencyPair.counter.toString(); return subscriptionName + KRAKEN_CHANNEL_DELIMITER + pair; } -} \ No newline at end of file +} diff --git a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingService.java b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingService.java index bc001a77ec1..d6c2ee1ff15 100644 --- a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingService.java +++ b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingService.java @@ -100,7 +100,6 @@ private static RateLimiter initRateLimiter(KrakenStreamingExchange exchange) { .limitForPeriod(requestsPerSecond) .limitRefreshPeriod(Duration.ofSeconds(1)) .build()); - } return rateLimiter; } @@ -184,7 +183,9 @@ protected void handleMessage(JsonNode message) { break; case error: LOG.error( - "Channel name={}, id={} has been failed: {}", channelName, channelId, + "Channel name={}, id={} has been failed: {}", + channelName, + channelId, statusMessage.getErrorMessage()); if ("ESession:Invalid session".equals(statusMessage.getErrorMessage())) { throw new ExchangeException("Issue with session validity"); @@ -213,7 +214,10 @@ protected void handleMessage(JsonNode message) { } if (!message.isArray() || channelName == null) { - LOG.error("Unknown message: isArray={}, name={}, message={}", message.isArray(), channelName, + LOG.error( + "Unknown message: isArray={}, name={}, message={}", + message.isArray(), + channelName, message); return; } @@ -266,7 +270,9 @@ public String getSubscribeMessage(String channelName, Object... args) throws IOE KrakenSubscriptionMessage subscriptionMessage = new KrakenSubscriptionMessage( - reqID, subscribe, null, + reqID, + subscribe, + null, new KrakenSubscriptionConfig(subscriptionName, null, interval, token)); String subscriptionMessageString = objectMapper.writeValueAsString(subscriptionMessage); @@ -281,8 +287,8 @@ public String getSubscribeMessage(String channelName, Object... args) throws IOE reqID, subscribe, Collections.singletonList(pair), - new KrakenSubscriptionConfig(subscriptionName, parseOrderBookSize(args), interval, - null)); + new KrakenSubscriptionConfig( + subscriptionName, parseOrderBookSize(args), interval, null)); String subscriptionMessageString = objectMapper.writeValueAsString(subscriptionMessage); return subscriptionMessageString; } @@ -315,8 +321,8 @@ public String getUnsubscribeMessage(String channelName, Object... args) throws I reqID, KrakenEventType.unsubscribe, Collections.singletonList(pair), - new KrakenSubscriptionConfig(subscriptionName, parseOrderBookSize(args), interval, - null)); + new KrakenSubscriptionConfig( + subscriptionName, parseOrderBookSize(args), interval, null)); return objectMapper.writeValueAsString(subscriptionMessage); } } @@ -384,4 +390,4 @@ static Integer parseOrderBookSize(Object[] args) { } return null; } -} \ No newline at end of file +} diff --git a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenStreamingOhlc.java b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenStreamingOhlc.java index cafa7a25e6b..f0992b18361 100644 --- a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenStreamingOhlc.java +++ b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenStreamingOhlc.java @@ -7,9 +7,16 @@ public class KrakenStreamingOhlc extends KrakenOHLC { private final long etime; - public KrakenStreamingOhlc(long time, long etime, BigDecimal open, - BigDecimal high, BigDecimal low, BigDecimal close, - BigDecimal vwap, BigDecimal volume, long count) { + public KrakenStreamingOhlc( + long time, + long etime, + BigDecimal open, + BigDecimal high, + BigDecimal low, + BigDecimal close, + BigDecimal vwap, + BigDecimal volume, + long count) { super(time, open, high, low, close, vwap, volume, count); this.etime = etime; } @@ -41,4 +48,4 @@ public String toString() { + this.getCount() + "]"; } -} \ No newline at end of file +} diff --git a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenSubscriptionConfig.java b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenSubscriptionConfig.java index 013e0301388..9d4e2e9a81d 100644 --- a/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenSubscriptionConfig.java +++ b/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/dto/KrakenSubscriptionConfig.java @@ -79,4 +79,4 @@ public Integer getInterval() { public void setInterval(Integer interval) { this.interval = interval; } -} \ No newline at end of file +} diff --git a/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingExchange.java b/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingExchange.java index e0cef1426e3..966fbe6a371 100644 --- a/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingExchange.java +++ b/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingExchange.java @@ -7,9 +7,6 @@ import info.bitrich.xchangestream.util.Events; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; -import org.knowm.xchange.kucoin.KucoinExchange; -import org.knowm.xchange.kucoin.dto.response.WebsocketResponse; - import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; diff --git a/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingService.java b/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingService.java index 347e2ac9bc3..0732cdfa0f4 100644 --- a/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingService.java +++ b/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingService.java @@ -11,7 +11,6 @@ import io.reactivex.rxjava3.core.CompletableSource; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.disposables.Disposable; - import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; diff --git a/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/LgoStreamingMarketDataService.java b/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/LgoStreamingMarketDataService.java index eec3beb0f69..21940e39779 100644 --- a/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/LgoStreamingMarketDataService.java +++ b/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/LgoStreamingMarketDataService.java @@ -41,5 +41,4 @@ public Observable getTrades(CurrencyPair currencyPair, Object... args) { private LgoTradeBatchSubscription createTradeSubscription(CurrencyPair currencyPair) { return LgoTradeBatchSubscription.create(service, currencyPair); } - } diff --git a/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingExchange.java b/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingExchange.java index dee0d964f95..19c3d2c235e 100644 --- a/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingExchange.java +++ b/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingExchange.java @@ -66,7 +66,7 @@ private String getApiUrl() { @Override public Completable disconnect() { - if(streamingService != null) { + if (streamingService != null) { streamingService.pingPongDisconnectIfConnected(); return streamingService.disconnect(); } diff --git a/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingMarketDataService.java b/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingMarketDataService.java index 2697a0f9ce0..a4262197eac 100644 --- a/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingMarketDataService.java +++ b/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingMarketDataService.java @@ -121,18 +121,23 @@ public Observable getOrderBook(Instrument instrument, Object... args) LOG.error(String.format("Failed to get orderBook, instId=%s.", instId)); return Observable.fromIterable(new LinkedList<>()); } - Date timestamp = new Timestamp( - Long.parseLong(okexOrderbooks.get(0).getTs())); - okexOrderbooks.get(0).getAsks().forEach( - okexPublicOrder -> - orderBook.update( - OkexAdapters.adaptLimitOrder( - okexPublicOrder, instrument, Order.OrderType.ASK, timestamp))); - okexOrderbooks.get(0).getBids().forEach( - okexPublicOrder -> - orderBook.update( - OkexAdapters.adaptLimitOrder( - okexPublicOrder, instrument, Order.OrderType.BID, timestamp))); + Date timestamp = new Timestamp(Long.parseLong(okexOrderbooks.get(0).getTs())); + okexOrderbooks + .get(0) + .getAsks() + .forEach( + okexPublicOrder -> + orderBook.update( + OkexAdapters.adaptLimitOrder( + okexPublicOrder, instrument, Order.OrderType.ASK, timestamp))); + okexOrderbooks + .get(0) + .getBids() + .forEach( + okexPublicOrder -> + orderBook.update( + OkexAdapters.adaptLimitOrder( + okexPublicOrder, instrument, Order.OrderType.BID, timestamp))); if (orderBookUpdatesSubscriptions.get(instrument) != null) { orderBookUpdatesSubscriptions( instrument, @@ -151,8 +156,8 @@ public Observable getOrderBook(Instrument instrument, Object... args) } @Override - public Observable> getOrderBookUpdates(Instrument instrument, - Object... args) { + public Observable> getOrderBookUpdates( + Instrument instrument, Object... args) { return orderBookUpdatesSubscriptions.computeIfAbsent(instrument, v -> PublishSubject.create()); } diff --git a/xchange-stream-okex/src/test/java/info/bitrich/xchangestream/okex/OkexStreamingPublicDataIntegration.java b/xchange-stream-okex/src/test/java/info/bitrich/xchangestream/okex/OkexStreamingPublicDataIntegration.java index 6062bfe0827..68594fbae72 100644 --- a/xchange-stream-okex/src/test/java/info/bitrich/xchangestream/okex/OkexStreamingPublicDataIntegration.java +++ b/xchange-stream-okex/src/test/java/info/bitrich/xchangestream/okex/OkexStreamingPublicDataIntegration.java @@ -4,8 +4,8 @@ import info.bitrich.xchangestream.core.StreamingExchange; import info.bitrich.xchangestream.core.StreamingExchangeFactory; -import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.disposables.Disposable; +import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.knowm.xchange.currency.CurrencyPair; diff --git a/xchange-stream-service-netty/src/main/java/info/bitrich/xchangestream/service/netty/NettyStreamingService.java b/xchange-stream-service-netty/src/main/java/info/bitrich/xchangestream/service/netty/NettyStreamingService.java index a6ecbba24f7..8063602a3fc 100644 --- a/xchange-stream-service-netty/src/main/java/info/bitrich/xchangestream/service/netty/NettyStreamingService.java +++ b/xchange-stream-service-netty/src/main/java/info/bitrich/xchangestream/service/netty/NettyStreamingService.java @@ -436,7 +436,8 @@ public Observable subscribeChannel(String channelName, Object... args) { try { sendMessage(getUnsubscribeMessage(subscriptionUniqueId, args)); } catch (IOException e) { - LOG.debug("Failed to unsubscribe channel: {} {}", subscriptionUniqueId, e.toString()); + LOG.debug( + "Failed to unsubscribe channel: {} {}", subscriptionUniqueId, e.toString()); } catch (Exception e) { LOG.warn("Failed to unsubscribe channel: {}", subscriptionUniqueId, e); }