Search in sources :

Example 1 with OrderDTO

use of tech.cassandre.trading.bot.dto.trade.OrderDTO in project cassandre-trading-bot by cassandre-tech.

the class BasicTa4jCassandreStrategyTestMock method tradeService.

@Bean
@Primary
public TradeService tradeService() {
    TradeService service = mock(TradeService.class);
    // Returns three values.
    Set<OrderDTO> reply = new LinkedHashSet<>();
    // Order 01.
    reply.add(OrderDTO.builder().orderId("000001").type(BID).strategy(strategyDTO).currencyPair(BTC_USDT).build());
    // Order 02.
    reply.add(OrderDTO.builder().orderId("000002").type(BID).strategy(strategyDTO).currencyPair(BTC_USDT).build());
    // Order 03.
    reply.add(OrderDTO.builder().orderId("000003").type(BID).strategy(strategyDTO).currencyPair(BTC_USDT).build());
    // Order 04.
    reply.add(OrderDTO.builder().orderId("000004").type(BID).strategy(strategyDTO).currencyPair(BTC_USDT).build());
    given(service.getOrders()).willReturn(reply);
    // Returns three values for getTrades().
    Set<TradeDTO> replyGetTrades = new LinkedHashSet<>();
    // Trade 01.
    replyGetTrades.add(TradeDTO.builder().tradeId("0000001").orderId("000001").type(BID).currencyPair(BTC_USDT).build());
    // Trade 02.
    replyGetTrades.add(TradeDTO.builder().tradeId("0000002").orderId("000002").type(BID).currencyPair(BTC_USDT).build());
    // Trade 03.
    replyGetTrades.add(TradeDTO.builder().tradeId("0000003").orderId("000003").type(BID).currencyPair(BTC_USDT).build());
    given(service.getTrades()).willReturn(replyGetTrades);
    return service;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) TradeService(tech.cassandre.trading.bot.service.TradeService) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) Primary(org.springframework.context.annotation.Primary) Bean(org.springframework.context.annotation.Bean)

Example 2 with OrderDTO

use of tech.cassandre.trading.bot.dto.trade.OrderDTO in project cassandre-trading-bot by cassandre-tech.

the class TradeServiceTest method checkCreateBuyLimitOrder.

@Test
@Tag("integration")
@DisplayName("Check creates a buy limit order")
public void checkCreateBuyLimitOrder() {
    final CurrencyPairDTO cp = new CurrencyPairDTO(ETH, BTC);
    // =============================================================================================================
    // Making a buy limit order (Buy 0.0001 ETH).
    final OrderCreationResultDTO result1 = strategy.createBuyLimitOrder(cp, new BigDecimal("0.0001"), new BigDecimal("0.1"));
    assertTrue(result1.isSuccessful());
    assertNull(result1.getErrorMessage());
    assertNull(result1.getException());
    assertNotNull(result1.getOrder().getOrderId());
    // =============================================================================================================
    // Getting a non-existing order.
    assertFalse(tradeService.getOrders().stream().anyMatch(o -> o.getOrderId().equals("")));
    // =============================================================================================================
    // Getting the order and testing the data.
    final Optional<OrderDTO> order1 = tradeService.getOrders().stream().filter(o -> o.getOrderId().equals(result1.getOrder().getOrderId())).findFirst();
    assertTrue(order1.isPresent());
    assertNotNull(order1.get().getOrderId());
    assertEquals(result1.getOrder().getOrderId(), order1.get().getOrderId());
    assertEquals(BID, order1.get().getType());
    assertEquals(cp, order1.get().getCurrencyPair());
    assertEquals(0, order1.get().getAmount().getValue().compareTo(new BigDecimal("0.0001")));
    assertEquals(cp.getBaseCurrency(), order1.get().getAmount().getCurrency());
    assertEquals(0, order1.get().getLimitPrice().getValue().compareTo(new BigDecimal("0.000001")));
    assertEquals(cp.getQuoteCurrency(), order1.get().getLimitPrice().getCurrency());
    assertNull(order1.get().getLeverage());
    assertNull(order1.get().getUserReference());
    assertNotNull(order1.get().getTimestamp());
    assertTrue(order1.get().getTimestamp().isAfter(ZonedDateTime.now().minusMinutes(1)));
    assertTrue(order1.get().getTimestamp().isBefore(ZonedDateTime.now().plusMinutes(1)));
    // Cancel the order.
    tradeService.cancelOrder(result1.getOrder().getOrderId());
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) BID(tech.cassandre.trading.bot.dto.trade.OrderTypeDTO.BID) ZonedDateTime(java.time.ZonedDateTime) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Autowired(org.springframework.beans.factory.annotation.Autowired) ActiveProfiles(org.springframework.test.context.ActiveProfiles) TradeService(tech.cassandre.trading.bot.service.TradeService) Disabled(org.junit.jupiter.api.Disabled) BaseTest(tech.cassandre.trading.bot.test.util.junit.BaseTest) TestableCassandreStrategy(tech.cassandre.trading.bot.test.util.strategies.TestableCassandreStrategy) BigDecimal(java.math.BigDecimal) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) BTC(tech.cassandre.trading.bot.dto.util.CurrencyDTO.BTC) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) Tag(org.junit.jupiter.api.Tag) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ETH(tech.cassandre.trading.bot.dto.util.CurrencyDTO.ETH) Awaitility.await(org.awaitility.Awaitility.await) TestPropertySource(org.springframework.test.context.TestPropertySource) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) DisplayName(org.junit.jupiter.api.DisplayName) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) OrderCreationResultDTO(tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO) Optional(java.util.Optional) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) OrderCreationResultDTO(tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO) BigDecimal(java.math.BigDecimal) BaseTest(tech.cassandre.trading.bot.test.util.junit.BaseTest) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) DisplayName(org.junit.jupiter.api.DisplayName) Tag(org.junit.jupiter.api.Tag)

