From f55ea913dc61366e3044b5502f29b1cb60ae47fa Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Wed, 8 Jun 2022 15:33:17 -0300 Subject: [PATCH 01/10] getOrder, placeOrder, cancelOrder implementation --- .../blockchain/BlockchainAdapters.java | 117 ++++++++++++++++- .../blockchain/BlockchainAuthenticated.java | 19 +++ .../blockchain/BlockchainConstants.java | 14 ++ .../blockchain/BlockchainExchange.java | 7 +- .../blockchain/dto/trade/BlockchainOrder.java | 59 +++++++++ .../params/BlockchainOrderParams.java | 24 ++++ .../BlockchainCurrencyPairSerializer.java | 17 +++ .../service/BlockchainTradeService.java | 112 ++++++++++++++++ .../service/BlockchainTradeServiceRaw.java | 61 +++++++++ .../service/BlockchainBaseTest.java | 33 +++++ .../service/account/AccountServiceTest.java | 20 --- .../service/trade/TradeServiceTest.java | 122 ++++++++++++++++++ .../service/utils/BlockchainConstants.java | 8 ++ .../resources/__files/accountInformation.json | 20 +++ .../resources/__files/new_order_limit.json | 16 +++ .../resources/__files/new_order_market.json | 16 +++ .../resources/__files/new_order_stop.json | 16 +++ .../src/test/resources/__files/orders.json | 18 +++ 18 files changed, 673 insertions(+), 26 deletions(-) create mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java create mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java create mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/serializer/BlockchainCurrencyPairSerializer.java create mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java create mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java create mode 100644 xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java create mode 100644 xchange-blockchain/src/test/resources/__files/accountInformation.json create mode 100644 xchange-blockchain/src/test/resources/__files/new_order_limit.json create mode 100644 xchange-blockchain/src/test/resources/__files/new_order_market.json create mode 100644 xchange-blockchain/src/test/resources/__files/new_order_stop.json create mode 100644 xchange-blockchain/src/test/resources/__files/orders.json diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index a1e10656f5a..ce9fcb6acb7 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -2,14 +2,26 @@ import lombok.experimental.UtilityClass; import org.knowm.xchange.blockchain.dto.account.*; +import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; +import org.knowm.xchange.blockchain.params.BlockchainOrderParams; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; +import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.account.AddressWithTag; import org.knowm.xchange.dto.account.FundingRecord; +import org.knowm.xchange.dto.trade.LimitOrder; +import org.knowm.xchange.dto.trade.MarketOrder; +import org.knowm.xchange.dto.trade.OpenOrders; +import org.knowm.xchange.dto.trade.StopOrder; +import org.knowm.xchange.instrument.Instrument; -import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; import static org.knowm.xchange.blockchain.BlockchainConstants.*; +import static org.knowm.xchange.blockchain.BlockchainConstants.SELL; @UtilityClass public class BlockchainAdapters { @@ -18,6 +30,13 @@ public static String toSymbol(CurrencyPair currencyPair) { return String.format(CURRENCY_PAIR_SYMBOL_FORMAT, currencyPair.base.getCurrencyCode(), currencyPair.counter.getCurrencyCode()); } + public static CurrencyPair toCurrencyPair(Instrument instrument){ + if(instrument instanceof CurrencyPair) { + return (CurrencyPair) instrument; + } + throw new IllegalArgumentException(String.format("Unsupported instrument '%s'", instrument)); + } + public static AddressWithTag toAddressWithTag(BlockchainDeposit blockchainDeposit){ return new AddressWithTag(blockchainDeposit.getAddress(), null); } @@ -86,4 +105,100 @@ public static CurrencyPair toCurrencyPairBySymbol(BlockchainSymbol blockchainSym Currency counterSymbol = blockchainSymbol.getCounterCurrency(); return new CurrencyPair(baseSymbol, counterSymbol); } + + public static OpenOrders toOpenOrders(List blockchainOrders){ + List limitOrders = new ArrayList<>(Collections.emptyList()); + List hiddenOrders = new ArrayList<>(Collections.emptyList()); + + for(BlockchainOrder blockchainOrder : blockchainOrders) { + final Order.OrderType orderType = blockchainOrder.isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; + final CurrencyPair symbol = blockchainOrder.getSymbol(); + Order.Builder builder; + + if (blockchainOrder.isMarketOrder()) { + builder = new MarketOrder.Builder(orderType, symbol); + } else if (blockchainOrder.isLimitOrder()){ + builder = new LimitOrder.Builder(orderType, symbol).limitPrice(blockchainOrder.getPrice()); + } else { + builder = new StopOrder.Builder(orderType, symbol).stopPrice(blockchainOrder.getPrice()); + } + Order order = builder.orderStatus(toOrderStatus(blockchainOrder.getOrdStatus())) + .originalAmount(blockchainOrder.getCumQty().add(blockchainOrder.getLeavesQty())) + .id(Long.toString(blockchainOrder.getExOrdId())) + .timestamp(blockchainOrder.getTimestamp()) + .averagePrice(blockchainOrder.getAvgPx()) + .build(); + + if (order instanceof LimitOrder) { + limitOrders.add((LimitOrder) order); + } else { + hiddenOrders.add(order); + } + } + + return new OpenOrders(limitOrders, hiddenOrders); + } + + public static Order.OrderStatus toOrderStatus(String status) { + switch (status.toUpperCase()) { + case OPEN: + return Order.OrderStatus.OPEN; + case REJECTED: + return Order.OrderStatus.REJECTED; + case CANCELED: + return Order.OrderStatus.CANCELED; + case FILLED: + return Order.OrderStatus.FILLED; + case PART_FILLED: + return Order.OrderStatus.PARTIALLY_FILLED; + case EXPIRED: + return Order.OrderStatus.EXPIRED; + case PENDING: + return Order.OrderStatus.PENDING_NEW; + default: + return Order.OrderStatus.UNKNOWN; + } + } + + public static BlockchainOrderParams toBlockchainOrder(String orderType, LimitOrder limitOrder, MarketOrder marketOrder, StopOrder stopOrder){ + + switch (orderType){ + case LIMIT: + return BlockchainOrderParams.builder() + .ordType(orderType) + .symbol(toCurrencyPair(limitOrder.getInstrument())) + .side(Order.OrderType.BID.equals(limitOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .orderQty(limitOrder.getOriginalAmount()) + .price(limitOrder.getLimitPrice()) + .clOrdId(generateClOrdId()) + .build(); + case MARKET: + return BlockchainOrderParams.builder() + .ordType(orderType) + .symbol(toCurrencyPair(marketOrder.getInstrument())) + .side(Order.OrderType.BID.equals(marketOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .orderQty(marketOrder.getOriginalAmount()) + .price(marketOrder.getCumulativeAmount()) + .clOrdId(generateClOrdId()) + .build(); + case STOP_ORDER: + return BlockchainOrderParams.builder() + .ordType(orderType) + .symbol(toCurrencyPair(stopOrder.getInstrument())) + .side(Order.OrderType.BID.equals(stopOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .orderQty(stopOrder.getOriginalAmount()) + .price(stopOrder.getStopPrice()) + .clOrdId(generateClOrdId()) + .build(); + default: + return null; + + } + } + + private static String generateClOrdId() { + String uuid = UUID.randomUUID().toString(); + uuid = uuid.substring(0, 16).replace("-", ""); + return uuid; + } } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java index e16dcd8bd6a..d91d122bac7 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java @@ -2,6 +2,8 @@ import org.knowm.xchange.blockchain.dto.BlockchainException; import org.knowm.xchange.blockchain.dto.account.*; +import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; +import org.knowm.xchange.blockchain.params.BlockchainOrderParams; import org.knowm.xchange.blockchain.params.BlockchainWithdrawalParams; import javax.ws.rs.*; @@ -85,4 +87,21 @@ List getWithdrawFunds(@QueryParam("from") Long startTime, @GET List depositHistory(@QueryParam("from") Long startTime, @QueryParam("to") Long endTime); + + @Path("orders") + @GET + List getOrders(); + + @Path("orders") + @POST + @Consumes(MediaType.APPLICATION_JSON) + BlockchainOrder postOrder(BlockchainOrderParams blockchainOrder); + + @Path("orders/{orderId}") + @DELETE + Boolean cancelOrder(@PathParam("orderId") String orderId) throws IOException, BlockchainException; + + @Path("orders") + @DELETE + Boolean cancelAllOrders(@QueryParam("symbol") String symbol) throws IOException, BlockchainException; } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java index 1c79fccdf8f..31b79bc43a1 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java @@ -11,18 +11,32 @@ public class BlockchainConstants { public static final String GET_FEES = "getFees"; public static final String GET_DEPOSIT_HISTORY = "depositHistory"; public static final String GET_WITHDRAWAL_HISTORY = "withdrawHistory"; + public static final String GET_ORDERS = "getOrders"; + public static final String POST_ORDER = "postOrder"; + public static final String CANCEL_ORDER = "cancelOrder"; + public static final String CANCEL_ALL_ORDERS = "cancelAllOrders"; public static final String GET_SYMBOLS = "getSymbols"; public static final String CURRENCY_PAIR_SYMBOL_FORMAT = "%s-%s"; public static final String X_API_TOKEN = "X-API-Token"; public static final String WITHDRAWAL_EXCEPTION = "Invalid WithdrawFundsParams parameter. Only DefaultWithdrawFundsParams is supported."; public static final String EXCEPTION_MESSAGE = "Operation failed without any error message"; public static final String FUNDING_RECORD_TYPE_UNSUPPORTED = "Invalid FundingRecord parameter. Only DefaultWithdrawFundsParams is supported."; + public static final String OPEN = "OPEN"; public static final String REJECTED = "REJECTED"; public static final String REFUNDING = "REFUNDING"; public static final String PENDING = "PENDING"; public static final String FAILED = "FAILED"; public static final String COMPLETED = "COMPLETED"; public static final String UNCONFIRMED = "UNCONFIRMED"; + public static final String CANCELED = "CANCELED"; + public static final String FILLED = "FILLED"; + public static final String PART_FILLED = "PART_FILLED"; + public static final String EXPIRED = "EXPIRED"; public static final String STATUS_INVALID = "Unknown withdraw status: "; public static final String NOT_IMPLEMENTED_YET = "Not implemented yet"; + public static final String MARKET = "MARKET"; + public static final String LIMIT = "LIMIT"; + public static final String STOP_ORDER = "STOP_ORDER"; + public static final String BUY = "buy"; + public static final String SELL = "sell"; } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java index 12369f725ed..1b8fceb8d06 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java @@ -3,6 +3,7 @@ import org.knowm.xchange.BaseExchange; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.blockchain.service.BlockchainAccountService; +import org.knowm.xchange.blockchain.service.BlockchainTradeService; import org.knowm.xchange.client.ExchangeRestProxyBuilder; import org.knowm.xchange.client.ResilienceRegistries; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; @@ -31,6 +32,7 @@ protected void initServices() { ).build(); this.accountService = new BlockchainAccountService(this, this.blockchain, this.getResilienceRegistries()); + this.tradeService = new BlockchainTradeService(this, this.blockchain, this.getResilienceRegistries()); } @Override @@ -61,9 +63,4 @@ public ResilienceRegistries getResilienceRegistries() { public MarketDataService getMarketDataService() { throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); } - - @Override - public TradeService getTradeService() { - throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); - } } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java new file mode 100644 index 00000000000..7475996a2a2 --- /dev/null +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java @@ -0,0 +1,59 @@ +package org.knowm.xchange.blockchain.dto.trade; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; +import org.knowm.xchange.blockchain.serializer.BlockchainCurrencyPairSerializer; +import org.knowm.xchange.currency.CurrencyPair; +import org.knowm.xchange.utils.jackson.CurrencyPairDeserializer; + +import java.math.BigDecimal; +import java.util.Date; + +import static org.knowm.xchange.blockchain.BlockchainConstants.*; +import static org.knowm.xchange.blockchain.BlockchainConstants.BUY; + +@Data +@Builder +@Jacksonized +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BlockchainOrder { + + @JsonSerialize(using = BlockchainCurrencyPairSerializer.class) + @JsonDeserialize(using = CurrencyPairDeserializer.class) + private final CurrencyPair symbol; + private final Long exOrdId; + private final String clOrdId; + private final String ordType; + private final String ordStatus; + private final String side; + private final String text; + private final BigDecimal price; + private final BigDecimal lastShares; + private final BigDecimal lastPx; + private final BigDecimal leavesQty; + private final BigDecimal cumQty; + private final BigDecimal avgPx; + private final Date timestamp; + + @JsonIgnore + public boolean isMarketOrder() { + return MARKET.equals(ordType); + } + + @JsonIgnore + public boolean isLimitOrder() { + return LIMIT.equals(ordType); + } + + @JsonIgnore + public boolean isBuyer() { + return BUY.equals(this.side.toUpperCase()); + } +} diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java new file mode 100644 index 00000000000..766e58dfd4b --- /dev/null +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java @@ -0,0 +1,24 @@ +package org.knowm.xchange.blockchain.params; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; +import org.knowm.xchange.currency.CurrencyPair; + +import java.math.BigDecimal; + +@Data +@Builder +@Jacksonized +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BlockchainOrderParams { + private final String clOrdId; + private final String ordType; + private final CurrencyPair symbol; + private final BigDecimal orderQty; + private final String side; + private final BigDecimal price; +} diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/serializer/BlockchainCurrencyPairSerializer.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/serializer/BlockchainCurrencyPairSerializer.java new file mode 100644 index 00000000000..81ae9a66c41 --- /dev/null +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/serializer/BlockchainCurrencyPairSerializer.java @@ -0,0 +1,17 @@ +package org.knowm.xchange.blockchain.serializer; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import org.knowm.xchange.blockchain.BlockchainAdapters; +import org.knowm.xchange.currency.CurrencyPair; + +import java.io.IOException; + +public class BlockchainCurrencyPairSerializer extends JsonSerializer { + + @Override + public void serialize(CurrencyPair currencyPair, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + jsonGenerator.writeString(BlockchainAdapters.toSymbol(currencyPair)); + } +} diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java new file mode 100644 index 00000000000..d888754cf51 --- /dev/null +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -0,0 +1,112 @@ +package org.knowm.xchange.blockchain.service; + +import org.knowm.xchange.blockchain.BlockchainAdapters; +import org.knowm.xchange.blockchain.BlockchainAuthenticated; +import org.knowm.xchange.blockchain.BlockchainErrorAdapter; +import org.knowm.xchange.blockchain.BlockchainExchange; +import org.knowm.xchange.blockchain.dto.BlockchainException; +import org.knowm.xchange.client.ResilienceRegistries; +import org.knowm.xchange.dto.trade.LimitOrder; +import org.knowm.xchange.dto.trade.MarketOrder; +import org.knowm.xchange.dto.trade.OpenOrders; +import org.knowm.xchange.dto.trade.StopOrder; +import org.knowm.xchange.service.trade.TradeService; +import org.knowm.xchange.service.trade.params.CancelAllOrders; +import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; +import org.knowm.xchange.service.trade.params.CancelOrderByIdParams; +import org.knowm.xchange.service.trade.params.CancelOrderParams; +import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair; +import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Optional; + +import static org.knowm.xchange.blockchain.BlockchainConstants.*; + +public class BlockchainTradeService extends BlockchainTradeServiceRaw implements TradeService { + + public BlockchainTradeService(BlockchainExchange exchange, BlockchainAuthenticated blockchainApi, ResilienceRegistries resilienceRegistries) { + super(exchange, blockchainApi, resilienceRegistries); + } + + @Override + public OpenOrders getOpenOrders() throws IOException { + return getOpenOrders(createOpenOrdersParams()); + } + + @Override + public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { + try { + return BlockchainAdapters.toOpenOrders(this.getOrders()); + } catch (BlockchainException e) { + throw BlockchainErrorAdapter.adapt(e); + } + } + + @Override + public String placeLimitOrder(LimitOrder limitOrder) throws IOException { + Long id = this.postOrder(BlockchainAdapters.toBlockchainOrder(LIMIT, limitOrder, + null, + null)).getExOrdId(); + if (id != null) return Long.toString(id); + return null; + } + + @Override + public String placeMarketOrder(MarketOrder marketOrder) throws IOException { + Long id = this.postOrder(BlockchainAdapters.toBlockchainOrder(MARKET, + null, marketOrder, + null)).getExOrdId(); + if (id != null) return Long.toString(id); + return null; + } + + @Override + public String placeStopOrder(StopOrder stopOrder) throws IOException { + Long id = this.postOrder(BlockchainAdapters.toBlockchainOrder(STOP_ORDER, + null, + null, stopOrder)).getExOrdId(); + if (id != null) return Long.toString(id); + return null; + } + + @Override + public OpenOrdersParams createOpenOrdersParams() { + return new DefaultOpenOrdersParamCurrencyPair(); + } + + @Override + public boolean cancelOrder(String orderId) throws IOException { + return cancelOrderById(orderId); + } + + @Override + public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { + if (orderParams instanceof CancelOrderByCurrencyPair) { + this.cancelAllOrdersBySymbol( + ((CancelOrderByCurrencyPair) orderParams).getCurrencyPair().toString()); + return true; + } else { + if (orderParams instanceof CancelOrderByIdParams) { + return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); + } else { + return false; + } + } + } + + @Override + public Collection cancelAllOrders(CancelAllOrders orderParams) throws IOException { + if (orderParams instanceof CancelOrderByCurrencyPair) { + cancelOrder(orderParams); + Collection cancelIds = Arrays.asList(((CancelOrderByCurrencyPair) orderParams).getCurrencyPair().toString()); + return cancelIds; + }else { + return null; + } + } + + +} diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java new file mode 100644 index 00000000000..d0c9b4c88c2 --- /dev/null +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java @@ -0,0 +1,61 @@ +package org.knowm.xchange.blockchain.service; + +import com.sun.org.apache.xpath.internal.operations.Bool; +import org.knowm.xchange.blockchain.BlockchainAuthenticated; +import org.knowm.xchange.blockchain.BlockchainErrorAdapter; +import org.knowm.xchange.blockchain.BlockchainExchange; +import org.knowm.xchange.blockchain.dto.BlockchainException; +import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; +import org.knowm.xchange.blockchain.params.BlockchainOrderParams; +import org.knowm.xchange.client.ResilienceRegistries; + +import java.io.IOException; +import java.util.List; + +import static org.knowm.xchange.blockchain.BlockchainConstants.*; + +public class BlockchainTradeServiceRaw extends BlockchainBaseService { + + protected BlockchainTradeServiceRaw(BlockchainExchange exchange, BlockchainAuthenticated blockchainApi, ResilienceRegistries resilienceRegistries) { + super(exchange, blockchainApi, resilienceRegistries); + } + + protected List getOrders() throws IOException { + return decorateApiCall(this.blockchainApi::getOrders) + .withRetry(retry(GET_ORDERS)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + } + + protected BlockchainOrder postOrder(BlockchainOrderParams blockchainOrder) throws IOException{ + return decorateApiCall(() -> this.blockchainApi.postOrder(blockchainOrder)) + .withRetry(retry(POST_ORDER)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + } + + protected Boolean cancelOrderById(String orderId) throws IOException, BlockchainException{ + try { + decorateApiCall(() -> this.blockchainApi.cancelOrder(orderId)) + .withRetry(retry(CANCEL_ORDER)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + return true; + }catch (BlockchainException e){ + throw BlockchainErrorAdapter.adapt(e); + } + + } + + protected Boolean cancelAllOrdersBySymbol(String symbol) throws IOException, BlockchainException{ + try { + decorateApiCall(() -> this.blockchainApi.cancelAllOrders(symbol)) + .withRetry(retry(CANCEL_ALL_ORDERS)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + return true; + }catch (BlockchainException e){ + throw BlockchainErrorAdapter.adapt(e); + } + } +} diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java index 87b4c263908..d42391280fb 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java @@ -6,6 +6,9 @@ import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.blockchain.BlockchainExchange; +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; + public class BlockchainBaseTest { @ClassRule @@ -23,4 +26,34 @@ protected static BlockchainExchange createExchange() { exchange.applySpecification(specification); return exchange; } + + protected void stubPost(String fileName, int statusCode, String url) { + stubFor( + post(urlPathEqualTo(url)) + .willReturn( + aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/json") + .withBodyFile(fileName))); + } + + protected void stubGet(String fileName, int statusCode, String url) { + stubFor( + get(urlPathEqualTo(url)) + .willReturn( + aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/json") + .withBodyFile(fileName))); + } + + protected void stubDelete(int statusCode, String url) { + stubFor( + delete(urlPathEqualTo(url)) + .willReturn( + aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/json"))); + //.withBodyFile(fileName))); + } } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java index 5d82ebc73e3..707da638206 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java @@ -166,24 +166,4 @@ private Map tradingFees() throws IOException { return service.getDynamicTradingFees(); } - private void stubPost(String fileName, int statusCode, String url) { - stubFor( - post(urlPathEqualTo(url)) - .willReturn( - aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "application/json") - .withBodyFile(fileName))); - } - - private void stubGet(String fileName, int statusCode, String url) { - stubFor( - get(urlPathEqualTo(url)) - .willReturn( - aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "application/json") - .withBodyFile(fileName))); - } - } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java new file mode 100644 index 00000000000..9c7f6e4ab7c --- /dev/null +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java @@ -0,0 +1,122 @@ +package org.knowm.xchange.blockchain.service.trade; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.knowm.xchange.blockchain.BlockchainExchange; +import org.knowm.xchange.blockchain.service.BlockchainBaseTest; +import org.knowm.xchange.currency.CurrencyPair; +import org.knowm.xchange.dto.Order; +import org.knowm.xchange.dto.trade.LimitOrder; +import org.knowm.xchange.dto.trade.MarketOrder; +import org.knowm.xchange.dto.trade.OpenOrders; +import org.knowm.xchange.dto.trade.StopOrder; +import org.knowm.xchange.service.trade.TradeService; +import si.mazi.rescu.HttpStatusIOException; + +import java.io.IOException; +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.knowm.xchange.blockchain.service.utils.BlockchainConstants.*; + +public class TradeServiceTest extends BlockchainBaseTest { + private TradeService service; + + @Before + public void init() { + BlockchainExchange exchange = createExchange(); + service = exchange.getTradeService(); + } + + @Test(timeout = 2000) + public void getOpenOrdersSuccess() throws Exception { + OpenOrders response = getOpenOrders(); + System.out.println(response); + Assert.assertNotNull(response); + } + + @Test(timeout = 2000) + public void placeLimitOrderSuccess() throws Exception { + String response = placeLimitOrder(); + System.out.println(response); + Assert.assertNotNull(response); + } + + @Test(timeout = 2000) + public void placeMarketOrderSuccess() throws Exception { + String response = placeMarketOrder(); + System.out.println(response); + Assert.assertNotNull(response); + } + + @Test(timeout = 2000) + public void placeStopOrderSuccess() throws Exception { + String response = placeStopOrder(); + System.out.println(response); + Assert.assertNotNull(response); + } + + @Test(timeout = 2000) + public void cancelOrderSuccess() throws Exception { + Boolean response = cancelOrder(200, ORDER_ID); + assertThat(response).isEqualTo(true); + } + + @Test(timeout = 2000) + public void cancelOrderFailure() throws Exception { + Throwable exception = catchThrowable(() -> cancelOrder(400, ORDER_ID)); + assertThat(exception) + .isInstanceOf(HttpStatusIOException.class) + .hasMessage(HTTP_CODE_400); + } + + private OpenOrders getOpenOrders() throws IOException { + stubGet(ORDERS_JSON, 200, URL_ORDERS); + + return service.getOpenOrders(); + } + + private String placeLimitOrder() throws IOException { + stubPost(NEW_ORDER_LIMIT_JSON, 200, URL_ORDERS); + + LimitOrder limitOrder = + new LimitOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_USDT) + .originalAmount(new BigDecimal("45.0")) + .limitPrice(new BigDecimal("0.23")) + .build(); + + return service.placeLimitOrder(limitOrder); + } + + private String placeMarketOrder() throws IOException { + stubPost(NEW_ORDER_MARKET_JSON, 200, URL_ORDERS); + + MarketOrder marketOrder = + new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_USDT) + .originalAmount(new BigDecimal("15.0")) + .cumulativeAmount(new BigDecimal("0.22")) + .build(); + + return service.placeMarketOrder(marketOrder); + } + + private String placeStopOrder() throws IOException { + stubPost(NEW_ORDER_STOP_JSON, 200, URL_ORDERS); + + StopOrder stopOrder = + new StopOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_USDT) + .originalAmount(new BigDecimal("67.0")) + .stopPrice(new BigDecimal("0.21")) + .build(); + + return service.placeStopOrder(stopOrder); + } + + private Boolean cancelOrder(int statusCode, String orderId) throws IOException { + stubDelete(statusCode, URL_ORDERS_DELETE); + + return service.cancelOrder(orderId); + } +} diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java index 7923975583b..be20016bcec 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java @@ -10,12 +10,19 @@ public class BlockchainConstants { public static final String URL_SYMBOLS = "/v3/exchange/symbols"; public static final String URL_DEPOSIT_BY_CURRENCY = "/v3/exchange/deposits/BTC"; public static final String URL_WITHDRAWALS = "/v3/exchange/withdrawals"; + public static final String URL_ORDERS = "/v3/exchange/orders"; + public static final String URL_ORDERS_DELETE = "/v3/exchange/orders/11111111"; public static final String WITHDRAWAL_ID = "3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ"; public static final String STATUS_CODE_401 = "Unauthorized (HTTP status code: 401)"; public static final String STATUS_CODE_400 = "Bad Request (HTTP status code: 400)"; + public static final String HTTP_CODE_400 = "HTTP status code was not OK: 400"; public static final String ADDRESS = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"; public static final String ADDRESS_DEPOSIT = "3CrbF4Z45fnJs62jFs1p3LkR8KiZSGKJFL"; public static final String ACCOUNT_INFORMATION_JSON = "accountInformation.json"; + public static final String ORDERS_JSON = "orders.json"; + public static final String NEW_ORDER_MARKET_JSON = "new_order_market.json"; + public static final String NEW_ORDER_LIMIT_JSON = "new_order_limit.json"; + public static final String NEW_ORDER_STOP_JSON = "new_order_stop.json"; public static final String DEPOSIT_SUCCESS_JSON = "deposit-success.json"; public static final String WITHDRAWAL_SUCCESS_JSON = "withdraw-success.json"; public static final String WITHDRAWAL_FAILURE_JSON = "withdraw-failure.json"; @@ -26,4 +33,5 @@ public class BlockchainConstants { public static final String DEPOSIT_FAILURE_JSON = "deposit-failure.json"; public static final String NOT_IMPLEMENTED_YET = "Not implemented yet"; public static final String BENEFICIARY = "ea1f34b3-e77a-4646-9cfa-5d6d3518c6d3"; + public static final String ORDER_ID = "11111111"; } diff --git a/xchange-blockchain/src/test/resources/__files/accountInformation.json b/xchange-blockchain/src/test/resources/__files/accountInformation.json new file mode 100644 index 00000000000..6c7cb704de9 --- /dev/null +++ b/xchange-blockchain/src/test/resources/__files/accountInformation.json @@ -0,0 +1,20 @@ +{ + "primary": [ + { + "currency": "BTC", + "balance": 0.0, + "available": 0.0, + "balance_local": 0.0, + "available_local": 0.0, + "rate": 29340.1 + }, + { + "currency": "USDT", + "balance": 200.0, + "available": 200.0, + "balance_local": 199.804, + "available_local": 199.804, + "rate": 0.99902 + } + ] +} \ No newline at end of file diff --git a/xchange-blockchain/src/test/resources/__files/new_order_limit.json b/xchange-blockchain/src/test/resources/__files/new_order_limit.json new file mode 100644 index 00000000000..4d5b33a1fb9 --- /dev/null +++ b/xchange-blockchain/src/test/resources/__files/new_order_limit.json @@ -0,0 +1,16 @@ +{ + "exOrdId": 11111111, + "clOrdId": "ABC", + "ordType": "LIMIT", + "ordStatus": "FILLED", + "side": "BUY", + "price": 0.12345, + "text": "string", + "symbol": "BTC-USD", + "lastShares": 0.5678, + "lastPx": 3500.12, + "leavesQty": 10, + "cumQty": 0.123345, + "avgPx": 345.33, + "timestamp": 1592830770594 +} \ No newline at end of file diff --git a/xchange-blockchain/src/test/resources/__files/new_order_market.json b/xchange-blockchain/src/test/resources/__files/new_order_market.json new file mode 100644 index 00000000000..33677fae2f8 --- /dev/null +++ b/xchange-blockchain/src/test/resources/__files/new_order_market.json @@ -0,0 +1,16 @@ +{ + "exOrdId": 22222222, + "clOrdId": "ABC", + "ordType": "MARKET", + "ordStatus": "FILLED", + "side": "BUY", + "price": 0.12345, + "text": "string", + "symbol": "BTC-USD", + "lastShares": 0.5678, + "lastPx": 3500.12, + "leavesQty": 10, + "cumQty": 0.123345, + "avgPx": 345.33, + "timestamp": 1592830770594 +} \ No newline at end of file diff --git a/xchange-blockchain/src/test/resources/__files/new_order_stop.json b/xchange-blockchain/src/test/resources/__files/new_order_stop.json new file mode 100644 index 00000000000..911b6514878 --- /dev/null +++ b/xchange-blockchain/src/test/resources/__files/new_order_stop.json @@ -0,0 +1,16 @@ +{ + "exOrdId": 33333333, + "clOrdId": "ABC", + "ordType": "STOP", + "ordStatus": "FILLED", + "side": "BUY", + "price": 0.12345, + "text": "string", + "symbol": "BTC-USD", + "lastShares": 0.5678, + "lastPx": 3500.12, + "leavesQty": 10, + "cumQty": 0.123345, + "avgPx": 345.33, + "timestamp": 1592830770594 +} \ No newline at end of file diff --git a/xchange-blockchain/src/test/resources/__files/orders.json b/xchange-blockchain/src/test/resources/__files/orders.json new file mode 100644 index 00000000000..e86d131e0d0 --- /dev/null +++ b/xchange-blockchain/src/test/resources/__files/orders.json @@ -0,0 +1,18 @@ +[ + { + "exOrdId": 11111111, + "clOrdId": "ABC", + "ordType": "MARKET", + "ordStatus": "FILLED", + "side": "BUY", + "price": 0.12345, + "text": "string", + "symbol": "BTC-USD", + "lastShares": 0.5678, + "lastPx": 3500.12, + "leavesQty": 10, + "cumQty": 0.123345, + "avgPx": 345.33, + "timestamp": 1592830770594 + } +] \ No newline at end of file From 3cf5759056af6b93c362df675a332b967eb818b0 Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Tue, 14 Jun 2022 09:23:12 -0300 Subject: [PATCH 02/10] tradeService review 1 --- .../blockchain/BlockchainAdapters.java | 161 +++++++++++++----- .../blockchain/BlockchainAuthenticated.java | 71 +++++++- .../blockchain/BlockchainConstants.java | 3 + .../blockchain/dto/trade/BlockchainOrder.java | 1 + .../params/BlockchainOrderParams.java | 24 --- .../params/BlockchainTradeHistoryParams.java | 26 +++ .../service/BlockchainTradeService.java | 137 +++++++++++---- .../service/BlockchainTradeServiceRaw.java | 18 +- .../service/BlockchainBaseTest.java | 1 - .../service/trade/TradeServiceTest.java | 58 +++++-- .../service/utils/BlockchainConstants.java | 5 +- .../blockchain/trade/BlockchainTradeDemo.java | 109 ++++++++++++ 12 files changed, 488 insertions(+), 126 deletions(-) delete mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java create mode 100644 xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainTradeHistoryParams.java create mode 100644 xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index ce9fcb6acb7..50db6696169 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -1,27 +1,29 @@ package org.knowm.xchange.blockchain; import lombok.experimental.UtilityClass; -import org.knowm.xchange.blockchain.dto.account.*; +import org.knowm.xchange.blockchain.dto.account.BlockchainDeposit; +import org.knowm.xchange.blockchain.dto.account.BlockchainDeposits; +import org.knowm.xchange.blockchain.dto.account.BlockchainSymbol; +import org.knowm.xchange.blockchain.dto.account.BlockchainWithdrawal; import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; -import org.knowm.xchange.blockchain.params.BlockchainOrderParams; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.account.AddressWithTag; import org.knowm.xchange.dto.account.FundingRecord; -import org.knowm.xchange.dto.trade.LimitOrder; -import org.knowm.xchange.dto.trade.MarketOrder; -import org.knowm.xchange.dto.trade.OpenOrders; -import org.knowm.xchange.dto.trade.StopOrder; +import org.knowm.xchange.dto.marketdata.Trades; +import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.instrument.Instrument; +import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; +import org.knowm.xchange.service.trade.params.CancelOrderParams; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; +import java.util.stream.Collectors; import static org.knowm.xchange.blockchain.BlockchainConstants.*; -import static org.knowm.xchange.blockchain.BlockchainConstants.SELL; @UtilityClass public class BlockchainAdapters { @@ -30,6 +32,15 @@ public static String toSymbol(CurrencyPair currencyPair) { return String.format(CURRENCY_PAIR_SYMBOL_FORMAT, currencyPair.base.getCurrencyCode(), currencyPair.counter.getCurrencyCode()); } + public static String toSymbol(CancelOrderParams currencyPair) { + if (currencyPair instanceof CancelOrderByCurrencyPair) { + return String.format(CURRENCY_PAIR_SYMBOL_FORMAT, + ((CancelOrderByCurrencyPair) currencyPair).getCurrencyPair().base, + ((CancelOrderByCurrencyPair) currencyPair).getCurrencyPair().counter); + } + throw new IllegalArgumentException(String.format("Unsupported currency pair '%s'", currencyPair)); + } + public static CurrencyPair toCurrencyPair(Instrument instrument){ if(instrument instanceof CurrencyPair) { return (CurrencyPair) instrument; @@ -139,6 +150,29 @@ public static OpenOrders toOpenOrders(List blockchainOrders){ return new OpenOrders(limitOrders, hiddenOrders); } + public static Order toOpenOrdersById(BlockchainOrder blockchainOrder){ + Order.OrderType orderType = blockchainOrder.isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; + CurrencyPair symbol = blockchainOrder.getSymbol(); + Order.Builder builder; + + if (blockchainOrder.isMarketOrder()) { + builder = new MarketOrder.Builder(orderType, symbol); + } else if (blockchainOrder.isLimitOrder()){ + builder = new LimitOrder.Builder(orderType, symbol).limitPrice(blockchainOrder.getPrice()); + } else { + builder = new StopOrder.Builder(orderType, symbol).stopPrice(blockchainOrder.getPrice()); + } + + return builder.originalAmount(blockchainOrder.getCumQty().add(blockchainOrder.getLeavesQty())) + .id(Long.toString(blockchainOrder.getExOrdId())) + .timestamp(blockchainOrder.getTimestamp()) + .averagePrice(blockchainOrder.getAvgPx()) + .cumulativeAmount(blockchainOrder.getCumQty()) + .orderStatus(toOrderStatus(blockchainOrder.getOrdStatus())) + .userReference(blockchainOrder.getClOrdId()) + .build(); + } + public static Order.OrderStatus toOrderStatus(String status) { switch (status.toUpperCase()) { case OPEN: @@ -160,40 +194,37 @@ public static Order.OrderStatus toOrderStatus(String status) { } } - public static BlockchainOrderParams toBlockchainOrder(String orderType, LimitOrder limitOrder, MarketOrder marketOrder, StopOrder stopOrder){ - - switch (orderType){ - case LIMIT: - return BlockchainOrderParams.builder() - .ordType(orderType) - .symbol(toCurrencyPair(limitOrder.getInstrument())) - .side(Order.OrderType.BID.equals(limitOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) - .orderQty(limitOrder.getOriginalAmount()) - .price(limitOrder.getLimitPrice()) - .clOrdId(generateClOrdId()) - .build(); - case MARKET: - return BlockchainOrderParams.builder() - .ordType(orderType) - .symbol(toCurrencyPair(marketOrder.getInstrument())) - .side(Order.OrderType.BID.equals(marketOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) - .orderQty(marketOrder.getOriginalAmount()) - .price(marketOrder.getCumulativeAmount()) - .clOrdId(generateClOrdId()) - .build(); - case STOP_ORDER: - return BlockchainOrderParams.builder() - .ordType(orderType) - .symbol(toCurrencyPair(stopOrder.getInstrument())) - .side(Order.OrderType.BID.equals(stopOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) - .orderQty(stopOrder.getOriginalAmount()) - .price(stopOrder.getStopPrice()) - .clOrdId(generateClOrdId()) - .build(); - default: - return null; + public static BlockchainOrder toBlockchainLimitOrder(LimitOrder limitOrder){ + return BlockchainOrder.builder() + .ordType(limitOrder.getType().toString()) + .symbol(toCurrencyPair(limitOrder.getInstrument())) + .side(Order.OrderType.BID.equals(limitOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .orderQty(limitOrder.getOriginalAmount()) + .price(limitOrder.getLimitPrice()) + .clOrdId(generateClOrdId()) + .build(); + } - } + public static BlockchainOrder toBlockchainMarketOrder(MarketOrder marketOrder){ + return BlockchainOrder.builder() + .ordType(marketOrder.getType().toString()) + .symbol(toCurrencyPair(marketOrder.getInstrument())) + .side(Order.OrderType.BID.equals(marketOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .orderQty(marketOrder.getOriginalAmount()) + .price(marketOrder.getCumulativeAmount()) + .clOrdId(generateClOrdId()) + .build(); + } + + public static BlockchainOrder toBlockchainStopOrder(StopOrder stopOrder){ + return BlockchainOrder.builder() + .ordType(stopOrder.getType().toString()) + .symbol(toCurrencyPair(stopOrder.getInstrument())) + .side(Order.OrderType.BID.equals(stopOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .orderQty(stopOrder.getOriginalAmount()) + .price(stopOrder.getStopPrice()) + .clOrdId(generateClOrdId()) + .build(); } private static String generateClOrdId() { @@ -201,4 +232,54 @@ private static String generateClOrdId() { uuid = uuid.substring(0, 16).replace("-", ""); return uuid; } + + public static UserTrades toUserTrades(List blockchainTrades) { + List trades = blockchainTrades.stream() + .map(blockchainTrade -> new UserTrade.Builder() + .type(blockchainTrade.isBuyer()? Order.OrderType.BID : Order.OrderType.ASK) + .originalAmount(blockchainTrade.getCumQty()) + .currencyPair(blockchainTrade.getSymbol()) + .price(blockchainTrade.getPrice()) + .timestamp(blockchainTrade.getTimestamp()) + .id(Long.toString(blockchainTrade.getExOrdId())) + .orderId(blockchainTrade.getClOrdId()) + .build() + ).collect(Collectors.toList()); + Long lastId = blockchainTrades.stream().map(BlockchainOrder::getExOrdId).max(Long::compareTo).orElse(0L); + return new UserTrades(trades, lastId, Trades.TradeSortType.SortByTimestamp); + } + + /*public static ExchangeMetaData adaptMetaData( + List currencyPairs, ExchangeMetaData metaData) { + + Map pairsMap = metaData.getCurrencyPairs(); + Map currenciesMap = metaData.getCurrencies(); + + pairsMap.keySet().retainAll(currencyPairs); + + Set currencies = + currencyPairs.stream() + .flatMap(pair -> Stream.of(pair.base, pair.counter)) + .collect(Collectors.toSet()); + currenciesMap.keySet().retainAll(currencies); + + for (CurrencyPair c : currencyPairs) { + if (!pairsMap.containsKey(c)) { + pairsMap.put(c, null); + } + + if (!currenciesMap.containsKey(c.base)) { + currenciesMap.put( + c.base, + new CurrencyMetaData( + 2, + null)); + } + if (!currenciesMap.containsKey(c.counter)) { + currenciesMap.put(c.counter, new CurrencyMetaData(2, null)); + } + } + + return metaData; + }*/ } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java index d91d122bac7..bbeb2c05b1e 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java @@ -3,7 +3,6 @@ import org.knowm.xchange.blockchain.dto.BlockchainException; import org.knowm.xchange.blockchain.dto.account.*; import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; -import org.knowm.xchange.blockchain.params.BlockchainOrderParams; import org.knowm.xchange.blockchain.params.BlockchainWithdrawalParams; import javax.ws.rs.*; @@ -88,20 +87,76 @@ List getWithdrawFunds(@QueryParam("from") Long startTime, List depositHistory(@QueryParam("from") Long startTime, @QueryParam("to") Long endTime); - @Path("orders") + /** + * Get a list orders + * + * @return live and historic orders, defaulting to live orders. Returns at most 100 results, use timestamp to + * paginate for further results + */ + @Path("/orders") @GET List getOrders(); - @Path("orders") + /** + * Get a specific order + * + * @param orderId + * @return the order according to the orderId, 404 if not found + */ + @Path("/orders/{orderId}") + @GET + BlockchainOrder getOrder(@PathParam("orderId") String orderId); + + /** + * Add an order + * + * @param blockchainOrder + * @return a new order according to the provided parameters + */ + @Path("/orders") @POST @Consumes(MediaType.APPLICATION_JSON) - BlockchainOrder postOrder(BlockchainOrderParams blockchainOrder); + BlockchainOrder postOrder(BlockchainOrder blockchainOrder); - @Path("orders/{orderId}") + /** + * Delete a specific order + * + * @param orderId + * @return status 200 if it was successfully removed or 400 if there was an error + * @throws IOException + * @throws BlockchainException + */ + @Path("/orders/{orderId}") @DELETE - Boolean cancelOrder(@PathParam("orderId") String orderId) throws IOException, BlockchainException; + Void cancelOrder(@PathParam("orderId") String orderId) throws IOException, BlockchainException; - @Path("orders") + /** + * Delete all open orders (of a symbol, if specified) + * + * @param symbol + * @return status 200 if it was successfully removed or 400 if there was an error + * @throws IOException + * @throws BlockchainException + */ + @Path("/orders") @DELETE - Boolean cancelAllOrders(@QueryParam("symbol") String symbol) throws IOException, BlockchainException; + Void cancelAllOrders(@QueryParam("symbol") String symbol) throws IOException, BlockchainException; + + /** + * Get a list of filled orders + * + * @param symbol + * @param startTime + * @param endTime + * @param limit + * @return filled orders, including partial fills. Returns at most 100 results, use timestamp to paginate for + * further results + */ + @Path("/trades") + @GET + List getTrades(@QueryParam("symbol") String symbol, + @QueryParam("from") Long startTime, + @QueryParam("to") Long endTime, + @QueryParam("limit") Integer limit); + } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java index 31b79bc43a1..d2dad904af6 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java @@ -12,15 +12,18 @@ public class BlockchainConstants { public static final String GET_DEPOSIT_HISTORY = "depositHistory"; public static final String GET_WITHDRAWAL_HISTORY = "withdrawHistory"; public static final String GET_ORDERS = "getOrders"; + public static final String GET_ORDER = "getOrder"; public static final String POST_ORDER = "postOrder"; public static final String CANCEL_ORDER = "cancelOrder"; public static final String CANCEL_ALL_ORDERS = "cancelAllOrders"; public static final String GET_SYMBOLS = "getSymbols"; + public static final String GET_TRADES = "getTrades"; public static final String CURRENCY_PAIR_SYMBOL_FORMAT = "%s-%s"; public static final String X_API_TOKEN = "X-API-Token"; public static final String WITHDRAWAL_EXCEPTION = "Invalid WithdrawFundsParams parameter. Only DefaultWithdrawFundsParams is supported."; public static final String EXCEPTION_MESSAGE = "Operation failed without any error message"; public static final String FUNDING_RECORD_TYPE_UNSUPPORTED = "Invalid FundingRecord parameter. Only DefaultWithdrawFundsParams is supported."; + public static final String CURRENCY_PAIR_EXCEPTION = "You need to provide the currency pair."; public static final String OPEN = "OPEN"; public static final String REJECTED = "REJECTED"; public static final String REFUNDING = "REFUNDING"; diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java index 7475996a2a2..4e2f85bbb1d 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java @@ -32,6 +32,7 @@ public class BlockchainOrder { private final String clOrdId; private final String ordType; private final String ordStatus; + private final BigDecimal orderQty; private final String side; private final String text; private final BigDecimal price; diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java deleted file mode 100644 index 766e58dfd4b..00000000000 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainOrderParams.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.knowm.xchange.blockchain.params; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import lombok.Builder; -import lombok.Data; -import lombok.extern.jackson.Jacksonized; -import org.knowm.xchange.currency.CurrencyPair; - -import java.math.BigDecimal; - -@Data -@Builder -@Jacksonized -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonInclude(JsonInclude.Include.NON_NULL) -public class BlockchainOrderParams { - private final String clOrdId; - private final String ordType; - private final CurrencyPair symbol; - private final BigDecimal orderQty; - private final String side; - private final BigDecimal price; -} diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainTradeHistoryParams.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainTradeHistoryParams.java new file mode 100644 index 00000000000..af07b9cad1a --- /dev/null +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/params/BlockchainTradeHistoryParams.java @@ -0,0 +1,26 @@ +package org.knowm.xchange.blockchain.params; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; +import org.knowm.xchange.currency.CurrencyPair; +import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; +import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit; +import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; +import java.util.Date; + +@Data +@Builder +@Jacksonized +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BlockchainTradeHistoryParams + implements TradeHistoryParamCurrencyPair, TradeHistoryParamLimit, TradeHistoryParamsTimeSpan { + + private CurrencyPair currencyPair; + private Integer limit; + private Date startTime; + private Date endTime; +} diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java index d888754cf51..cd7daf944fd 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -5,25 +5,25 @@ import org.knowm.xchange.blockchain.BlockchainErrorAdapter; import org.knowm.xchange.blockchain.BlockchainExchange; import org.knowm.xchange.blockchain.dto.BlockchainException; +import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; +import org.knowm.xchange.blockchain.params.BlockchainTradeHistoryParams; import org.knowm.xchange.client.ResilienceRegistries; -import org.knowm.xchange.dto.trade.LimitOrder; -import org.knowm.xchange.dto.trade.MarketOrder; -import org.knowm.xchange.dto.trade.OpenOrders; -import org.knowm.xchange.dto.trade.StopOrder; +import org.knowm.xchange.dto.Order; +import org.knowm.xchange.dto.account.OpenPositions; +import org.knowm.xchange.dto.trade.*; +import org.knowm.xchange.exceptions.ExchangeException; +import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.service.trade.TradeService; -import org.knowm.xchange.service.trade.params.CancelAllOrders; -import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; -import org.knowm.xchange.service.trade.params.CancelOrderByIdParams; -import org.knowm.xchange.service.trade.params.CancelOrderParams; -import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair; -import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; +import org.knowm.xchange.service.trade.params.*; +import org.knowm.xchange.service.trade.params.orders.*; import java.io.IOException; -import java.util.Arrays; +import java.util.ArrayList; import java.util.Collection; -import java.util.Optional; +import java.util.List; -import static org.knowm.xchange.blockchain.BlockchainConstants.*; +import static org.knowm.xchange.blockchain.BlockchainConstants.CURRENCY_PAIR_EXCEPTION; +import static org.knowm.xchange.blockchain.BlockchainConstants.NOT_IMPLEMENTED_YET; public class BlockchainTradeService extends BlockchainTradeServiceRaw implements TradeService { @@ -47,27 +47,21 @@ public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { - Long id = this.postOrder(BlockchainAdapters.toBlockchainOrder(LIMIT, limitOrder, - null, - null)).getExOrdId(); + Long id = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)).getExOrdId(); if (id != null) return Long.toString(id); return null; } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { - Long id = this.postOrder(BlockchainAdapters.toBlockchainOrder(MARKET, - null, marketOrder, - null)).getExOrdId(); + Long id = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)).getExOrdId(); if (id != null) return Long.toString(id); return null; } @Override public String placeStopOrder(StopOrder stopOrder) throws IOException { - Long id = this.postOrder(BlockchainAdapters.toBlockchainOrder(STOP_ORDER, - null, - null, stopOrder)).getExOrdId(); + Long id = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)).getExOrdId(); if (id != null) return Long.toString(id); return null; } @@ -85,26 +79,97 @@ public boolean cancelOrder(String orderId) throws IOException { @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByCurrencyPair) { - this.cancelAllOrdersBySymbol( - ((CancelOrderByCurrencyPair) orderParams).getCurrencyPair().toString()); + this.cancelAllOrdersBySymbol(BlockchainAdapters.toSymbol(orderParams)); return true; - } else { - if (orderParams instanceof CancelOrderByIdParams) { - return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); - } else { - return false; + } + + if (orderParams instanceof CancelOrderByIdParams) { + return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); + } + + return false; + } + + @Override + public Class[] getRequiredCancelOrderParamClasses() { + return new Class[]{CancelOrderByIdParams.class, CancelOrderByCurrencyPair.class}; + } + + @Override + public OpenPositions getOpenPositions() throws IOException { + throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); + } + + @Override + public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { + try { + Long startTime = null; + Long endTime = null; + Integer limit = null; + + if (!(params instanceof TradeHistoryParamCurrencyPair)) { + throw new ExchangeException(CURRENCY_PAIR_EXCEPTION); + } + + String symbol = BlockchainAdapters.toSymbol( + ((TradeHistoryParamCurrencyPair) params).getCurrencyPair()); + + if (symbol == null) { + throw new ExchangeException(CURRENCY_PAIR_EXCEPTION); } + + if (params instanceof TradeHistoryParamsTimeSpan) { + if (((TradeHistoryParamsTimeSpan) params).getStartTime() != null) { + startTime = ((TradeHistoryParamsTimeSpan) params).getStartTime().getTime(); + } + if (((TradeHistoryParamsTimeSpan) params).getEndTime() != null) { + endTime = ((TradeHistoryParamsTimeSpan) params).getEndTime().getTime(); + } + } + + if (params instanceof TradeHistoryParamLimit) { + TradeHistoryParamLimit limitParams = (TradeHistoryParamLimit) params; + limit = limitParams.getLimit(); + } + + List tradesOrders = this.getTrades(symbol, startTime, endTime, limit); + return BlockchainAdapters.toUserTrades(tradesOrders); + } catch (BlockchainException e) { + throw BlockchainErrorAdapter.adapt(e); } } @Override - public Collection cancelAllOrders(CancelAllOrders orderParams) throws IOException { - if (orderParams instanceof CancelOrderByCurrencyPair) { - cancelOrder(orderParams); - Collection cancelIds = Arrays.asList(((CancelOrderByCurrencyPair) orderParams).getCurrencyPair().toString()); - return cancelIds; - }else { - return null; + public TradeHistoryParams createTradeHistoryParams() { + return BlockchainTradeHistoryParams.builder().build(); + } + + @Override + public Class getRequiredOrderQueryParamClass() { + return OrderQueryParamCurrencyPair.class; + } + + @Override + public Collection getOrder(String... orderIds) throws IOException { + List openOrders = new ArrayList<>(); + + for (String orderId : orderIds) { + openOrders.addAll(getOrder(new DefaultQueryOrderParam(orderId))); + } + return openOrders; + } + + @Override + public Collection getOrder(OrderQueryParams... params) throws IOException { + try { + Collection orders = new ArrayList<>(); + for (OrderQueryParams param : params) { + BlockchainOrder order = this.getOrder(param.getOrderId()); + orders.add(BlockchainAdapters.toOpenOrdersById(order)); + } + return orders; + } catch (BlockchainException e) { + throw BlockchainErrorAdapter.adapt(e); } } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java index d0c9b4c88c2..3ce4ba8bd9a 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java @@ -1,12 +1,10 @@ package org.knowm.xchange.blockchain.service; -import com.sun.org.apache.xpath.internal.operations.Bool; import org.knowm.xchange.blockchain.BlockchainAuthenticated; import org.knowm.xchange.blockchain.BlockchainErrorAdapter; import org.knowm.xchange.blockchain.BlockchainExchange; import org.knowm.xchange.blockchain.dto.BlockchainException; import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; -import org.knowm.xchange.blockchain.params.BlockchainOrderParams; import org.knowm.xchange.client.ResilienceRegistries; import java.io.IOException; @@ -27,7 +25,14 @@ protected List getOrders() throws IOException { .call(); } - protected BlockchainOrder postOrder(BlockchainOrderParams blockchainOrder) throws IOException{ + protected BlockchainOrder getOrder(String orderId) throws IOException { + return decorateApiCall(() -> this.blockchainApi.getOrder(orderId)) + .withRetry(retry(GET_ORDER)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + } + + protected BlockchainOrder postOrder(BlockchainOrder blockchainOrder) throws IOException{ return decorateApiCall(() -> this.blockchainApi.postOrder(blockchainOrder)) .withRetry(retry(POST_ORDER)) .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) @@ -58,4 +63,11 @@ protected Boolean cancelAllOrdersBySymbol(String symbol) throws IOException, Blo throw BlockchainErrorAdapter.adapt(e); } } + + protected List getTrades(String symbol, Long startTime, Long endTime, Integer limit) throws IOException { + return decorateApiCall(() -> this.blockchainApi.getTrades(symbol, startTime, endTime, limit)) + .withRetry(retry(GET_TRADES)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + } } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java index d42391280fb..d3857c9a7c9 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java @@ -54,6 +54,5 @@ protected void stubDelete(int statusCode, String url) { aResponse() .withStatus(statusCode) .withHeader("Content-Type", "application/json"))); - //.withBodyFile(fileName))); } } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java index 9c7f6e4ab7c..8082f43936c 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java @@ -7,15 +7,18 @@ import org.knowm.xchange.blockchain.service.BlockchainBaseTest; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; -import org.knowm.xchange.dto.trade.LimitOrder; -import org.knowm.xchange.dto.trade.MarketOrder; -import org.knowm.xchange.dto.trade.OpenOrders; -import org.knowm.xchange.dto.trade.StopOrder; +import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.service.trade.TradeService; +import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; +import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; +import org.knowm.xchange.service.trade.params.TradeHistoryParams; +import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import si.mazi.rescu.HttpStatusIOException; import java.io.IOException; import java.math.BigDecimal; +import java.util.Collection; +import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; @@ -32,29 +35,26 @@ public void init() { @Test(timeout = 2000) public void getOpenOrdersSuccess() throws Exception { - OpenOrders response = getOpenOrders(); - System.out.println(response); + stubGet(ORDERS_JSON, 200, URL_ORDERS); + OpenOrders response = service.getOpenOrders(); Assert.assertNotNull(response); } @Test(timeout = 2000) public void placeLimitOrderSuccess() throws Exception { String response = placeLimitOrder(); - System.out.println(response); Assert.assertNotNull(response); } @Test(timeout = 2000) public void placeMarketOrderSuccess() throws Exception { String response = placeMarketOrder(); - System.out.println(response); Assert.assertNotNull(response); } @Test(timeout = 2000) public void placeStopOrderSuccess() throws Exception { String response = placeStopOrder(); - System.out.println(response); Assert.assertNotNull(response); } @@ -72,10 +72,36 @@ public void cancelOrderFailure() throws Exception { .hasMessage(HTTP_CODE_400); } - private OpenOrders getOpenOrders() throws IOException { - stubGet(ORDERS_JSON, 200, URL_ORDERS); + @Test(timeout = 2000) + public void cancelOrderByCurrency() throws Exception { + CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair("BTC/USD"); + Boolean response = cancelAllOrder(200, cancelOrderByCurrencyPair); + assertThat(response).isEqualTo(true); + } + + @Test(timeout = 2000) + public void getTrades() throws Exception { + TradeHistoryParams params = service.createTradeHistoryParams(); + if (params instanceof TradeHistoryParamsTimeSpan) { + final TradeHistoryParamsTimeSpan timeSpanParam = (TradeHistoryParamsTimeSpan) params; + timeSpanParam.setStartTime( + new Date(System.currentTimeMillis() - END_TIME)); + } + if (params instanceof TradeHistoryParamCurrencyPair) { + ((TradeHistoryParamCurrencyPair) params).setCurrencyPair(CurrencyPair.BTC_USDT); + } + + stubGet(ORDERS_JSON, 200, URL_TRADES); + UserTrades response = service.getTradeHistory(params); + Assert.assertNotNull(response); + } - return service.getOpenOrders(); + @Test(timeout = 2000) + public void getOrderSuccess() throws Exception { + stubGet(NEW_ORDER_LIMIT_JSON, 200, URL_ORDERS_BY_ID_1); + stubGet(NEW_ORDER_MARKET_JSON, 200, URL_ORDERS_BY_ID_2); + Collection response = service.getOrder("11111111","22222222"); + Assert.assertNotNull(response); } private String placeLimitOrder() throws IOException { @@ -115,8 +141,14 @@ private String placeStopOrder() throws IOException { } private Boolean cancelOrder(int statusCode, String orderId) throws IOException { - stubDelete(statusCode, URL_ORDERS_DELETE); + stubDelete(statusCode, URL_ORDERS_BY_ID_1); return service.cancelOrder(orderId); } + + private Boolean cancelAllOrder(int statusCode, CancelOrderByCurrencyPair orderParams) throws IOException { + stubDelete(statusCode, URL_ORDERS); + + return service.cancelOrder(orderParams); + } } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java index be20016bcec..8bae9276afe 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java @@ -11,7 +11,9 @@ public class BlockchainConstants { public static final String URL_DEPOSIT_BY_CURRENCY = "/v3/exchange/deposits/BTC"; public static final String URL_WITHDRAWALS = "/v3/exchange/withdrawals"; public static final String URL_ORDERS = "/v3/exchange/orders"; - public static final String URL_ORDERS_DELETE = "/v3/exchange/orders/11111111"; + public static final String URL_ORDERS_BY_ID_1 = "/v3/exchange/orders/11111111"; + public static final String URL_ORDERS_BY_ID_2 = "/v3/exchange/orders/22222222"; + public static final String URL_TRADES = "/v3/exchange/trades"; public static final String WITHDRAWAL_ID = "3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ"; public static final String STATUS_CODE_401 = "Unauthorized (HTTP status code: 401)"; public static final String STATUS_CODE_400 = "Bad Request (HTTP status code: 400)"; @@ -34,4 +36,5 @@ public class BlockchainConstants { public static final String NOT_IMPLEMENTED_YET = "Not implemented yet"; public static final String BENEFICIARY = "ea1f34b3-e77a-4646-9cfa-5d6d3518c6d3"; public static final String ORDER_ID = "11111111"; + public static final Long END_TIME = 12 * 30 * 24 * 60 * 60 * 1000L; } diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java new file mode 100644 index 00000000000..bc0a93bde0d --- /dev/null +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -0,0 +1,109 @@ +package org.knowm.xchange.examples.blockchain.trade; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import lombok.SneakyThrows; +import org.knowm.xchange.Exchange; +import org.knowm.xchange.currency.CurrencyPair; +import org.knowm.xchange.dto.Order; +import org.knowm.xchange.dto.trade.*; +import org.knowm.xchange.examples.blockchain.BlockchainDemoUtils; +import org.knowm.xchange.service.trade.TradeService; +import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; +import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; +import org.knowm.xchange.service.trade.params.TradeHistoryParams; +import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; +import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Date; + +import static org.knowm.xchange.examples.blockchain.BlockchainDemoUtils.END_TIME; + +public class BlockchainTradeDemo { + private static final Exchange BLOCKCHAIN_EXCHANGE = BlockchainDemoUtils.createExchange(); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); + + public static void main(String[] args) throws IOException { + System.out.println("===== TRADE SERVICE ====="); + tradeServiceDemo(); + } + + @SneakyThrows + private static void tradeServiceDemo() throws IOException { + TradeService tradeService = BLOCKCHAIN_EXCHANGE.getTradeService(); + + System.out.println("===== placeLimitOrder ====="); + LimitOrder limitOrder = + new LimitOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) + .originalAmount(new BigDecimal("1.0")) + .limitPrice(new BigDecimal("0.23")) + .build(); + + String tradeLimitOrder = tradeService.placeLimitOrder(limitOrder); + System.out.println(OBJECT_MAPPER.writeValueAsString(tradeLimitOrder)); + + System.out.println("===== placeMarketOrder ====="); + MarketOrder marketOrder = + new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) + .originalAmount(new BigDecimal("1.0")) + .cumulativeAmount(new BigDecimal("0.22")) + .build(); + + String tradeMarketOrder = tradeService.placeMarketOrder(marketOrder); + System.out.println(OBJECT_MAPPER.writeValueAsString(tradeMarketOrder)); + + System.out.println("===== placeStopOrder ====="); + StopOrder stopOrder = + new StopOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) + .originalAmount(new BigDecimal("1.0")) + .stopPrice(new BigDecimal("0.21")) + .build(); + + String tradeStopOrder = tradeService.placeStopOrder(stopOrder); + System.out.println(OBJECT_MAPPER.writeValueAsString(tradeStopOrder)); + + Thread.sleep(5000); + System.out.println("===== getOpenOrders ====="); + + try { + final OpenOrdersParamCurrencyPair openOrdersParamsBtcUsd = + (OpenOrdersParamCurrencyPair) tradeService.createOpenOrdersParams(); + openOrdersParamsBtcUsd.setCurrencyPair(CurrencyPair.ADA_USDT); + OpenOrders openOrdersParams = tradeService.getOpenOrders(openOrdersParamsBtcUsd); + System.out.println(OBJECT_MAPPER.writeValueAsString(openOrdersParams)); + + OpenOrders openOrders = tradeService.getOpenOrders(); + System.out.println(OBJECT_MAPPER.writeValueAsString(openOrders)); + } catch (IOException e) { + e.printStackTrace(); + } + + + System.out.println("===== cancelOrder ====="); + CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair("ADA/USDT"); + Boolean cancelAllOrderByCurrency = tradeService.cancelOrder(cancelOrderByCurrencyPair); + System.out.println("Canceling returned " + cancelAllOrderByCurrency); + + System.out.println("===== getTradeHistory ====="); + + TradeHistoryParams params = tradeService.createTradeHistoryParams(); + if (params instanceof TradeHistoryParamsTimeSpan) { + final TradeHistoryParamsTimeSpan timeSpanParam = (TradeHistoryParamsTimeSpan) params; + timeSpanParam.setStartTime( + new Date(System.currentTimeMillis() - END_TIME)); + } + + if (params instanceof TradeHistoryParamCurrencyPair) { + ((TradeHistoryParamCurrencyPair) params).setCurrencyPair(CurrencyPair.ADA_USDT); + } + UserTrades tradeHistory = tradeService.getTradeHistory(params); + System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); + + System.out.println("===== getOrder ====="); + Collection getOrder = tradeService.getOrder(tradeLimitOrder); + System.out.println(OBJECT_MAPPER.writeValueAsString(getOrder)); + } +} From 3faa2b1b20150d8582adc9e0141a969c83693b86 Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Wed, 15 Jun 2022 13:30:49 -0300 Subject: [PATCH 03/10] review version 2 --- .../blockchain/BlockchainAdapters.java | 101 ++++++------------ .../blockchain/BlockchainConstants.java | 4 +- .../blockchain/BlockchainExchange.java | 95 +++++++++------- .../dto/account/BlockchainSymbol.java | 6 +- .../blockchain/dto/trade/BlockchainOrder.java | 22 ++++ .../service/BlockchainTradeService.java | 15 ++- .../service/BlockchainBaseTest.java | 12 ++- .../service/account/AccountServiceTest.java | 25 ++--- .../service/trade/TradeServiceTest.java | 68 ++++++------ .../service/utils/BlockchainConstants.java | 4 + .../blockchain/trade/BlockchainTradeDemo.java | 43 +++----- 11 files changed, 194 insertions(+), 201 deletions(-) diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index 50db6696169..80a7d1c87d1 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -12,15 +12,15 @@ import org.knowm.xchange.dto.account.AddressWithTag; import org.knowm.xchange.dto.account.FundingRecord; import org.knowm.xchange.dto.marketdata.Trades; +import org.knowm.xchange.dto.meta.CurrencyMetaData; +import org.knowm.xchange.dto.meta.CurrencyPairMetaData; +import org.knowm.xchange.dto.meta.ExchangeMetaData; +import org.knowm.xchange.dto.meta.RateLimit; import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.instrument.Instrument; -import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; -import org.knowm.xchange.service.trade.params.CancelOrderParams; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.UUID; +import java.util.*; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.knowm.xchange.blockchain.BlockchainConstants.*; @@ -32,15 +32,6 @@ public static String toSymbol(CurrencyPair currencyPair) { return String.format(CURRENCY_PAIR_SYMBOL_FORMAT, currencyPair.base.getCurrencyCode(), currencyPair.counter.getCurrencyCode()); } - public static String toSymbol(CancelOrderParams currencyPair) { - if (currencyPair instanceof CancelOrderByCurrencyPair) { - return String.format(CURRENCY_PAIR_SYMBOL_FORMAT, - ((CancelOrderByCurrencyPair) currencyPair).getCurrencyPair().base, - ((CancelOrderByCurrencyPair) currencyPair).getCurrencyPair().counter); - } - throw new IllegalArgumentException(String.format("Unsupported currency pair '%s'", currencyPair)); - } - public static CurrencyPair toCurrencyPair(Instrument instrument){ if(instrument instanceof CurrencyPair) { return (CurrencyPair) instrument; @@ -118,21 +109,12 @@ public static CurrencyPair toCurrencyPairBySymbol(BlockchainSymbol blockchainSym } public static OpenOrders toOpenOrders(List blockchainOrders){ - List limitOrders = new ArrayList<>(Collections.emptyList()); - List hiddenOrders = new ArrayList<>(Collections.emptyList()); + List limitOrders = new ArrayList<>(); + List hiddenOrders = new ArrayList<>(); for(BlockchainOrder blockchainOrder : blockchainOrders) { - final Order.OrderType orderType = blockchainOrder.isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; - final CurrencyPair symbol = blockchainOrder.getSymbol(); - Order.Builder builder; + Order.Builder builder = blockchainOrder.getOrderBuilder(); - if (blockchainOrder.isMarketOrder()) { - builder = new MarketOrder.Builder(orderType, symbol); - } else if (blockchainOrder.isLimitOrder()){ - builder = new LimitOrder.Builder(orderType, symbol).limitPrice(blockchainOrder.getPrice()); - } else { - builder = new StopOrder.Builder(orderType, symbol).stopPrice(blockchainOrder.getPrice()); - } Order order = builder.orderStatus(toOrderStatus(blockchainOrder.getOrdStatus())) .originalAmount(blockchainOrder.getCumQty().add(blockchainOrder.getLeavesQty())) .id(Long.toString(blockchainOrder.getExOrdId())) @@ -151,17 +133,7 @@ public static OpenOrders toOpenOrders(List blockchainOrders){ } public static Order toOpenOrdersById(BlockchainOrder blockchainOrder){ - Order.OrderType orderType = blockchainOrder.isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; - CurrencyPair symbol = blockchainOrder.getSymbol(); - Order.Builder builder; - - if (blockchainOrder.isMarketOrder()) { - builder = new MarketOrder.Builder(orderType, symbol); - } else if (blockchainOrder.isLimitOrder()){ - builder = new LimitOrder.Builder(orderType, symbol).limitPrice(blockchainOrder.getPrice()); - } else { - builder = new StopOrder.Builder(orderType, symbol).stopPrice(blockchainOrder.getPrice()); - } + Order.Builder builder = blockchainOrder.getOrderBuilder(); return builder.originalAmount(blockchainOrder.getCumQty().add(blockchainOrder.getLeavesQty())) .id(Long.toString(blockchainOrder.getExOrdId())) @@ -196,7 +168,7 @@ public static Order.OrderStatus toOrderStatus(String status) { public static BlockchainOrder toBlockchainLimitOrder(LimitOrder limitOrder){ return BlockchainOrder.builder() - .ordType(limitOrder.getType().toString()) + .ordType(LIMIT) .symbol(toCurrencyPair(limitOrder.getInstrument())) .side(Order.OrderType.BID.equals(limitOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) .orderQty(limitOrder.getOriginalAmount()) @@ -207,7 +179,7 @@ public static BlockchainOrder toBlockchainLimitOrder(LimitOrder limitOrder){ public static BlockchainOrder toBlockchainMarketOrder(MarketOrder marketOrder){ return BlockchainOrder.builder() - .ordType(marketOrder.getType().toString()) + .ordType(MARKET) .symbol(toCurrencyPair(marketOrder.getInstrument())) .side(Order.OrderType.BID.equals(marketOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) .orderQty(marketOrder.getOriginalAmount()) @@ -218,7 +190,7 @@ public static BlockchainOrder toBlockchainMarketOrder(MarketOrder marketOrder){ public static BlockchainOrder toBlockchainStopOrder(StopOrder stopOrder){ return BlockchainOrder.builder() - .ordType(stopOrder.getType().toString()) + .ordType(STOP) .symbol(toCurrencyPair(stopOrder.getInstrument())) .side(Order.OrderType.BID.equals(stopOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) .orderQty(stopOrder.getOriginalAmount()) @@ -249,37 +221,24 @@ public static UserTrades toUserTrades(List blockchainTrades) { return new UserTrades(trades, lastId, Trades.TradeSortType.SortByTimestamp); } - /*public static ExchangeMetaData adaptMetaData( - List currencyPairs, ExchangeMetaData metaData) { - - Map pairsMap = metaData.getCurrencyPairs(); - Map currenciesMap = metaData.getCurrencies(); + public static ExchangeMetaData adaptMetaData(Map markets) { + Map currencyPairs = new HashMap<>(); + Map currency = new HashMap<>(); - pairsMap.keySet().retainAll(currencyPairs); + for (Map.Entry entry : markets.entrySet()) { + CurrencyPair pair = BlockchainAdapters.toCurrencyPairBySymbol(entry.getValue()); + CurrencyPairMetaData currencyPairMetaData = + new CurrencyPairMetaData.Builder() + .baseScale(entry.getValue().getBaseCurrencyScale()) + .minimumAmount(entry.getValue().getMinOrderSize()) + .maximumAmount(entry.getValue().getMaxOrderSize()) + .build(); + currencyPairs.put(pair, currencyPairMetaData); + currency.put(entry.getValue().getBaseCurrency(), null); + } - Set currencies = - currencyPairs.stream() - .flatMap(pair -> Stream.of(pair.base, pair.counter)) - .collect(Collectors.toSet()); - currenciesMap.keySet().retainAll(currencies); + RateLimit[] rateLimits = {new RateLimit(30, 1, TimeUnit.SECONDS)}; - for (CurrencyPair c : currencyPairs) { - if (!pairsMap.containsKey(c)) { - pairsMap.put(c, null); - } - - if (!currenciesMap.containsKey(c.base)) { - currenciesMap.put( - c.base, - new CurrencyMetaData( - 2, - null)); - } - if (!currenciesMap.containsKey(c.counter)) { - currenciesMap.put(c.counter, new CurrencyMetaData(2, null)); - } - } - - return metaData; - }*/ + return new ExchangeMetaData(currencyPairs, currency, rateLimits, rateLimits, false); + } } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java index d2dad904af6..26f2a3baf27 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java @@ -23,7 +23,7 @@ public class BlockchainConstants { public static final String WITHDRAWAL_EXCEPTION = "Invalid WithdrawFundsParams parameter. Only DefaultWithdrawFundsParams is supported."; public static final String EXCEPTION_MESSAGE = "Operation failed without any error message"; public static final String FUNDING_RECORD_TYPE_UNSUPPORTED = "Invalid FundingRecord parameter. Only DefaultWithdrawFundsParams is supported."; - public static final String CURRENCY_PAIR_EXCEPTION = "You need to provide the currency pair."; + public static final String CURRENCY_PAIR_EXCEPTION = "Invalid TradeHistoryParams type, it should be an instance of BlockchainTradeHistoryParams"; public static final String OPEN = "OPEN"; public static final String REJECTED = "REJECTED"; public static final String REFUNDING = "REFUNDING"; @@ -39,7 +39,7 @@ public class BlockchainConstants { public static final String NOT_IMPLEMENTED_YET = "Not implemented yet"; public static final String MARKET = "MARKET"; public static final String LIMIT = "LIMIT"; - public static final String STOP_ORDER = "STOP_ORDER"; + public static final String STOP = "STOP"; public static final String BUY = "buy"; public static final String SELL = "sell"; } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java index 1b8fceb8d06..78beb26414d 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java @@ -2,65 +2,80 @@ import org.knowm.xchange.BaseExchange; import org.knowm.xchange.ExchangeSpecification; +import org.knowm.xchange.blockchain.dto.account.BlockchainSymbol; import org.knowm.xchange.blockchain.service.BlockchainAccountService; +import org.knowm.xchange.blockchain.service.BlockchainAccountServiceRaw; import org.knowm.xchange.blockchain.service.BlockchainTradeService; import org.knowm.xchange.client.ExchangeRestProxyBuilder; import org.knowm.xchange.client.ResilienceRegistries; +import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.service.marketdata.MarketDataService; -import org.knowm.xchange.service.trade.TradeService; import si.mazi.rescu.SynchronizedValueFactory; import javax.ws.rs.HeaderParam; +import java.io.IOException; +import java.util.Map; -import static org.knowm.xchange.blockchain.BlockchainConstants.*; +import static org.knowm.xchange.blockchain.BlockchainConstants.NOT_IMPLEMENTED_YET; +import static org.knowm.xchange.blockchain.BlockchainConstants.X_API_TOKEN; -/** @author scuevas*/ +/** + * @author scuevas + */ public class BlockchainExchange extends BaseExchange { - protected static ResilienceRegistries RESILIENCE_REGISTRIES; + protected static ResilienceRegistries RESILIENCE_REGISTRIES; - protected BlockchainAuthenticated blockchain; + protected BlockchainAuthenticated blockchain; - @Override - protected void initServices() { - this.blockchain = ExchangeRestProxyBuilder - .forInterface(BlockchainAuthenticated.class, this.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.addDefaultParam( - HeaderParam.class, X_API_TOKEN, - this.getExchangeSpecification().getSecretKey()) - ).build(); + @Override + protected void initServices() { + this.blockchain = ExchangeRestProxyBuilder + .forInterface(BlockchainAuthenticated.class, this.getExchangeSpecification()) + .clientConfigCustomizer(clientConfig -> clientConfig.addDefaultParam( + HeaderParam.class, X_API_TOKEN, + this.getExchangeSpecification().getSecretKey()) + ).build(); - this.accountService = new BlockchainAccountService(this, this.blockchain, this.getResilienceRegistries()); - this.tradeService = new BlockchainTradeService(this, this.blockchain, this.getResilienceRegistries()); - } + this.accountService = new BlockchainAccountService(this, this.blockchain, this.getResilienceRegistries()); + this.tradeService = new BlockchainTradeService(this, this.blockchain, this.getResilienceRegistries()); + } + + @Override + public void remoteInit() throws IOException, ExchangeException { + BlockchainAccountServiceRaw dataService = + (BlockchainAccountServiceRaw) this.accountService; + Map markets = dataService.getSymbols(); + exchangeMetaData = BlockchainAdapters.adaptMetaData(markets); + } - @Override - public ExchangeSpecification getDefaultExchangeSpecification() { - ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); - exchangeSpecification.setSslUri("https://api.blockchain.com"); - exchangeSpecification.setHost("www.blockchain.com"); - exchangeSpecification.setPort(80); - exchangeSpecification.setExchangeName("Blockchain Exchange"); - exchangeSpecification.setExchangeDescription("Blockchain Exchange"); - return exchangeSpecification; - } + @Override + public ExchangeSpecification getDefaultExchangeSpecification() { + ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass()); + exchangeSpecification.setSslUri("https://api.blockchain.com"); + exchangeSpecification.setHost("www.blockchain.com"); + exchangeSpecification.setPort(80); + exchangeSpecification.setExchangeName("Blockchain Exchange"); + exchangeSpecification.setExchangeDescription("Blockchain Exchange"); + return exchangeSpecification; + } - @Override - public SynchronizedValueFactory getNonceFactory() { - throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); - } + @Override + public SynchronizedValueFactory getNonceFactory() { + throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); + } - @Override - public ResilienceRegistries getResilienceRegistries() { - if (RESILIENCE_REGISTRIES == null) { - RESILIENCE_REGISTRIES = BlockchainResilience.getResilienceRegistries(); + @Override + public ResilienceRegistries getResilienceRegistries() { + if (RESILIENCE_REGISTRIES == null) { + RESILIENCE_REGISTRIES = BlockchainResilience.getResilienceRegistries(); + } + return RESILIENCE_REGISTRIES; } - return RESILIENCE_REGISTRIES; - } - @Override - public MarketDataService getMarketDataService() { - throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); - } + @Override + public MarketDataService getMarketDataService() { + throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); + } } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/account/BlockchainSymbol.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/account/BlockchainSymbol.java index 8523b614c73..cc0e41b5b2f 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/account/BlockchainSymbol.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/account/BlockchainSymbol.java @@ -7,6 +7,8 @@ import lombok.extern.jackson.Jacksonized; import org.knowm.xchange.currency.Currency; +import java.math.BigDecimal; + @Data @Builder @Jacksonized @@ -26,11 +28,11 @@ public class BlockchainSymbol { @JsonProperty("min_price_increment_scale") private final Integer minPriceIncrementScale; @JsonProperty("min_order_size") - private final Long minOrderSize; + private final BigDecimal minOrderSize; @JsonProperty("min_order_size_scale") private final Integer minOrderSizeScale; @JsonProperty("max_order_size") - private final Integer maxOrderSize; + private final BigDecimal maxOrderSize; @JsonProperty("max_order_size_scale") private final Integer maxOrderSizeScale; @JsonProperty("lot_size") diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java index 4e2f85bbb1d..3b8808c0902 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java @@ -10,6 +10,10 @@ import lombok.extern.jackson.Jacksonized; import org.knowm.xchange.blockchain.serializer.BlockchainCurrencyPairSerializer; import org.knowm.xchange.currency.CurrencyPair; +import org.knowm.xchange.dto.Order; +import org.knowm.xchange.dto.trade.LimitOrder; +import org.knowm.xchange.dto.trade.MarketOrder; +import org.knowm.xchange.dto.trade.StopOrder; import org.knowm.xchange.utils.jackson.CurrencyPairDeserializer; import java.math.BigDecimal; @@ -57,4 +61,22 @@ public boolean isLimitOrder() { public boolean isBuyer() { return BUY.equals(this.side.toUpperCase()); } + + @JsonIgnore + public Order.Builder getOrderBuilder(){ + final Order.OrderType orderType = this.isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; + final CurrencyPair symbol = this.getSymbol(); + Order.Builder builder; + + if (this.isMarketOrder()) { + builder = new MarketOrder.Builder(orderType, symbol); + } else if (this.isLimitOrder()){ + builder = new LimitOrder.Builder(orderType, symbol).limitPrice(this.getPrice()); + } else { + builder = new StopOrder.Builder(orderType, symbol).stopPrice(this.getPrice()); + } + + return builder; + } + } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java index cd7daf944fd..2b38cc169ae 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -79,8 +79,7 @@ public boolean cancelOrder(String orderId) throws IOException { @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByCurrencyPair) { - this.cancelAllOrdersBySymbol(BlockchainAdapters.toSymbol(orderParams)); - return true; + return this.cancelAllOrdersBySymbol(BlockchainAdapters.toSymbol(((CancelOrderByCurrencyPair) orderParams).getCurrencyPair())); } if (orderParams instanceof CancelOrderByIdParams) { @@ -96,7 +95,7 @@ public Class[] getRequiredCancelOrderParamClasses() { } @Override - public OpenPositions getOpenPositions() throws IOException { + public OpenPositions getOpenPositions() { throw new NotYetImplementedForExchangeException(NOT_IMPLEMENTED_YET); } @@ -114,10 +113,6 @@ public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException String symbol = BlockchainAdapters.toSymbol( ((TradeHistoryParamCurrencyPair) params).getCurrencyPair()); - if (symbol == null) { - throw new ExchangeException(CURRENCY_PAIR_EXCEPTION); - } - if (params instanceof TradeHistoryParamsTimeSpan) { if (((TradeHistoryParamsTimeSpan) params).getStartTime() != null) { startTime = ((TradeHistoryParamsTimeSpan) params).getStartTime().getTime(); @@ -140,7 +135,7 @@ public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException } @Override - public TradeHistoryParams createTradeHistoryParams() { + public BlockchainTradeHistoryParams createTradeHistoryParams() { return BlockchainTradeHistoryParams.builder().build(); } @@ -154,7 +149,9 @@ public Collection getOrder(String... orderIds) throws IOException { List openOrders = new ArrayList<>(); for (String orderId : orderIds) { - openOrders.addAll(getOrder(new DefaultQueryOrderParam(orderId))); + if (orderId != null) { + openOrders.addAll(getOrder(new DefaultQueryOrderParam(orderId))); + } } return openOrders; } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java index d3857c9a7c9..0bc5dc0e1ae 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java @@ -8,6 +8,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static org.knowm.xchange.blockchain.service.utils.BlockchainConstants.APPLICATION; +import static org.knowm.xchange.blockchain.service.utils.BlockchainConstants.CONTENT_TYPE; public class BlockchainBaseTest { @@ -33,17 +35,17 @@ protected void stubPost(String fileName, int statusCode, String url) { .willReturn( aResponse() .withStatus(statusCode) - .withHeader("Content-Type", "application/json") + .withHeader(CONTENT_TYPE, APPLICATION) .withBodyFile(fileName))); } - protected void stubGet(String fileName, int statusCode, String url) { + protected void stubGet(String fileName, String url) { stubFor( get(urlPathEqualTo(url)) .willReturn( aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "application/json") + .withStatus(200) + .withHeader(CONTENT_TYPE, APPLICATION) .withBodyFile(fileName))); } @@ -53,6 +55,6 @@ protected void stubDelete(int statusCode, String url) { .willReturn( aResponse() .withStatus(statusCode) - .withHeader("Content-Type", "application/json"))); + .withHeader(CONTENT_TYPE, APPLICATION))); } } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java index 707da638206..b6876bafee2 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; -import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; import static org.knowm.xchange.blockchain.service.utils.BlockchainConstants.*; @@ -61,7 +60,7 @@ public void withdrawFailure() { @Test(timeout = 2000) public void withdrawException() { - Throwable exception = catchThrowable(() -> withdrawExcept()); + Throwable exception = catchThrowable(this::withdrawExcept); assertThat(exception) .isInstanceOf(NotYetImplementedForExchangeException.class) .hasMessage(NOT_IMPLEMENTED_YET); @@ -87,9 +86,7 @@ public void getWithdrawFundingHistorySuccess() throws Exception { Assert.assertNotNull(response); response.forEach( - record -> { - Assert.assertTrue( record.getAmount().compareTo(BigDecimal.ZERO) > 0); - }); + record -> Assert.assertTrue(record.getAmount().compareTo(BigDecimal.ZERO) > 0)); } @Test(timeout = 2000) @@ -98,9 +95,7 @@ public void getDepositFundingHistorySuccess() throws Exception { Assert.assertNotNull(response); response.forEach( - record -> { - Assert.assertTrue( record.getAmount().compareTo(BigDecimal.ZERO) > 0); - }); + record -> Assert.assertTrue(record.getAmount().compareTo(BigDecimal.ZERO) > 0)); } @Test(timeout = 2000) @@ -110,7 +105,7 @@ public void getDynamicTradingFeesSuccess() throws Exception { } private AccountInfo getAccountInfo() throws IOException { - stubGet(ACCOUNT_INFORMATION_JSON, 200, URL_ACCOUNT); + stubGet(ACCOUNT_INFORMATION_JSON, URL_ACCOUNT); return service.getAccountInfo(); } @@ -127,9 +122,9 @@ private String withdraw(String responseFileName, int statusCode) throws IOExcept return service.withdrawFunds(params); } - private String withdrawExcept() throws IOException { + private void withdrawExcept() throws IOException { stubPost(WITHDRAWAL_SUCCESS_JSON, 200, URL_WITHDRAWALS); - return service.withdrawFunds( + service.withdrawFunds( Currency.BTC, BigDecimal.valueOf(0.005), ADDRESS); } @@ -140,7 +135,7 @@ private String requestDeposit(String responseFileName, int statusCode) throws IO } private List withdrawFundingHistory() throws IOException { - stubGet(WITHDRAWAL_HISTORY_SUCCESS_JSON, 200, URL_WITHDRAWALS); + stubGet(WITHDRAWAL_HISTORY_SUCCESS_JSON, URL_WITHDRAWALS); TradeHistoryParams params = service.createFundingHistoryParams(); if (params instanceof HistoryParamsFundingType) { ((HistoryParamsFundingType) params).setType(FundingRecord.Type.WITHDRAWAL); @@ -150,7 +145,7 @@ private List withdrawFundingHistory() throws IOException { } private List depositFundingHistory() throws IOException { - stubGet(DEPOSIT_HISTORY_SUCCESS_JSON, 200, URL_DEPOSITS); + stubGet(DEPOSIT_HISTORY_SUCCESS_JSON, URL_DEPOSITS); TradeHistoryParams params = service.createFundingHistoryParams(); if (params instanceof HistoryParamsFundingType) { ((HistoryParamsFundingType) params).setType(FundingRecord.Type.DEPOSIT); @@ -160,8 +155,8 @@ private List depositFundingHistory() throws IOException { } private Map tradingFees() throws IOException { - stubGet(FEES_JSON, 200, URL_FEES); - stubGet(SYMBOL_JSON, 200, URL_SYMBOLS); + stubGet(FEES_JSON, URL_FEES); + stubGet(SYMBOL_JSON, URL_SYMBOLS); return service.getDynamicTradingFees(); } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java index 8082f43936c..3ee8cc0f606 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java @@ -4,14 +4,13 @@ import org.junit.Before; import org.junit.Test; import org.knowm.xchange.blockchain.BlockchainExchange; +import org.knowm.xchange.blockchain.params.BlockchainTradeHistoryParams; import org.knowm.xchange.blockchain.service.BlockchainBaseTest; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; -import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; -import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import si.mazi.rescu.HttpStatusIOException; @@ -35,38 +34,43 @@ public void init() { @Test(timeout = 2000) public void getOpenOrdersSuccess() throws Exception { - stubGet(ORDERS_JSON, 200, URL_ORDERS); + stubGet(ORDERS_JSON, URL_ORDERS); OpenOrders response = service.getOpenOrders(); - Assert.assertNotNull(response); + assertThat(response).isNotNull(); + assertThat(response.getAllOpenOrders()).isNotEmpty(); + Order order = response.getAllOpenOrders().get(0); + assertThat(order).isNotNull(); + assertThat(order.getOriginalAmount()).isNotNull().isPositive(); + assertThat(order.getId()).isEqualTo(ORDER_ID); } @Test(timeout = 2000) public void placeLimitOrderSuccess() throws Exception { String response = placeLimitOrder(); - Assert.assertNotNull(response); + assertThat(response).isEqualTo(ORDER_ID); } @Test(timeout = 2000) public void placeMarketOrderSuccess() throws Exception { String response = placeMarketOrder(); - Assert.assertNotNull(response); + assertThat(response).isEqualTo(MARKET_ORDER_ID); } @Test(timeout = 2000) public void placeStopOrderSuccess() throws Exception { String response = placeStopOrder(); - Assert.assertNotNull(response); + assertThat(response).isEqualTo(STOP_ORDER_ID); } @Test(timeout = 2000) public void cancelOrderSuccess() throws Exception { - Boolean response = cancelOrder(200, ORDER_ID); + Boolean response = cancelOrder(200); assertThat(response).isEqualTo(true); } @Test(timeout = 2000) - public void cancelOrderFailure() throws Exception { - Throwable exception = catchThrowable(() -> cancelOrder(400, ORDER_ID)); + public void cancelOrderFailure() { + Throwable exception = catchThrowable(() -> cancelOrder(400)); assertThat(exception) .isInstanceOf(HttpStatusIOException.class) .hasMessage(HTTP_CODE_400); @@ -75,33 +79,37 @@ public void cancelOrderFailure() throws Exception { @Test(timeout = 2000) public void cancelOrderByCurrency() throws Exception { CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair("BTC/USD"); - Boolean response = cancelAllOrder(200, cancelOrderByCurrencyPair); + Boolean response = cancelAllOrder(cancelOrderByCurrencyPair); assertThat(response).isEqualTo(true); } @Test(timeout = 2000) public void getTrades() throws Exception { - TradeHistoryParams params = service.createTradeHistoryParams(); - if (params instanceof TradeHistoryParamsTimeSpan) { - final TradeHistoryParamsTimeSpan timeSpanParam = (TradeHistoryParamsTimeSpan) params; - timeSpanParam.setStartTime( - new Date(System.currentTimeMillis() - END_TIME)); - } - if (params instanceof TradeHistoryParamCurrencyPair) { - ((TradeHistoryParamCurrencyPair) params).setCurrencyPair(CurrencyPair.BTC_USDT); - } - - stubGet(ORDERS_JSON, 200, URL_TRADES); + BlockchainTradeHistoryParams params = (BlockchainTradeHistoryParams) service.createTradeHistoryParams(); + ((TradeHistoryParamsTimeSpan) params).setStartTime( + new Date(System.currentTimeMillis() - END_TIME)); + + params.setCurrencyPair(CurrencyPair.BTC_USDT); + + stubGet(ORDERS_JSON, URL_TRADES); UserTrades response = service.getTradeHistory(params); - Assert.assertNotNull(response); + assertThat(response).isNotNull(); + assertThat(response.getUserTrades()).isNotEmpty(); + UserTrade trade = response.getUserTrades().get(0); + assertThat(trade).isNotNull(); + assertThat(trade.getOriginalAmount()).isNotNull().isPositive(); + assertThat(trade.getPrice()).isNotNull().isPositive(); } @Test(timeout = 2000) public void getOrderSuccess() throws Exception { - stubGet(NEW_ORDER_LIMIT_JSON, 200, URL_ORDERS_BY_ID_1); - stubGet(NEW_ORDER_MARKET_JSON, 200, URL_ORDERS_BY_ID_2); - Collection response = service.getOrder("11111111","22222222"); + stubGet(NEW_ORDER_LIMIT_JSON, URL_ORDERS_BY_ID_1); + stubGet(NEW_ORDER_MARKET_JSON, URL_ORDERS_BY_ID_2); + Collection response = service.getOrder("11111111", "22222222"); Assert.assertNotNull(response); + response.forEach( + record -> Assert.assertTrue(record.getOriginalAmount().compareTo(BigDecimal.ZERO) > 0)); + } private String placeLimitOrder() throws IOException { @@ -140,14 +148,14 @@ private String placeStopOrder() throws IOException { return service.placeStopOrder(stopOrder); } - private Boolean cancelOrder(int statusCode, String orderId) throws IOException { + private Boolean cancelOrder(int statusCode) throws IOException { stubDelete(statusCode, URL_ORDERS_BY_ID_1); - return service.cancelOrder(orderId); + return service.cancelOrder(ORDER_ID); } - private Boolean cancelAllOrder(int statusCode, CancelOrderByCurrencyPair orderParams) throws IOException { - stubDelete(statusCode, URL_ORDERS); + private Boolean cancelAllOrder(CancelOrderByCurrencyPair orderParams) throws IOException { + stubDelete(200, URL_ORDERS); return service.cancelOrder(orderParams); } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java index 8bae9276afe..b14fc2e480a 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java @@ -36,5 +36,9 @@ public class BlockchainConstants { public static final String NOT_IMPLEMENTED_YET = "Not implemented yet"; public static final String BENEFICIARY = "ea1f34b3-e77a-4646-9cfa-5d6d3518c6d3"; public static final String ORDER_ID = "11111111"; + public static final String MARKET_ORDER_ID = "22222222"; + public static final String STOP_ORDER_ID = "33333333"; public static final Long END_TIME = 12 * 30 * 24 * 60 * 60 * 1000L; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String APPLICATION = "application/json"; } diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index bc0a93bde0d..85170a3d851 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -2,16 +2,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import lombok.SneakyThrows; import org.knowm.xchange.Exchange; +import org.knowm.xchange.blockchain.params.BlockchainTradeHistoryParams; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.examples.blockchain.BlockchainDemoUtils; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; -import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; -import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; @@ -26,13 +24,12 @@ public class BlockchainTradeDemo { private static final Exchange BLOCKCHAIN_EXCHANGE = BlockchainDemoUtils.createExchange(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); - public static void main(String[] args) throws IOException { + public static void main(String[] args) throws IOException, InterruptedException { System.out.println("===== TRADE SERVICE ====="); tradeServiceDemo(); } - @SneakyThrows - private static void tradeServiceDemo() throws IOException { + private static void tradeServiceDemo() throws InterruptedException, IOException { TradeService tradeService = BLOCKCHAIN_EXCHANGE.getTradeService(); System.out.println("===== placeLimitOrder ====="); @@ -68,37 +65,29 @@ private static void tradeServiceDemo() throws IOException { Thread.sleep(5000); System.out.println("===== getOpenOrders ====="); - try { - final OpenOrdersParamCurrencyPair openOrdersParamsBtcUsd = - (OpenOrdersParamCurrencyPair) tradeService.createOpenOrdersParams(); - openOrdersParamsBtcUsd.setCurrencyPair(CurrencyPair.ADA_USDT); - OpenOrders openOrdersParams = tradeService.getOpenOrders(openOrdersParamsBtcUsd); - System.out.println(OBJECT_MAPPER.writeValueAsString(openOrdersParams)); + final OpenOrdersParamCurrencyPair openOrdersParamsBtcUsd = + (OpenOrdersParamCurrencyPair) tradeService.createOpenOrdersParams(); + openOrdersParamsBtcUsd.setCurrencyPair(CurrencyPair.ADA_USDT); + OpenOrders openOrdersParams = tradeService.getOpenOrders(openOrdersParamsBtcUsd); + System.out.println(OBJECT_MAPPER.writeValueAsString(openOrdersParams)); - OpenOrders openOrders = tradeService.getOpenOrders(); - System.out.println(OBJECT_MAPPER.writeValueAsString(openOrders)); - } catch (IOException e) { - e.printStackTrace(); - } + OpenOrders openOrders = tradeService.getOpenOrders(); + System.out.println(OBJECT_MAPPER.writeValueAsString(openOrders)); System.out.println("===== cancelOrder ====="); CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair("ADA/USDT"); - Boolean cancelAllOrderByCurrency = tradeService.cancelOrder(cancelOrderByCurrencyPair); + boolean cancelAllOrderByCurrency = tradeService.cancelOrder(cancelOrderByCurrencyPair); System.out.println("Canceling returned " + cancelAllOrderByCurrency); System.out.println("===== getTradeHistory ====="); - TradeHistoryParams params = tradeService.createTradeHistoryParams(); - if (params instanceof TradeHistoryParamsTimeSpan) { - final TradeHistoryParamsTimeSpan timeSpanParam = (TradeHistoryParamsTimeSpan) params; - timeSpanParam.setStartTime( - new Date(System.currentTimeMillis() - END_TIME)); - } + BlockchainTradeHistoryParams params = (BlockchainTradeHistoryParams) tradeService.createTradeHistoryParams(); + ((TradeHistoryParamsTimeSpan) params).setStartTime( + new Date(System.currentTimeMillis() - END_TIME)); + + params.setCurrencyPair(CurrencyPair.ADA_USDT); - if (params instanceof TradeHistoryParamCurrencyPair) { - ((TradeHistoryParamCurrencyPair) params).setCurrencyPair(CurrencyPair.ADA_USDT); - } UserTrades tradeHistory = tradeService.getTradeHistory(params); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); From 2b2baef39c6cd0a42941e631ec087b741b11c4eb Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Wed, 15 Jun 2022 17:43:39 -0300 Subject: [PATCH 04/10] review version 3 --- .../blockchain/BlockchainConstants.java | 1 + .../blockchain/dto/trade/BlockchainOrder.java | 12 ++++--- .../service/BlockchainTradeService.java | 34 +++++++++++++------ .../service/trade/TradeServiceTest.java | 3 +- .../blockchain/BlockchainDemoUtils.java | 6 ++++ .../blockchain/trade/BlockchainTradeDemo.java | 16 ++++----- 6 files changed, 48 insertions(+), 24 deletions(-) diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java index 26f2a3baf27..e1d1912face 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java @@ -24,6 +24,7 @@ public class BlockchainConstants { public static final String EXCEPTION_MESSAGE = "Operation failed without any error message"; public static final String FUNDING_RECORD_TYPE_UNSUPPORTED = "Invalid FundingRecord parameter. Only DefaultWithdrawFundsParams is supported."; public static final String CURRENCY_PAIR_EXCEPTION = "Invalid TradeHistoryParams type, it should be an instance of BlockchainTradeHistoryParams"; + public static final String ORDER_EXCEPTION = "The order was rejected probably the amount does not comply with the restrictions. The order id is null"; public static final String OPEN = "OPEN"; public static final String REJECTED = "REJECTED"; public static final String REFUNDING = "REFUNDING"; diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java index 3b8808c0902..e1106b2db36 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java @@ -62,18 +62,22 @@ public boolean isBuyer() { return BUY.equals(this.side.toUpperCase()); } + @JsonIgnore + public Order.OrderType getOrderType(){ + return isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; + } + @JsonIgnore public Order.Builder getOrderBuilder(){ - final Order.OrderType orderType = this.isBuyer() ? Order.OrderType.BID : Order.OrderType.ASK; final CurrencyPair symbol = this.getSymbol(); Order.Builder builder; if (this.isMarketOrder()) { - builder = new MarketOrder.Builder(orderType, symbol); + builder = new MarketOrder.Builder(getOrderType(), symbol); } else if (this.isLimitOrder()){ - builder = new LimitOrder.Builder(orderType, symbol).limitPrice(this.getPrice()); + builder = new LimitOrder.Builder(getOrderType(), symbol).limitPrice(this.getPrice()); } else { - builder = new StopOrder.Builder(orderType, symbol).stopPrice(this.getPrice()); + builder = new StopOrder.Builder(getOrderType(), symbol).stopPrice(this.getPrice()); } return builder; diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java index 2b38cc169ae..7bb9f7acabd 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -22,8 +22,7 @@ import java.util.Collection; import java.util.List; -import static org.knowm.xchange.blockchain.BlockchainConstants.CURRENCY_PAIR_EXCEPTION; -import static org.knowm.xchange.blockchain.BlockchainConstants.NOT_IMPLEMENTED_YET; +import static org.knowm.xchange.blockchain.BlockchainConstants.*; public class BlockchainTradeService extends BlockchainTradeServiceRaw implements TradeService { @@ -47,23 +46,36 @@ public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { - Long id = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)).getExOrdId(); - if (id != null) return Long.toString(id); - return null; + try { + Long id = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)).getExOrdId(); + if (id == null) throw new ExchangeException(ORDER_EXCEPTION); + return Long.toString(id); + } catch (BlockchainException e) { + throw BlockchainErrorAdapter.adapt(e); + } } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { - Long id = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)).getExOrdId(); - if (id != null) return Long.toString(id); - return null; + try { + Long id = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)).getExOrdId(); + if (id == null) throw new ExchangeException(ORDER_EXCEPTION); + return Long.toString(id); + } catch (BlockchainException e) { + throw BlockchainErrorAdapter.adapt(e); + } } @Override public String placeStopOrder(StopOrder stopOrder) throws IOException { - Long id = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)).getExOrdId(); - if (id != null) return Long.toString(id); - return null; + try { + Long id = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)).getExOrdId(); + if (id == null) throw new ExchangeException(ORDER_EXCEPTION); + return Long.toString(id); + } catch (BlockchainException e) { + throw BlockchainErrorAdapter.adapt(e); + } + } @Override diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java index 3ee8cc0f606..292f7f156a8 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java @@ -106,7 +106,8 @@ public void getOrderSuccess() throws Exception { stubGet(NEW_ORDER_LIMIT_JSON, URL_ORDERS_BY_ID_1); stubGet(NEW_ORDER_MARKET_JSON, URL_ORDERS_BY_ID_2); Collection response = service.getOrder("11111111", "22222222"); - Assert.assertNotNull(response); + assertThat(response).isNotNull(); + assertThat(response).isNotEmpty(); response.forEach( record -> Assert.assertTrue(record.getOriginalAmount().compareTo(BigDecimal.ZERO) > 0)); diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java index 975a8afcd0c..b1b69a8f191 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java @@ -5,9 +5,15 @@ import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.blockchain.BlockchainExchange; +import java.math.BigDecimal; + public class BlockchainDemoUtils { public static final Long END_TIME = 12 * 30 * 24 * 60 * 60 * 1000L; public static final String BENEFICIARY = "8a2e42ee-c94a-4641-9208-9501cbc0fed0"; + public static final String SYMBOL = "ADA/USDT"; + public static final BigDecimal AMOUNT = new BigDecimal("1.0"); + public static final BigDecimal STOP_PRICE = new BigDecimal("0.01"); + public static final BigDecimal STOP_LIMIT = new BigDecimal("0.005"); public static Exchange createExchange() { Exchange bcd = ExchangeFactory.INSTANCE.createExchange(BlockchainExchange.class); diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index 85170a3d851..ae0815fc18f 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -18,7 +18,7 @@ import java.util.Collection; import java.util.Date; -import static org.knowm.xchange.examples.blockchain.BlockchainDemoUtils.END_TIME; +import static org.knowm.xchange.examples.blockchain.BlockchainDemoUtils.*; public class BlockchainTradeDemo { private static final Exchange BLOCKCHAIN_EXCHANGE = BlockchainDemoUtils.createExchange(); @@ -35,8 +35,8 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println("===== placeLimitOrder ====="); LimitOrder limitOrder = new LimitOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) - .originalAmount(new BigDecimal("1.0")) - .limitPrice(new BigDecimal("0.23")) + .originalAmount(AMOUNT) + .limitPrice(STOP_LIMIT) .build(); String tradeLimitOrder = tradeService.placeLimitOrder(limitOrder); @@ -45,8 +45,8 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println("===== placeMarketOrder ====="); MarketOrder marketOrder = new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) - .originalAmount(new BigDecimal("1.0")) - .cumulativeAmount(new BigDecimal("0.22")) + .originalAmount(AMOUNT) + .cumulativeAmount(STOP_PRICE) .build(); String tradeMarketOrder = tradeService.placeMarketOrder(marketOrder); @@ -55,8 +55,8 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println("===== placeStopOrder ====="); StopOrder stopOrder = new StopOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) - .originalAmount(new BigDecimal("1.0")) - .stopPrice(new BigDecimal("0.21")) + .originalAmount(AMOUNT) + .stopPrice(STOP_PRICE) .build(); String tradeStopOrder = tradeService.placeStopOrder(stopOrder); @@ -76,7 +76,7 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println("===== cancelOrder ====="); - CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair("ADA/USDT"); + CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair(SYMBOL); boolean cancelAllOrderByCurrency = tradeService.cancelOrder(cancelOrderByCurrencyPair); System.out.println("Canceling returned " + cancelAllOrderByCurrency); From fbea05334515414739135a1b16750930c4dc659c Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Thu, 16 Jun 2022 16:33:33 -0300 Subject: [PATCH 05/10] review version 3.1 --- .../blockchain/BlockchainAdapters.java | 10 +++++++--- .../blockchain/BlockchainAuthenticated.java | 2 +- .../blockchain/BlockchainConstants.java | 3 +-- .../blockchain/dto/trade/BlockchainOrder.java | 1 + .../service/BlockchainTradeService.java | 15 +++++++++------ .../service/BlockchainTradeServiceRaw.java | 15 ++++++++++----- .../service/BlockchainBaseTest.java | 4 ++-- .../service/account/AccountServiceTest.java | 10 +++++----- .../service/trade/TradeServiceTest.java | 19 +++++++++++++++---- .../service/utils/BlockchainConstants.java | 3 +++ .../resources/__files/order_not_found.json | 1 + .../blockchain/trade/BlockchainTradeDemo.java | 3 +-- 12 files changed, 56 insertions(+), 30 deletions(-) create mode 100644 xchange-blockchain/src/test/resources/__files/order_not_found.json diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index 80a7d1c87d1..d3ef5ba9200 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -19,6 +19,7 @@ import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.instrument.Instrument; +import java.math.BigDecimal; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -194,7 +195,8 @@ public static BlockchainOrder toBlockchainStopOrder(StopOrder stopOrder){ .symbol(toCurrencyPair(stopOrder.getInstrument())) .side(Order.OrderType.BID.equals(stopOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) .orderQty(stopOrder.getOriginalAmount()) - .price(stopOrder.getStopPrice()) + .price(stopOrder.getLimitPrice()) + .stopPx(stopOrder.getStopPrice()) .clOrdId(generateClOrdId()) .build(); } @@ -208,7 +210,7 @@ private static String generateClOrdId() { public static UserTrades toUserTrades(List blockchainTrades) { List trades = blockchainTrades.stream() .map(blockchainTrade -> new UserTrade.Builder() - .type(blockchainTrade.isBuyer()? Order.OrderType.BID : Order.OrderType.ASK) + .type(blockchainTrade.getOrderType()) .originalAmount(blockchainTrade.getCumQty()) .currencyPair(blockchainTrade.getSymbol()) .price(blockchainTrade.getPrice()) @@ -227,10 +229,12 @@ public static ExchangeMetaData adaptMetaData(Map marke for (Map.Entry entry : markets.entrySet()) { CurrencyPair pair = BlockchainAdapters.toCurrencyPairBySymbol(entry.getValue()); + BigDecimal min_scale = BigDecimal.valueOf(Math.pow(10, (entry.getValue().getMinOrderSizeScale())*-1)); + BigDecimal minAmount = entry.getValue().getMinOrderSize().multiply(min_scale); CurrencyPairMetaData currencyPairMetaData = new CurrencyPairMetaData.Builder() .baseScale(entry.getValue().getBaseCurrencyScale()) - .minimumAmount(entry.getValue().getMinOrderSize()) + .minimumAmount(minAmount) .maximumAmount(entry.getValue().getMaxOrderSize()) .build(); currencyPairs.put(pair, currencyPairMetaData); diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java index bbeb2c05b1e..1ee518f6c04 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java @@ -105,7 +105,7 @@ List depositHistory(@QueryParam("from") Long startTime, */ @Path("/orders/{orderId}") @GET - BlockchainOrder getOrder(@PathParam("orderId") String orderId); + BlockchainOrder getOrder(@PathParam("orderId") String orderId) throws IOException, BlockchainException;; /** * Add an order diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java index e1d1912face..84e035caafc 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java @@ -24,7 +24,6 @@ public class BlockchainConstants { public static final String EXCEPTION_MESSAGE = "Operation failed without any error message"; public static final String FUNDING_RECORD_TYPE_UNSUPPORTED = "Invalid FundingRecord parameter. Only DefaultWithdrawFundsParams is supported."; public static final String CURRENCY_PAIR_EXCEPTION = "Invalid TradeHistoryParams type, it should be an instance of BlockchainTradeHistoryParams"; - public static final String ORDER_EXCEPTION = "The order was rejected probably the amount does not comply with the restrictions. The order id is null"; public static final String OPEN = "OPEN"; public static final String REJECTED = "REJECTED"; public static final String REFUNDING = "REFUNDING"; @@ -40,7 +39,7 @@ public class BlockchainConstants { public static final String NOT_IMPLEMENTED_YET = "Not implemented yet"; public static final String MARKET = "MARKET"; public static final String LIMIT = "LIMIT"; - public static final String STOP = "STOP"; + public static final String STOP = "STOPLIMIT"; public static final String BUY = "buy"; public static final String SELL = "sell"; } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java index e1106b2db36..91ee285612b 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/dto/trade/BlockchainOrder.java @@ -45,6 +45,7 @@ public class BlockchainOrder { private final BigDecimal leavesQty; private final BigDecimal cumQty; private final BigDecimal avgPx; + private final BigDecimal stopPx; private final Date timestamp; @JsonIgnore diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java index 7bb9f7acabd..2b3ac761a84 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -47,8 +47,9 @@ public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { try { - Long id = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)).getExOrdId(); - if (id == null) throw new ExchangeException(ORDER_EXCEPTION); + BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)); + Long id = order.getExOrdId(); + if (id == null) throw new ExchangeException(order.getText()); return Long.toString(id); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); @@ -58,8 +59,9 @@ public String placeLimitOrder(LimitOrder limitOrder) throws IOException { @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { try { - Long id = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)).getExOrdId(); - if (id == null) throw new ExchangeException(ORDER_EXCEPTION); + BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)); + Long id = order.getExOrdId(); + if (id == null) throw new ExchangeException(order.getText()); return Long.toString(id); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); @@ -69,8 +71,9 @@ public String placeMarketOrder(MarketOrder marketOrder) throws IOException { @Override public String placeStopOrder(StopOrder stopOrder) throws IOException { try { - Long id = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)).getExOrdId(); - if (id == null) throw new ExchangeException(ORDER_EXCEPTION); + BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)); + Long id = order.getExOrdId(); + if (id == null) throw new ExchangeException(order.getText()); return Long.toString(id); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java index 3ce4ba8bd9a..d36b514b8c7 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java @@ -18,7 +18,7 @@ protected BlockchainTradeServiceRaw(BlockchainExchange exchange, BlockchainAuthe super(exchange, blockchainApi, resilienceRegistries); } - protected List getOrders() throws IOException { + protected List getOrders() throws IOException, BlockchainException { return decorateApiCall(this.blockchainApi::getOrders) .withRetry(retry(GET_ORDERS)) .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) @@ -26,10 +26,15 @@ protected List getOrders() throws IOException { } protected BlockchainOrder getOrder(String orderId) throws IOException { - return decorateApiCall(() -> this.blockchainApi.getOrder(orderId)) - .withRetry(retry(GET_ORDER)) - .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) - .call(); + try { + return decorateApiCall(() -> this.blockchainApi.getOrder(orderId)) + .withRetry(retry(GET_ORDER)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + }catch (BlockchainException e){ + throw BlockchainErrorAdapter.adapt(e); + } + } protected BlockchainOrder postOrder(BlockchainOrder blockchainOrder) throws IOException{ diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java index 0bc5dc0e1ae..47de172b2c1 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/BlockchainBaseTest.java @@ -39,12 +39,12 @@ protected void stubPost(String fileName, int statusCode, String url) { .withBodyFile(fileName))); } - protected void stubGet(String fileName, String url) { + protected void stubGet(String fileName, int statusCode, String url) { stubFor( get(urlPathEqualTo(url)) .willReturn( aResponse() - .withStatus(200) + .withStatus(statusCode) .withHeader(CONTENT_TYPE, APPLICATION) .withBodyFile(fileName))); } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java index b6876bafee2..5c96171ef0d 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/account/AccountServiceTest.java @@ -105,7 +105,7 @@ public void getDynamicTradingFeesSuccess() throws Exception { } private AccountInfo getAccountInfo() throws IOException { - stubGet(ACCOUNT_INFORMATION_JSON, URL_ACCOUNT); + stubGet(ACCOUNT_INFORMATION_JSON, 200, URL_ACCOUNT); return service.getAccountInfo(); } @@ -135,7 +135,7 @@ private String requestDeposit(String responseFileName, int statusCode) throws IO } private List withdrawFundingHistory() throws IOException { - stubGet(WITHDRAWAL_HISTORY_SUCCESS_JSON, URL_WITHDRAWALS); + stubGet(WITHDRAWAL_HISTORY_SUCCESS_JSON, 200, URL_WITHDRAWALS); TradeHistoryParams params = service.createFundingHistoryParams(); if (params instanceof HistoryParamsFundingType) { ((HistoryParamsFundingType) params).setType(FundingRecord.Type.WITHDRAWAL); @@ -145,7 +145,7 @@ private List withdrawFundingHistory() throws IOException { } private List depositFundingHistory() throws IOException { - stubGet(DEPOSIT_HISTORY_SUCCESS_JSON, URL_DEPOSITS); + stubGet(DEPOSIT_HISTORY_SUCCESS_JSON, 200, URL_DEPOSITS); TradeHistoryParams params = service.createFundingHistoryParams(); if (params instanceof HistoryParamsFundingType) { ((HistoryParamsFundingType) params).setType(FundingRecord.Type.DEPOSIT); @@ -155,8 +155,8 @@ private List depositFundingHistory() throws IOException { } private Map tradingFees() throws IOException { - stubGet(FEES_JSON, URL_FEES); - stubGet(SYMBOL_JSON, URL_SYMBOLS); + stubGet(FEES_JSON, 200, URL_FEES); + stubGet(SYMBOL_JSON, 200, URL_SYMBOLS); return service.getDynamicTradingFees(); } diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java index 292f7f156a8..3af24e34fd7 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java @@ -9,6 +9,7 @@ import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.*; +import org.knowm.xchange.exceptions.RateLimitExceededException; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByCurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; @@ -34,7 +35,7 @@ public void init() { @Test(timeout = 2000) public void getOpenOrdersSuccess() throws Exception { - stubGet(ORDERS_JSON, URL_ORDERS); + stubGet(ORDERS_JSON, 200, URL_ORDERS); OpenOrders response = service.getOpenOrders(); assertThat(response).isNotNull(); assertThat(response.getAllOpenOrders()).isNotEmpty(); @@ -91,7 +92,7 @@ public void getTrades() throws Exception { params.setCurrencyPair(CurrencyPair.BTC_USDT); - stubGet(ORDERS_JSON, URL_TRADES); + stubGet(ORDERS_JSON, 200, URL_TRADES); UserTrades response = service.getTradeHistory(params); assertThat(response).isNotNull(); assertThat(response.getUserTrades()).isNotEmpty(); @@ -103,8 +104,8 @@ public void getTrades() throws Exception { @Test(timeout = 2000) public void getOrderSuccess() throws Exception { - stubGet(NEW_ORDER_LIMIT_JSON, URL_ORDERS_BY_ID_1); - stubGet(NEW_ORDER_MARKET_JSON, URL_ORDERS_BY_ID_2); + stubGet(NEW_ORDER_LIMIT_JSON, 200, URL_ORDERS_BY_ID_1); + stubGet(NEW_ORDER_MARKET_JSON, 200, URL_ORDERS_BY_ID_2); Collection response = service.getOrder("11111111", "22222222"); assertThat(response).isNotNull(); assertThat(response).isNotEmpty(); @@ -113,6 +114,16 @@ record -> Assert.assertTrue(record.getOriginalAmount().compareTo(BigDecimal.ZERO } + @Test(timeout = 2000) + public void getOrderFailure() { + stubGet(ORDER_NOT_FOUND_JSON, 404, URL_ORDERS_BY_ID); + Throwable exception = catchThrowable(() -> service.getOrder("111111211")); + assertThat(exception) + .isInstanceOf(RateLimitExceededException.class) + .hasMessage(STATUS_CODE_404); + + } + private String placeLimitOrder() throws IOException { stubPost(NEW_ORDER_LIMIT_JSON, 200, URL_ORDERS); diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java index b14fc2e480a..690e56291e1 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/utils/BlockchainConstants.java @@ -13,10 +13,12 @@ public class BlockchainConstants { public static final String URL_ORDERS = "/v3/exchange/orders"; public static final String URL_ORDERS_BY_ID_1 = "/v3/exchange/orders/11111111"; public static final String URL_ORDERS_BY_ID_2 = "/v3/exchange/orders/22222222"; + public static final String URL_ORDERS_BY_ID = "/v3/exchange/orders/111111211"; public static final String URL_TRADES = "/v3/exchange/trades"; public static final String WITHDRAWAL_ID = "3QXYWgRGX2BPYBpUDBssGbeWEa5zq6snBZ"; public static final String STATUS_CODE_401 = "Unauthorized (HTTP status code: 401)"; public static final String STATUS_CODE_400 = "Bad Request (HTTP status code: 400)"; + public static final String STATUS_CODE_404 = " (HTTP status code: 404)"; public static final String HTTP_CODE_400 = "HTTP status code was not OK: 400"; public static final String ADDRESS = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"; public static final String ADDRESS_DEPOSIT = "3CrbF4Z45fnJs62jFs1p3LkR8KiZSGKJFL"; @@ -25,6 +27,7 @@ public class BlockchainConstants { public static final String NEW_ORDER_MARKET_JSON = "new_order_market.json"; public static final String NEW_ORDER_LIMIT_JSON = "new_order_limit.json"; public static final String NEW_ORDER_STOP_JSON = "new_order_stop.json"; + public static final String ORDER_NOT_FOUND_JSON = "order_not_found.json"; public static final String DEPOSIT_SUCCESS_JSON = "deposit-success.json"; public static final String WITHDRAWAL_SUCCESS_JSON = "withdraw-success.json"; public static final String WITHDRAWAL_FAILURE_JSON = "withdraw-failure.json"; diff --git a/xchange-blockchain/src/test/resources/__files/order_not_found.json b/xchange-blockchain/src/test/resources/__files/order_not_found.json new file mode 100644 index 00000000000..6f7472cac4c --- /dev/null +++ b/xchange-blockchain/src/test/resources/__files/order_not_found.json @@ -0,0 +1 @@ +{"timestamp":"2022-06-16T18:55:35.753+00:00","status":404,"error":"Not Found","message":"","path":"/orders/111111211"} \ No newline at end of file diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index ae0815fc18f..943cf545737 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -14,7 +14,6 @@ import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; import java.io.IOException; -import java.math.BigDecimal; import java.util.Collection; import java.util.Date; @@ -46,7 +45,6 @@ private static void tradeServiceDemo() throws InterruptedException, IOException MarketOrder marketOrder = new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) .originalAmount(AMOUNT) - .cumulativeAmount(STOP_PRICE) .build(); String tradeMarketOrder = tradeService.placeMarketOrder(marketOrder); @@ -57,6 +55,7 @@ private static void tradeServiceDemo() throws InterruptedException, IOException new StopOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) .originalAmount(AMOUNT) .stopPrice(STOP_PRICE) + .limitPrice(STOP_LIMIT) .build(); String tradeStopOrder = tradeService.placeStopOrder(stopOrder); From dd25621a7f1a5e38c3746605c024561de0366a50 Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Thu, 16 Jun 2022 17:06:17 -0300 Subject: [PATCH 06/10] review version 3.2 --- .../blockchain/service/trade/TradeServiceTest.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java index 3af24e34fd7..8b0b38224c9 100644 --- a/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java +++ b/xchange-blockchain/src/test/java/org/knowm/xchange/blockchain/service/trade/TradeServiceTest.java @@ -19,6 +19,7 @@ import java.math.BigDecimal; import java.util.Collection; import java.util.Date; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; @@ -38,8 +39,9 @@ public void getOpenOrdersSuccess() throws Exception { stubGet(ORDERS_JSON, 200, URL_ORDERS); OpenOrders response = service.getOpenOrders(); assertThat(response).isNotNull(); - assertThat(response.getAllOpenOrders()).isNotEmpty(); - Order order = response.getAllOpenOrders().get(0); + List allOrders = response.getAllOpenOrders(); + assertThat(allOrders).isNotEmpty(); + Order order = allOrders.get(0); assertThat(order).isNotNull(); assertThat(order.getOriginalAmount()).isNotNull().isPositive(); assertThat(order.getId()).isEqualTo(ORDER_ID); @@ -95,8 +97,9 @@ public void getTrades() throws Exception { stubGet(ORDERS_JSON, 200, URL_TRADES); UserTrades response = service.getTradeHistory(params); assertThat(response).isNotNull(); - assertThat(response.getUserTrades()).isNotEmpty(); - UserTrade trade = response.getUserTrades().get(0); + List userTrades = response.getUserTrades(); + assertThat(userTrades).isNotEmpty(); + UserTrade trade = userTrades.get(0); assertThat(trade).isNotNull(); assertThat(trade.getOriginalAmount()).isNotNull().isPositive(); assertThat(trade.getPrice()).isNotNull().isPositive(); From 6661d122a12b0ef7d24ee1c4c7c164d117a3700d Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Tue, 21 Jun 2022 16:39:31 -0300 Subject: [PATCH 07/10] review version 3.3 --- .../xchange/blockchain/BlockchainAdapters.java | 9 ++++++--- .../xchange/blockchain/BlockchainConstants.java | 2 ++ .../xchange/blockchain/BlockchainExchange.java | 11 +++++------ .../service/BlockchainTradeService.java | 15 ++++++--------- .../examples/blockchain/BlockchainDemoUtils.java | 5 +++-- .../blockchain/trade/BlockchainTradeDemo.java | 8 +++++--- 6 files changed, 27 insertions(+), 23 deletions(-) diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index d3ef5ba9200..d51ba7f7cdb 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -229,13 +229,16 @@ public static ExchangeMetaData adaptMetaData(Map marke for (Map.Entry entry : markets.entrySet()) { CurrencyPair pair = BlockchainAdapters.toCurrencyPairBySymbol(entry.getValue()); - BigDecimal min_scale = BigDecimal.valueOf(Math.pow(10, (entry.getValue().getMinOrderSizeScale())*-1)); - BigDecimal minAmount = entry.getValue().getMinOrderSize().multiply(min_scale); + BigDecimal minScale = BigDecimal.valueOf(Math.pow(10, (entry.getValue().getMinOrderSizeScale())*-1)); + BigDecimal minAmount = entry.getValue().getMinOrderSize().multiply(minScale); + BigDecimal maxScale = BigDecimal.valueOf(Math.pow(10, (entry.getValue().getMaxOrderSizeScale())*-1)); + BigDecimal maxAmount = entry.getValue().getMaxOrderSize().multiply(maxScale); CurrencyPairMetaData currencyPairMetaData = new CurrencyPairMetaData.Builder() .baseScale(entry.getValue().getBaseCurrencyScale()) + .priceScale(entry.getValue().getCounterCurrencyScale()) .minimumAmount(minAmount) - .maximumAmount(entry.getValue().getMaxOrderSize()) + .maximumAmount(maxAmount) .build(); currencyPairs.put(pair, currencyPairMetaData); currency.put(entry.getValue().getBaseCurrency(), null); diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java index 84e035caafc..2d8cea04546 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainConstants.java @@ -20,6 +20,8 @@ public class BlockchainConstants { public static final String GET_TRADES = "getTrades"; public static final String CURRENCY_PAIR_SYMBOL_FORMAT = "%s-%s"; public static final String X_API_TOKEN = "X-API-Token"; + public static final String XCHANGE = "XChange"; + public static final String X_API_INTEGRATION = "X_API_INTEGRATION"; public static final String WITHDRAWAL_EXCEPTION = "Invalid WithdrawFundsParams parameter. Only DefaultWithdrawFundsParams is supported."; public static final String EXCEPTION_MESSAGE = "Operation failed without any error message"; public static final String FUNDING_RECORD_TYPE_UNSUPPORTED = "Invalid FundingRecord parameter. Only DefaultWithdrawFundsParams is supported."; diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java index 78beb26414d..76198f88441 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainExchange.java @@ -17,8 +17,7 @@ import java.io.IOException; import java.util.Map; -import static org.knowm.xchange.blockchain.BlockchainConstants.NOT_IMPLEMENTED_YET; -import static org.knowm.xchange.blockchain.BlockchainConstants.X_API_TOKEN; +import static org.knowm.xchange.blockchain.BlockchainConstants.*; /** * @author scuevas @@ -33,10 +32,10 @@ public class BlockchainExchange extends BaseExchange { protected void initServices() { this.blockchain = ExchangeRestProxyBuilder .forInterface(BlockchainAuthenticated.class, this.getExchangeSpecification()) - .clientConfigCustomizer(clientConfig -> clientConfig.addDefaultParam( - HeaderParam.class, X_API_TOKEN, - this.getExchangeSpecification().getSecretKey()) - ).build(); + .clientConfigCustomizer(clientConfig -> { + clientConfig.addDefaultParam(HeaderParam.class, X_API_TOKEN, this.getExchangeSpecification().getSecretKey()); + clientConfig.addDefaultParam(HeaderParam.class, X_API_INTEGRATION, XCHANGE); + }).build(); this.accountService = new BlockchainAccountService(this, this.blockchain, this.getResilienceRegistries()); this.tradeService = new BlockchainTradeService(this, this.blockchain, this.getResilienceRegistries()); diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java index 2b3ac761a84..e6dfbe9b767 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -48,9 +48,8 @@ public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { public String placeLimitOrder(LimitOrder limitOrder) throws IOException { try { BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)); - Long id = order.getExOrdId(); - if (id == null) throw new ExchangeException(order.getText()); - return Long.toString(id); + if (order.getOrdStatus().equals(REJECTED)) throw new ExchangeException(order.getText()); + return Long.toString(order.getExOrdId()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); } @@ -60,9 +59,8 @@ public String placeLimitOrder(LimitOrder limitOrder) throws IOException { public String placeMarketOrder(MarketOrder marketOrder) throws IOException { try { BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)); - Long id = order.getExOrdId(); - if (id == null) throw new ExchangeException(order.getText()); - return Long.toString(id); + if (order.getOrdStatus().equals(REJECTED)) throw new ExchangeException(order.getText()); + return Long.toString(order.getExOrdId()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); } @@ -72,9 +70,8 @@ public String placeMarketOrder(MarketOrder marketOrder) throws IOException { public String placeStopOrder(StopOrder stopOrder) throws IOException { try { BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)); - Long id = order.getExOrdId(); - if (id == null) throw new ExchangeException(order.getText()); - return Long.toString(id); + if (order.getOrdStatus().equals(REJECTED)) throw new ExchangeException(order.getText()); + return Long.toString(order.getExOrdId()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); } diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java index b1b69a8f191..740bbc82e47 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java @@ -12,8 +12,9 @@ public class BlockchainDemoUtils { public static final String BENEFICIARY = "8a2e42ee-c94a-4641-9208-9501cbc0fed0"; public static final String SYMBOL = "ADA/USDT"; public static final BigDecimal AMOUNT = new BigDecimal("1.0"); - public static final BigDecimal STOP_PRICE = new BigDecimal("0.01"); - public static final BigDecimal STOP_LIMIT = new BigDecimal("0.005"); + public static final BigDecimal AMOUNT_LIMIT = new BigDecimal("0.01"); + public static final BigDecimal STOP_PRICE = new BigDecimal("1"); + public static final BigDecimal STOP_LIMIT = new BigDecimal("1"); public static Exchange createExchange() { Exchange bcd = ExchangeFactory.INSTANCE.createExchange(BlockchainExchange.class); diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index 943cf545737..3e6800c68d8 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -38,6 +38,7 @@ private static void tradeServiceDemo() throws InterruptedException, IOException .limitPrice(STOP_LIMIT) .build(); + tradeService.verifyOrder(limitOrder); String tradeLimitOrder = tradeService.placeLimitOrder(limitOrder); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeLimitOrder)); @@ -47,13 +48,14 @@ private static void tradeServiceDemo() throws InterruptedException, IOException .originalAmount(AMOUNT) .build(); + tradeService.verifyOrder(marketOrder); String tradeMarketOrder = tradeService.placeMarketOrder(marketOrder); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeMarketOrder)); System.out.println("===== placeStopOrder ====="); StopOrder stopOrder = - new StopOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) - .originalAmount(AMOUNT) + new StopOrder.Builder(Order.OrderType.ASK, CurrencyPair.BTC_USDT) + .originalAmount(AMOUNT_LIMIT) .stopPrice(STOP_PRICE) .limitPrice(STOP_LIMIT) .build(); @@ -91,7 +93,7 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); System.out.println("===== getOrder ====="); - Collection getOrder = tradeService.getOrder(tradeLimitOrder); + Collection getOrder = tradeService.getOrder(openOrders.getOpenOrders().get(0).getId()); System.out.println(OBJECT_MAPPER.writeValueAsString(getOrder)); } } From 54dd86e9f2ce381925ac2a7fbeaee323563b8a76 Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Thu, 23 Jun 2022 09:39:48 -0300 Subject: [PATCH 08/10] review version 3.4 --- .../blockchain/BlockchainAdapters.java | 12 +- .../blockchain/BlockchainAuthenticated.java | 10 ++ .../service/BlockchainTradeService.java | 15 ++- .../service/BlockchainTradeServiceRaw.java | 7 ++ .../blockchain/BlockchainDemoUtils.java | 11 +- .../blockchain/trade/BlockchainTradeDemo.java | 108 ++++++++++++------ 6 files changed, 113 insertions(+), 50 deletions(-) diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index d51ba7f7cdb..83a64487c2f 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -171,7 +171,7 @@ public static BlockchainOrder toBlockchainLimitOrder(LimitOrder limitOrder){ return BlockchainOrder.builder() .ordType(LIMIT) .symbol(toCurrencyPair(limitOrder.getInstrument())) - .side(Order.OrderType.BID.equals(limitOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .side(orderType(limitOrder.getType())) .orderQty(limitOrder.getOriginalAmount()) .price(limitOrder.getLimitPrice()) .clOrdId(generateClOrdId()) @@ -182,7 +182,7 @@ public static BlockchainOrder toBlockchainMarketOrder(MarketOrder marketOrder){ return BlockchainOrder.builder() .ordType(MARKET) .symbol(toCurrencyPair(marketOrder.getInstrument())) - .side(Order.OrderType.BID.equals(marketOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .side(orderType(marketOrder.getType())) .orderQty(marketOrder.getOriginalAmount()) .price(marketOrder.getCumulativeAmount()) .clOrdId(generateClOrdId()) @@ -193,7 +193,7 @@ public static BlockchainOrder toBlockchainStopOrder(StopOrder stopOrder){ return BlockchainOrder.builder() .ordType(STOP) .symbol(toCurrencyPair(stopOrder.getInstrument())) - .side(Order.OrderType.BID.equals(stopOrder.getType())? BUY.toUpperCase() : SELL.toUpperCase()) + .side(orderType(stopOrder.getType())) .orderQty(stopOrder.getOriginalAmount()) .price(stopOrder.getLimitPrice()) .stopPx(stopOrder.getStopPrice()) @@ -241,11 +241,15 @@ public static ExchangeMetaData adaptMetaData(Map marke .maximumAmount(maxAmount) .build(); currencyPairs.put(pair, currencyPairMetaData); - currency.put(entry.getValue().getBaseCurrency(), null); + currency.put(entry.getValue().getBaseCurrency(), new CurrencyMetaData(entry.getValue().getBaseCurrencyScale(),null)); } RateLimit[] rateLimits = {new RateLimit(30, 1, TimeUnit.SECONDS)}; return new ExchangeMetaData(currencyPairs, currency, rateLimits, rateLimits, false); } + + public static String orderType(Order.OrderType type){ + return Order.OrderType.BID.equals(type)? BUY.toUpperCase() : SELL.toUpperCase(); + } } diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java index 1ee518f6c04..301f3d7bd24 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAuthenticated.java @@ -97,6 +97,16 @@ List depositHistory(@QueryParam("from") Long startTime, @GET List getOrders(); + /** + * Get a list orders by symbol + * + * @return live and historic orders, defaulting to live orders. Returns at most 100 results, use timestamp to + * paginate for further results + */ + @Path("/orders") + @GET + List getOrdersBySymbol(@QueryParam("symbol") String symbol) throws IOException, BlockchainException; + /** * Get a specific order * diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java index e6dfbe9b767..2c3b8bb79ac 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeService.java @@ -8,6 +8,7 @@ import org.knowm.xchange.blockchain.dto.trade.BlockchainOrder; import org.knowm.xchange.blockchain.params.BlockchainTradeHistoryParams; import org.knowm.xchange.client.ResilienceRegistries; +import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.account.OpenPositions; import org.knowm.xchange.dto.trade.*; @@ -38,6 +39,14 @@ public OpenOrders getOpenOrders() throws IOException { @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { try { + CurrencyPair currencyPair = null; + if (params instanceof OpenOrdersParamCurrencyPair) { + currencyPair = ((OpenOrdersParamCurrencyPair) params).getCurrencyPair(); + } + + if(currencyPair != null) { + return BlockchainAdapters.toOpenOrders(this.getOrdersBySymbol(BlockchainAdapters.toSymbol(currencyPair))); + } return BlockchainAdapters.toOpenOrders(this.getOrders()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); @@ -48,7 +57,7 @@ public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { public String placeLimitOrder(LimitOrder limitOrder) throws IOException { try { BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainLimitOrder(limitOrder)); - if (order.getOrdStatus().equals(REJECTED)) throw new ExchangeException(order.getText()); + if (REJECTED.equals(order.getOrdStatus())) throw new ExchangeException(order.getText()); return Long.toString(order.getExOrdId()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); @@ -59,7 +68,7 @@ public String placeLimitOrder(LimitOrder limitOrder) throws IOException { public String placeMarketOrder(MarketOrder marketOrder) throws IOException { try { BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainMarketOrder(marketOrder)); - if (order.getOrdStatus().equals(REJECTED)) throw new ExchangeException(order.getText()); + if (REJECTED.equals(order.getOrdStatus())) throw new ExchangeException(order.getText()); return Long.toString(order.getExOrdId()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); @@ -70,7 +79,7 @@ public String placeMarketOrder(MarketOrder marketOrder) throws IOException { public String placeStopOrder(StopOrder stopOrder) throws IOException { try { BlockchainOrder order = this.postOrder(BlockchainAdapters.toBlockchainStopOrder(stopOrder)); - if (order.getOrdStatus().equals(REJECTED)) throw new ExchangeException(order.getText()); + if (REJECTED.equals(order.getOrdStatus())) throw new ExchangeException(order.getText()); return Long.toString(order.getExOrdId()); } catch (BlockchainException e) { throw BlockchainErrorAdapter.adapt(e); diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java index d36b514b8c7..41177e66bf6 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/service/BlockchainTradeServiceRaw.java @@ -25,6 +25,13 @@ protected List getOrders() throws IOException, BlockchainExcept .call(); } + protected List getOrdersBySymbol(String symbol) throws IOException, BlockchainException { + return decorateApiCall(() -> this.blockchainApi.getOrdersBySymbol(symbol)) + .withRetry(retry(GET_ORDERS)) + .withRateLimiter(rateLimiter(ENDPOINT_RATE_LIMIT)) + .call(); + } + protected BlockchainOrder getOrder(String orderId) throws IOException { try { return decorateApiCall(() -> this.blockchainApi.getOrder(orderId)) diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java index 740bbc82e47..3860d2e76ab 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/BlockchainDemoUtils.java @@ -10,11 +10,12 @@ public class BlockchainDemoUtils { public static final Long END_TIME = 12 * 30 * 24 * 60 * 60 * 1000L; public static final String BENEFICIARY = "8a2e42ee-c94a-4641-9208-9501cbc0fed0"; - public static final String SYMBOL = "ADA/USDT"; - public static final BigDecimal AMOUNT = new BigDecimal("1.0"); - public static final BigDecimal AMOUNT_LIMIT = new BigDecimal("0.01"); - public static final BigDecimal STOP_PRICE = new BigDecimal("1"); - public static final BigDecimal STOP_LIMIT = new BigDecimal("1"); + public static final String SYMBOL = "BTC/USDT"; + public static final BigDecimal AMOUNT = new BigDecimal("0.01"); + public static final BigDecimal AMOUNT_LIMIT = new BigDecimal("10"); + public static final BigDecimal STOP_PRICE = new BigDecimal("0.4"); + public static final BigDecimal STOP_LIMIT = new BigDecimal("2000"); + public static final BigDecimal STOP_LIMIT_PRICE = new BigDecimal("0.5"); public static Exchange createExchange() { Exchange bcd = ExchangeFactory.INSTANCE.createExchange(BlockchainExchange.class); diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index 3e6800c68d8..0c1dbfab217 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.SerializationFeature; import org.knowm.xchange.Exchange; import org.knowm.xchange.blockchain.params.BlockchainTradeHistoryParams; +import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.*; @@ -22,6 +23,8 @@ public class BlockchainTradeDemo { private static final Exchange BLOCKCHAIN_EXCHANGE = BlockchainDemoUtils.createExchange(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); + private static final CurrencyPair ustUsd = new CurrencyPair(Currency.USDT, Currency.USD); + private static final TradeService tradeService = BLOCKCHAIN_EXCHANGE.getTradeService(); public static void main(String[] args) throws IOException, InterruptedException { System.out.println("===== TRADE SERVICE ====="); @@ -29,11 +32,56 @@ public static void main(String[] args) throws IOException, InterruptedException } private static void tradeServiceDemo() throws InterruptedException, IOException { - TradeService tradeService = BLOCKCHAIN_EXCHANGE.getTradeService(); - System.out.println("===== placeLimitOrder ====="); + String limitOrderId = limitOrder(); + System.out.println("===== placeMarketOrder ====="); + String marketOrderId = marketOrder(); + System.out.println("===== placeStopOrder ====="); + String stopOrderId = stopOrder(); + + Thread.sleep(5000); + + System.out.println("===== getOpenOrders by symbol ====="); + final OpenOrdersParamCurrencyPair openOrdersParamsBtcUsd = + (OpenOrdersParamCurrencyPair) tradeService.createOpenOrdersParams(); + openOrdersParamsBtcUsd.setCurrencyPair(CurrencyPair.BTC_USDT); + OpenOrders openOrdersParams = tradeService.getOpenOrders(openOrdersParamsBtcUsd); + System.out.println(OBJECT_MAPPER.writeValueAsString(openOrdersParams)); + + System.out.println("===== getOpenOrders ====="); + OpenOrders openOrders = tradeService.getOpenOrders(); + System.out.println(OBJECT_MAPPER.writeValueAsString(openOrders)); + + System.out.println("===== getTradeHistory ====="); + BlockchainTradeHistoryParams params = (BlockchainTradeHistoryParams) tradeService.createTradeHistoryParams(); + ((TradeHistoryParamsTimeSpan) params).setStartTime( + new Date(System.currentTimeMillis() - END_TIME)); + + params.setCurrencyPair(ustUsd); + + UserTrades tradeHistory = tradeService.getTradeHistory(params); + System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); + + System.out.println("===== getOrder ====="); + getOrderById(limitOrderId); + getOrderById(marketOrderId); + getOrderById(stopOrderId); + + System.out.println("===== cancelOrder by id ====="); + System.out.println("Canceling returned " + cancelOrderById(limitOrderId)); + System.out.println("Canceling returned " + cancelOrderById(marketOrderId)); + System.out.println("Canceling returned " + cancelOrderById(stopOrderId)); + + System.out.println("===== cancelOrder by symbol ====="); + CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair(SYMBOL); + boolean cancelAllOrderByCurrency = tradeService.cancelOrder(cancelOrderByCurrencyPair); + System.out.println("Canceling returned " + cancelAllOrderByCurrency); + } + + + public static String limitOrder() throws IOException { LimitOrder limitOrder = - new LimitOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) + new LimitOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_USDT) .originalAmount(AMOUNT) .limitPrice(STOP_LIMIT) .build(); @@ -42,9 +90,12 @@ private static void tradeServiceDemo() throws InterruptedException, IOException String tradeLimitOrder = tradeService.placeLimitOrder(limitOrder); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeLimitOrder)); - System.out.println("===== placeMarketOrder ====="); + return tradeLimitOrder; + } + + public static String marketOrder() throws IOException { MarketOrder marketOrder = - new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.ADA_USDT) + new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_USDT) .originalAmount(AMOUNT) .build(); @@ -52,48 +103,29 @@ private static void tradeServiceDemo() throws InterruptedException, IOException String tradeMarketOrder = tradeService.placeMarketOrder(marketOrder); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeMarketOrder)); - System.out.println("===== placeStopOrder ====="); + return tradeMarketOrder; + } + + public static String stopOrder() throws IOException { StopOrder stopOrder = - new StopOrder.Builder(Order.OrderType.ASK, CurrencyPair.BTC_USDT) + new StopOrder.Builder(Order.OrderType.ASK, ustUsd) .originalAmount(AMOUNT_LIMIT) .stopPrice(STOP_PRICE) - .limitPrice(STOP_LIMIT) + .limitPrice(STOP_LIMIT_PRICE) .build(); String tradeStopOrder = tradeService.placeStopOrder(stopOrder); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeStopOrder)); - Thread.sleep(5000); - System.out.println("===== getOpenOrders ====="); - - final OpenOrdersParamCurrencyPair openOrdersParamsBtcUsd = - (OpenOrdersParamCurrencyPair) tradeService.createOpenOrdersParams(); - openOrdersParamsBtcUsd.setCurrencyPair(CurrencyPair.ADA_USDT); - OpenOrders openOrdersParams = tradeService.getOpenOrders(openOrdersParamsBtcUsd); - System.out.println(OBJECT_MAPPER.writeValueAsString(openOrdersParams)); - - OpenOrders openOrders = tradeService.getOpenOrders(); - System.out.println(OBJECT_MAPPER.writeValueAsString(openOrders)); - - - System.out.println("===== cancelOrder ====="); - CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair(SYMBOL); - boolean cancelAllOrderByCurrency = tradeService.cancelOrder(cancelOrderByCurrencyPair); - System.out.println("Canceling returned " + cancelAllOrderByCurrency); - - System.out.println("===== getTradeHistory ====="); - - BlockchainTradeHistoryParams params = (BlockchainTradeHistoryParams) tradeService.createTradeHistoryParams(); - ((TradeHistoryParamsTimeSpan) params).setStartTime( - new Date(System.currentTimeMillis() - END_TIME)); - - params.setCurrencyPair(CurrencyPair.ADA_USDT); - - UserTrades tradeHistory = tradeService.getTradeHistory(params); - System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); + return tradeStopOrder; + } - System.out.println("===== getOrder ====="); - Collection getOrder = tradeService.getOrder(openOrders.getOpenOrders().get(0).getId()); + public static void getOrderById(String idOrder) throws IOException { + Collection getOrder = tradeService.getOrder(idOrder); System.out.println(OBJECT_MAPPER.writeValueAsString(getOrder)); } + + public static Boolean cancelOrderById(String id) throws IOException { + return tradeService.cancelOrder(id); + } } From 0784d620e5726c83597b59b7fcbf306938a43879 Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Thu, 23 Jun 2022 13:12:24 -0300 Subject: [PATCH 09/10] review version 3.5 --- .../org/knowm/xchange/blockchain/BlockchainAdapters.java | 8 ++++---- .../examples/blockchain/trade/BlockchainTradeDemo.java | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java index 83a64487c2f..e8609b7d73c 100644 --- a/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java +++ b/xchange-blockchain/src/main/java/org/knowm/xchange/blockchain/BlockchainAdapters.java @@ -171,7 +171,7 @@ public static BlockchainOrder toBlockchainLimitOrder(LimitOrder limitOrder){ return BlockchainOrder.builder() .ordType(LIMIT) .symbol(toCurrencyPair(limitOrder.getInstrument())) - .side(orderType(limitOrder.getType())) + .side(getOrderType(limitOrder.getType())) .orderQty(limitOrder.getOriginalAmount()) .price(limitOrder.getLimitPrice()) .clOrdId(generateClOrdId()) @@ -182,7 +182,7 @@ public static BlockchainOrder toBlockchainMarketOrder(MarketOrder marketOrder){ return BlockchainOrder.builder() .ordType(MARKET) .symbol(toCurrencyPair(marketOrder.getInstrument())) - .side(orderType(marketOrder.getType())) + .side(getOrderType(marketOrder.getType())) .orderQty(marketOrder.getOriginalAmount()) .price(marketOrder.getCumulativeAmount()) .clOrdId(generateClOrdId()) @@ -193,7 +193,7 @@ public static BlockchainOrder toBlockchainStopOrder(StopOrder stopOrder){ return BlockchainOrder.builder() .ordType(STOP) .symbol(toCurrencyPair(stopOrder.getInstrument())) - .side(orderType(stopOrder.getType())) + .side(getOrderType(stopOrder.getType())) .orderQty(stopOrder.getOriginalAmount()) .price(stopOrder.getLimitPrice()) .stopPx(stopOrder.getStopPrice()) @@ -249,7 +249,7 @@ public static ExchangeMetaData adaptMetaData(Map marke return new ExchangeMetaData(currencyPairs, currency, rateLimits, rateLimits, false); } - public static String orderType(Order.OrderType type){ + public static String getOrderType(Order.OrderType type){ return Order.OrderType.BID.equals(type)? BUY.toUpperCase() : SELL.toUpperCase(); } } diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index 0c1dbfab217..3012e45672a 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -23,7 +23,7 @@ public class BlockchainTradeDemo { private static final Exchange BLOCKCHAIN_EXCHANGE = BlockchainDemoUtils.createExchange(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); - private static final CurrencyPair ustUsd = new CurrencyPair(Currency.USDT, Currency.USD); + private static final CurrencyPair usdtUsd = new CurrencyPair(Currency.USDT, Currency.USD); private static final TradeService tradeService = BLOCKCHAIN_EXCHANGE.getTradeService(); public static void main(String[] args) throws IOException, InterruptedException { @@ -57,7 +57,7 @@ private static void tradeServiceDemo() throws InterruptedException, IOException ((TradeHistoryParamsTimeSpan) params).setStartTime( new Date(System.currentTimeMillis() - END_TIME)); - params.setCurrencyPair(ustUsd); + params.setCurrencyPair(usdtUsd); UserTrades tradeHistory = tradeService.getTradeHistory(params); System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); @@ -108,7 +108,7 @@ public static String marketOrder() throws IOException { public static String stopOrder() throws IOException { StopOrder stopOrder = - new StopOrder.Builder(Order.OrderType.ASK, ustUsd) + new StopOrder.Builder(Order.OrderType.ASK, usdtUsd) .originalAmount(AMOUNT_LIMIT) .stopPrice(STOP_PRICE) .limitPrice(STOP_LIMIT_PRICE) From ea94f4bcfcc1c7621abbd9652d26d1e2904f3c25 Mon Sep 17 00:00:00 2001 From: scuevas-bc Date: Thu, 23 Jun 2022 15:52:19 -0300 Subject: [PATCH 10/10] review version 3.6 --- .../blockchain/trade/BlockchainTradeDemo.java | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java index 3012e45672a..3c28c7cfb86 100644 --- a/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java +++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/blockchain/trade/BlockchainTradeDemo.java @@ -33,12 +33,16 @@ public static void main(String[] args) throws IOException, InterruptedException private static void tradeServiceDemo() throws InterruptedException, IOException { System.out.println("===== placeLimitOrder ====="); - String limitOrderId = limitOrder(); + executeOrder(limitOrder()); + System.out.println("===== placeMarketOrder ====="); - String marketOrderId = marketOrder(); + executeOrder(marketOrder()); + System.out.println("===== placeStopOrder ====="); - String stopOrderId = stopOrder(); + executeOrder(stopOrder()); + } + public static void executeOrder(String orderId) throws InterruptedException, IOException{ Thread.sleep(5000); System.out.println("===== getOpenOrders by symbol ====="); @@ -63,14 +67,11 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println(OBJECT_MAPPER.writeValueAsString(tradeHistory)); System.out.println("===== getOrder ====="); - getOrderById(limitOrderId); - getOrderById(marketOrderId); - getOrderById(stopOrderId); + Collection getOrder = tradeService.getOrder(orderId); + System.out.println(OBJECT_MAPPER.writeValueAsString(getOrder)); System.out.println("===== cancelOrder by id ====="); - System.out.println("Canceling returned " + cancelOrderById(limitOrderId)); - System.out.println("Canceling returned " + cancelOrderById(marketOrderId)); - System.out.println("Canceling returned " + cancelOrderById(stopOrderId)); + System.out.println("Canceling returned " + tradeService.cancelOrder(orderId)); System.out.println("===== cancelOrder by symbol ====="); CancelOrderByCurrencyPair cancelOrderByCurrencyPair = () -> new CurrencyPair(SYMBOL); @@ -78,7 +79,6 @@ private static void tradeServiceDemo() throws InterruptedException, IOException System.out.println("Canceling returned " + cancelAllOrderByCurrency); } - public static String limitOrder() throws IOException { LimitOrder limitOrder = new LimitOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_USDT) @@ -119,13 +119,4 @@ public static String stopOrder() throws IOException { return tradeStopOrder; } - - public static void getOrderById(String idOrder) throws IOException { - Collection getOrder = tradeService.getOrder(idOrder); - System.out.println(OBJECT_MAPPER.writeValueAsString(getOrder)); - } - - public static Boolean cancelOrderById(String id) throws IOException { - return tradeService.cancelOrder(id); - } }