Example 3 with OrderDTO

use of tech.cassandre.trading.bot.dto.trade.OrderDTO in project cassandre-trading-bot by cassandre-tech.

the class TradeServiceXChangeImplementation method createLimitOrder.

/**
 * Creates limit order.
 *
 * @param strategy     strategy
 * @param orderTypeDTO order type
 * @param currencyPair currency pair
 * @param amount       amount
 * @param limitPrice   In a BID this is the highest acceptable price, in an ASK this is the lowest acceptable price
 * @return order creation result
 */
private OrderCreationResultDTO createLimitOrder(final GenericCassandreStrategy strategy, final OrderTypeDTO orderTypeDTO, final CurrencyPairDTO currencyPair, final BigDecimal amount, final BigDecimal limitPrice) {
    try {
        // Making the order.
        LimitOrder l = new LimitOrder(UTIL_MAPPER.mapToOrderType(orderTypeDTO), amount.setScale(currencyPair.getBaseCurrencyPrecision(), FLOOR), CURRENCY_MAPPER.mapToCurrencyPair(currencyPair), getGeneratedOrderId(), null, limitPrice);
        logger.debug("Sending limit order: {} - {} - {}", orderTypeDTO, currencyPair, amount.setScale(currencyPair.getBaseCurrencyPrecision(), FLOOR));
        // Sending & creating the order.
        OrderDTO order = OrderDTO.builder().orderId(tradeService.placeLimitOrder(l)).type(orderTypeDTO).strategy(strategy.getStrategyDTO()).currencyPair(currencyPair).amount(CurrencyAmountDTO.builder().value(amount).currency(currencyPair.getBaseCurrency()).build()).cumulativeAmount(CurrencyAmountDTO.builder().value(amount).currency(currencyPair.getBaseCurrency()).build()).averagePrice(CurrencyAmountDTO.builder().value(strategy.getLastPriceForCurrencyPair(currencyPair)).currency(currencyPair.getQuoteCurrency()).build()).limitPrice(CurrencyAmountDTO.builder().value(limitPrice).currency(currencyPair.getQuoteCurrency()).build()).marketPrice(CurrencyAmountDTO.builder().value(strategy.getLastPriceForCurrencyPair(currencyPair)).currency(currencyPair.getQuoteCurrency()).build()).status(PENDING_NEW).timestamp(ZonedDateTime.now()).build();
        // We save the order.
        Optional<Order> savedOrder = orderRepository.findByOrderId(order.getOrderId());
        if (savedOrder.isEmpty()) {
            savedOrder = Optional.of(orderRepository.save(ORDER_MAPPER.mapToOrder(order)));
        }
        final OrderCreationResultDTO result = new OrderCreationResultDTO(ORDER_MAPPER.mapToOrderDTO(savedOrder.get()));
        logger.debug("Order creation result: {}", result);
        return result;
    } catch (Exception e) {
        final String error = "TradeService - Error calling createLimitOrder for " + amount + " " + currencyPair + ": " + e.getMessage();
        e.printStackTrace();
        logger.error(error);
        return new OrderCreationResultDTO(error, e);
    }
}
Also used : Order(tech.cassandre.trading.bot.domain.Order) LimitOrder(org.knowm.xchange.dto.trade.LimitOrder) MarketOrder(org.knowm.xchange.dto.trade.MarketOrder) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) OrderCreationResultDTO(tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO) LimitOrder(org.knowm.xchange.dto.trade.LimitOrder) NotAvailableFromExchangeException(org.knowm.xchange.exceptions.NotAvailableFromExchangeException) IOException(java.io.IOException)

Example 4 with OrderDTO

use of tech.cassandre.trading.bot.dto.trade.OrderDTO in project cassandre-trading-bot by cassandre-tech.

the class PositionServiceTest method checkOpeningOrderFailure.

@Test
@DisplayName("Check opening order failure")
public void checkOpeningOrderFailure() {
    // =============================================================================================================
    // Creates a position. Then send an order update with an error.
    // The position must end up being in OPENING_FAILURE
    // Creates position 1 (ETH/BTC, 0.0001, 10% stop gain).
    final PositionCreationResultDTO p1 = strategy.createLongPosition(ETH_BTC, new BigDecimal("0.0001"), PositionRulesDTO.builder().stopGainPercentage(10f).build());
    assertTrue(p1.isSuccessful());
    assertEquals(1, p1.getPosition().getUid());
    assertEquals("ORDER00010", p1.getPosition().getOpeningOrder().getOrderId());
    assertNull(p1.getErrorMessage());
    assertNull(p1.getException());
    assertTrue(positionService.getPositionByUid(1).isPresent());
    assertEquals(OPENING, positionService.getPositionByUid(1).get().getStatus());
    long position1Uid = p1.getPosition().getUid();
    // We retrieve the order from the service, and we wait for the order to update the position.
    // Only one order updates (we don't send the PENDING_NOW order in flux).
    // Two positions updates because order status change from PENDING_NEW to NEW.
    orderFlux.update();
    await().untilAsserted(() -> assertEquals(1, strategy.getOrdersUpdatesReceived().size()));
    await().untilAsserted(() -> assertEquals(2, strategy.getPositionsUpdatesReceived().size()));
    // Position 1.
    Optional<PositionDTO> position1 = strategy.getPositionByPositionId(position1Uid);
    assertTrue(position1.isPresent());
    // Opening order.
    OrderDTO p1OpeningOrder = position1.get().getOpeningOrder();
    assertNotNull(p1OpeningOrder);
    assertEquals("ORDER00010", p1OpeningOrder.getOrderId());
    assertEquals(BID, p1OpeningOrder.getType());
    assertEquals(ETH_BTC, p1OpeningOrder.getCurrencyPair());
    assertEquals(NEW, p1OpeningOrder.getStatus());
    // Closing order.
    OrderDTO p1ClosingOrder = position1.get().getClosingOrder();
    assertNull(p1ClosingOrder);
    // =============================================================================================================
    // An update for opening order ORDER00020 (position 2) arrives and change status with an error !
    OrderDTO order00010 = OrderDTO.builder().orderId("ORDER00010").type(BID).strategy(strategyDTO).amount(new CurrencyAmountDTO("0.00012", ETH_BTC.getBaseCurrency())).currencyPair(ETH_BTC).timestamp(ZonedDateTime.now()).status(STOPPED).build();
    orderFlux.emitValue(order00010);
    // The position should move to failure.
    await().untilAsserted(() -> assertEquals(OPENING_FAILURE, getPositionDTO(position1Uid).getStatus()));
    assertEquals("Position 1 - Opening failure", getPositionDTO(position1Uid).getDescription());
}
Also used : PositionCreationResultDTO(tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO) CurrencyAmountDTO(tech.cassandre.trading.bot.dto.util.CurrencyAmountDTO) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) BigDecimal(java.math.BigDecimal) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) BaseTest(tech.cassandre.trading.bot.test.util.junit.BaseTest) DisplayName(org.junit.jupiter.api.DisplayName)

Example 5 with OrderDTO

use of tech.cassandre.trading.bot.dto.trade.OrderDTO in project cassandre-trading-bot by cassandre-tech.

the class BasicCassandreStrategyTestMock method tradeService.

@Bean
@Primary
public TradeService tradeService() {
    TradeService service = mock(TradeService.class);
    // Returns three values for getOpenOrders().
    Set<OrderDTO> replyGetOpenOrders = new LinkedHashSet<>();
    // Order 01.
    replyGetOpenOrders.add(OrderDTO.builder().orderId("000001").type(BID).strategy(strategyDTO).currencyPair(ETH_BTC).timestamp(createZonedDateTime("01-01-2020")).build());
    // Order 02.
    replyGetOpenOrders.add(OrderDTO.builder().orderId("000002").type(BID).strategy(strategyDTO).currencyPair(ETH_BTC).timestamp(createZonedDateTime("01-02-2020")).build());
    // Order 03.
    replyGetOpenOrders.add(OrderDTO.builder().orderId("000003").type(BID).strategy(strategyDTO).currencyPair(ETH_BTC).timestamp(createZonedDateTime("01-03-2020")).build());
    given(service.getOrders()).willReturn(replyGetOpenOrders);
    // Returns three values for getTrades().
    Set<TradeDTO> replyGetTrades = new LinkedHashSet<>();
    // Trade 01.
    replyGetTrades.add(TradeDTO.builder().tradeId("0000001").orderId("000001").type(BID).currencyPair(ETH_BTC).timestamp(createZonedDateTime("01-01-2020")).build());
    // Trade 02.
    replyGetTrades.add(TradeDTO.builder().tradeId("0000002").orderId("000001").type(BID).currencyPair(ETH_BTC).timestamp(createZonedDateTime("01-02-2020")).build());
    // Trade 03.
    replyGetTrades.add(TradeDTO.builder().tradeId("0000003").orderId("000001").type(BID).currencyPair(ETH_BTC).timestamp(createZonedDateTime("01-03-2020")).build());
    given(service.getTrades()).willReturn(replyGetTrades);
    return service;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) TradeService(tech.cassandre.trading.bot.service.TradeService) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) Primary(org.springframework.context.annotation.Primary) Bean(org.springframework.context.annotation.Bean)

Aggregations

OrderDTO (tech.cassandre.trading.bot.dto.trade.OrderDTO)25 DisplayName (org.junit.jupiter.api.DisplayName)15 Test (org.junit.jupiter.api.Test)15 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)13 BaseTest (tech.cassandre.trading.bot.test.util.junit.BaseTest)12 BigDecimal (java.math.BigDecimal)11 CurrencyAmountDTO (tech.cassandre.trading.bot.dto.util.CurrencyAmountDTO)10 OrderCreationResultDTO (tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO)9 TradeDTO (tech.cassandre.trading.bot.dto.trade.TradeDTO)9 TradeService (tech.cassandre.trading.bot.service.TradeService)8 Order (tech.cassandre.trading.bot.domain.Order)7 IOException (java.io.IOException)6 LimitOrder (org.knowm.xchange.dto.trade.LimitOrder)6 MarketOrder (org.knowm.xchange.dto.trade.MarketOrder)6 NotAvailableFromExchangeException (org.knowm.xchange.exceptions.NotAvailableFromExchangeException)6 ZonedDateTime (java.time.ZonedDateTime)5 Optional (java.util.Optional)5 Awaitility.await (org.awaitility.Awaitility.await)5 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)5 Assertions.assertNotNull (org.junit.jupiter.api.Assertions.assertNotNull)5