Search in sources :

Example 1 with Position

use of tech.cassandre.trading.bot.domain.Position in project cassandre-trading-bot by cassandre-tech.

the class PositionServiceCassandreImplementation method createPosition.

/**
 * Creates a position.
 *
 * @param strategy     strategy
 * @param type         long or short
 * @param currencyPair currency pair
 * @param amount       amount
 * @param rules        rules
 * @return position creation result
 */
public final PositionCreationResultDTO createPosition(final GenericCassandreStrategy strategy, final PositionTypeDTO type, final CurrencyPairDTO currencyPair, final BigDecimal amount, final PositionRulesDTO rules) {
    logger.debug("Creating a {} position for {} on {} with the rules: {}", type.toString().toLowerCase(Locale.ROOT), amount, currencyPair, rules);
    // It's forbidden to create a position with a too small amount.
    if (amount == null || MINIMUM_AMOUNT_FOR_POSITION.compareTo(amount) > 0) {
        logger.error("Impossible to create a position for such a small amount");
        return new PositionCreationResultDTO("Impossible to create a position for such a small amount: " + amount, null);
    }
    // =============================================================================================================
    // Creates the order.
    final OrderCreationResultDTO orderCreationResult;
    if (type == LONG) {
        // Long position - we buy.
        orderCreationResult = tradeService.createBuyMarketOrder(strategy, currencyPair, amount);
    } else {
        // Short position - we sell.
        orderCreationResult = tradeService.createSellMarketOrder(strategy, currencyPair, amount);
    }
    // If it works, creates the position.
    if (orderCreationResult.isSuccessful()) {
        // =========================================================================================================
        // Creates the position in database.
        Position position = new Position();
        position.setStrategy(STRATEGY_MAPPER.mapToStrategy(strategy.getStrategyDTO()));
        position = positionRepository.save(position);
        // =========================================================================================================
        // Creates the position dto.
        PositionDTO p = new PositionDTO(position.getId(), type, strategy.getStrategyDTO(), currencyPair, amount, orderCreationResult.getOrder(), rules);
        positionRepository.save(POSITION_MAPPER.mapToPosition(p));
        logger.debug("Position {} opened with order {}", p.getPositionId(), orderCreationResult.getOrder().getOrderId());
        // =========================================================================================================
        // Creates the result & emit the position.
        positionFlux.emitValue(p);
        return new PositionCreationResultDTO(p);
    } else {
        logger.error("Position creation failure: {}", orderCreationResult.getErrorMessage());
        return new PositionCreationResultDTO(orderCreationResult.getErrorMessage(), orderCreationResult.getException());
    }
}
Also used : PositionCreationResultDTO(tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO) Position(tech.cassandre.trading.bot.domain.Position) OrderCreationResultDTO(tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO)

Example 2 with Position

use of tech.cassandre.trading.bot.domain.Position in project cassandre-trading-bot by cassandre-tech.

the class PositionServiceCassandreImplementation method closePosition.

@Override
public final OrderCreationResultDTO closePosition(final GenericCassandreStrategy strategy, final long id, final TickerDTO ticker) {
    final Optional<Position> position = positionRepository.findById(id);
    if (position.isPresent()) {
        final PositionDTO positionDTO = POSITION_MAPPER.mapToPositionDTO(position.get());
        final OrderCreationResultDTO orderCreationResult;
        if (positionDTO.getType() == LONG) {
            // Long - We just sell.
            orderCreationResult = tradeService.createSellMarketOrder(strategy, positionDTO.getCurrencyPair(), positionDTO.getAmount().getValue());
        } else {
            // Short - We buy back with the money we get from the original selling.
            // On opening, we had:
            // CP2: ETH/USDT - 1 ETH costs 10 USDT - We sold 1 ETH, and it will give us 10 USDT.
            // We will use those 10 USDT to buy back ETH when the rule is triggered.
            // CP2: ETH/USDT - 1 ETH costs 2 USDT - We buy 5 ETH, and it will cost us 10 USDT.
            // We can now use those 10 USDT to buy 5 ETH (amount sold / price).
            final BigDecimal amountToBuy = positionDTO.getAmountToLock().getValue().divide(ticker.getLast(), HALF_UP).setScale(SCALE, FLOOR);
            orderCreationResult = tradeService.createBuyMarketOrder(strategy, positionDTO.getCurrencyPair(), amountToBuy);
        }
        if (orderCreationResult.isSuccessful()) {
            positionDTO.closePositionWithOrder(orderCreationResult.getOrder());
            logger.debug("Position {} closed with order {}", positionDTO.getPositionId(), orderCreationResult.getOrder().getOrderId());
        } else {
            logger.error("Position {} not closed: {}", positionDTO.getPositionId(), orderCreationResult.getErrorMessage());
        }
        positionFlux.emitValue(positionDTO);
        return orderCreationResult;
    } else {
        logger.error("Impossible to close position {} because we couldn't find it in database", id);
        return new OrderCreationResultDTO("Impossible to close position " + id + " because we couldn't find it in database", null);
    }
}
Also used : Position(tech.cassandre.trading.bot.domain.Position) OrderCreationResultDTO(tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) BigDecimal(java.math.BigDecimal)

Example 3 with Position

use of tech.cassandre.trading.bot.domain.Position in project cassandre-trading-bot by cassandre-tech.

the class PositionTest method checkSavedNewPosition.

@Test
@DisplayName("Check how a new position is saved")
public void checkSavedNewPosition() {
    // First ticker emitted for dry mode - MANDATORY.
    tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).timestamp(createZonedDateTime(1)).last(new BigDecimal("0.2")).build());
    await().untilAsserted(() -> assertEquals(1, strategy.getLastTickers().size()));
    // =============================================================================================================
    // Creates a position with ID 6 - waiting for order DRY_ORDER_000000001.
    long positionCount = positionRepository.count();
    PositionRulesDTO rules = PositionRulesDTO.builder().stopGainPercentage(1f).stopLossPercentage(2f).build();
    PositionCreationResultDTO creationResult1 = strategy.createLongPosition(ETH_BTC, new BigDecimal("0.0001"), rules);
    assertTrue(creationResult1.isSuccessful());
    assertEquals(6, creationResult1.getPosition().getUid());
    assertEquals("DRY_ORDER_000000001", creationResult1.getPosition().getOpeningOrder().getOrderId());
    // Check that the position was correctly created.
    // The corresponding order and trade will arrive in few moments.
    // In the meantime, the position should be in OPENING status.
    await().untilAsserted(() -> assertEquals(positionCount + 1, positionRepository.count()));
    Position p6 = getPosition(6L);
    assertEquals(6L, p6.getUid());
    assertEquals(6L, p6.getPositionId());
    assertEquals(LONG, p6.getType());
    assertNotNull(p6.getStrategy());
    assertEquals(1, p6.getStrategy().getUid());
    assertEquals("01", p6.getStrategy().getStrategyId());
    assertEquals(ETH_BTC.toString(), p6.getCurrencyPair());
    assertEquals(0, new BigDecimal("0.0001").compareTo(p6.getAmount().getValue()));
    assertEquals(ETH_BTC.getBaseCurrency().toString(), p6.getAmount().getCurrency());
    assertEquals(1, p6.getStopGainPercentageRule());
    assertEquals(2, p6.getStopLossPercentageRule());
    assertEquals(OPENING, p6.getStatus());
    assertEquals("DRY_ORDER_000000001", p6.getOpeningOrder().getOrderId());
    assertEquals("DRY_ORDER_000000001", p6.getOpeningOrder().getOrderId());
    assertNull(p6.getClosingOrder());
    // If we wait a bit, the order and trade will arrive and the position status will move to OPENED.
    await().untilAsserted(() -> {
        orderFlux.update();
        tradeFlux.update();
        assertEquals(OPENED, getPosition(6L).getStatus());
    });
    p6 = getPosition(6L);
    assertEquals(6L, p6.getUid());
    assertEquals(6L, p6.getPositionId());
    assertEquals(LONG, p6.getType());
    assertNotNull(p6.getStrategy());
    assertEquals(1, p6.getStrategy().getUid());
    assertEquals("01", p6.getStrategy().getStrategyId());
    assertEquals(ETH_BTC.toString(), p6.getCurrencyPair());
    assertEquals(0, new BigDecimal("0.0001").compareTo(p6.getAmount().getValue()));
    assertEquals(ETH_BTC.getBaseCurrency().toString(), p6.getAmount().getCurrency());
    assertEquals(1, p6.getStopGainPercentageRule());
    assertEquals(2, p6.getStopLossPercentageRule());
    assertEquals(OPENED, p6.getStatus());
    assertNotNull(p6.getOpeningOrder());
    assertFalse(p6.getOpeningOrder().getTrades().isEmpty());
    assertTrue(p6.getOpeningOrder().getTrades().stream().anyMatch(t -> "DRY_TRADE_000000001".equals(t.getTradeId())));
    // =============================================================================================================
    // Creates a position with ID to 7.
    PositionCreationResultDTO creationResult2 = strategy.createLongPosition(ETH_BTC, new BigDecimal("0.0002"), PositionRulesDTO.builder().build());
    assertTrue(creationResult2.isSuccessful());
    assertEquals("DRY_ORDER_000000002", creationResult2.getPosition().getOpeningOrder().getOrderId());
    // Check the created position in database.
    await().untilAsserted(() -> assertEquals(positionCount + 2, positionRepository.count()));
    Position p7 = getPosition(7L);
    assertEquals(7L, p7.getUid());
    assertEquals(7L, p7.getPositionId());
    assertEquals(LONG, p7.getType());
    assertNotNull(p7.getStrategy());
    assertEquals(1, p7.getStrategy().getUid());
    assertEquals("01", p7.getStrategy().getStrategyId());
    assertEquals(ETH_BTC.toString(), p7.getCurrencyPair());
    assertEquals(0, new BigDecimal("0.0002").compareTo(p7.getAmount().getValue()));
    assertEquals(ETH_BTC.getBaseCurrency().toString(), p7.getAmount().getCurrency());
    assertNull(p7.getStopGainPercentageRule());
    assertNull(p7.getStopLossPercentageRule());
    assertEquals(OPENING, p7.getStatus());
    assertEquals("DRY_ORDER_000000002", p7.getOpeningOrder().getOrderId());
    assertNull(p7.getClosingOrder());
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) ASK(tech.cassandre.trading.bot.dto.trade.OrderTypeDTO.ASK) ZonedDateTime(java.time.ZonedDateTime) BEFORE_EACH_TEST_METHOD(org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) Position(tech.cassandre.trading.bot.domain.Position) Autowired(org.springframework.beans.factory.annotation.Autowired) ActiveProfiles(org.springframework.test.context.ActiveProfiles) CurrencyAmountDTO(tech.cassandre.trading.bot.dto.util.CurrencyAmountDTO) BigDecimal(java.math.BigDecimal) TradeFlux(tech.cassandre.trading.bot.batch.TradeFlux) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) USDT(tech.cassandre.trading.bot.dto.util.CurrencyDTO.USDT) OrderFlux(tech.cassandre.trading.bot.batch.OrderFlux) NEW(tech.cassandre.trading.bot.dto.trade.OrderStatusDTO.NEW) OPENED(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENED) ETH(tech.cassandre.trading.bot.dto.util.CurrencyDTO.ETH) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) Awaitility.await(org.awaitility.Awaitility.await) USD(tech.cassandre.trading.bot.dto.util.CurrencyDTO.USD) PositionRepository(tech.cassandre.trading.bot.repository.PositionRepository) PositionService(tech.cassandre.trading.bot.service.PositionService) TickerFlux(tech.cassandre.trading.bot.batch.TickerFlux) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) Test(org.junit.jupiter.api.Test) PositionCreationResultDTO(tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO) OrderRepository(tech.cassandre.trading.bot.repository.OrderRepository) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) TickerDTO(tech.cassandre.trading.bot.dto.market.TickerDTO) Property(tech.cassandre.trading.bot.test.util.junit.configuration.Property) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) CLOSED(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSED) PositionException(tech.cassandre.trading.bot.util.exception.PositionException) LONG(tech.cassandre.trading.bot.dto.position.PositionTypeDTO.LONG) BaseTest(tech.cassandre.trading.bot.test.util.junit.BaseTest) TestableCassandreStrategy(tech.cassandre.trading.bot.test.util.strategies.TestableCassandreStrategy) OPENING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENING) PositionFlux(tech.cassandre.trading.bot.batch.PositionFlux) BTC(tech.cassandre.trading.bot.dto.util.CurrencyDTO.BTC) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Configuration(tech.cassandre.trading.bot.test.util.junit.configuration.Configuration) Iterator(java.util.Iterator) CLOSING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSING) DisplayName(org.junit.jupiter.api.DisplayName) PositionRulesDTO(tech.cassandre.trading.bot.dto.position.PositionRulesDTO) PARAMETER_EXCHANGE_DRY(tech.cassandre.trading.bot.test.util.junit.configuration.ConfigurationExtension.PARAMETER_EXCHANGE_DRY) PositionCreationResultDTO(tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO) Position(tech.cassandre.trading.bot.domain.Position) PositionRulesDTO(tech.cassandre.trading.bot.dto.position.PositionRulesDTO) BigDecimal(java.math.BigDecimal) 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 4 with Position

use of tech.cassandre.trading.bot.domain.Position in project cassandre-trading-bot by cassandre-tech.

the class PositionServiceCassandreImplementation method getGains.

@Override
public final Map<CurrencyDTO, GainDTO> getGains(final long strategyUid) {
    logger.debug("Retrieving gains for all positions");
    HashMap<CurrencyDTO, BigDecimal> totalBefore = new LinkedHashMap<>();
    HashMap<CurrencyDTO, BigDecimal> totalAfter = new LinkedHashMap<>();
    List<CurrencyAmountDTO> openingOrdersFees = new LinkedList<>();
    List<CurrencyAmountDTO> closingOrdersFees = new LinkedList<>();
    HashMap<CurrencyDTO, GainDTO> gains = new LinkedHashMap<>();
    // We calculate, by currency, the amount bought & sold.
    positionRepository.findByStatus(CLOSED).stream().filter(position -> strategyUid == 0 || position.getStrategy().getUid() == strategyUid).map(POSITION_MAPPER::mapToPositionDTO).forEach(positionDTO -> {
        // We retrieve the currency and initiate the maps if they are empty
        CurrencyDTO currency;
        if (positionDTO.getType() == LONG) {
            // LONG.
            currency = positionDTO.getCurrencyPair().getQuoteCurrency();
        } else {
            // SHORT.
            currency = positionDTO.getCurrencyPair().getBaseCurrency();
        }
        gains.putIfAbsent(currency, null);
        totalBefore.putIfAbsent(currency, ZERO);
        totalAfter.putIfAbsent(currency, ZERO);
        // We calculate the amounts bought and amount sold.
        if (positionDTO.getType() == LONG) {
            totalBefore.put(currency, positionDTO.getOpeningOrder().getTrades().stream().map(t -> t.getAmountValue().multiply(t.getPriceValue())).reduce(totalBefore.get(currency), BigDecimal::add));
            totalAfter.put(currency, positionDTO.getClosingOrder().getTrades().stream().map(t -> t.getAmountValue().multiply(t.getPriceValue())).reduce(totalAfter.get(currency), BigDecimal::add));
        } else {
            totalBefore.put(currency, positionDTO.getOpeningOrder().getTrades().stream().map(TradeDTO::getAmountValue).reduce(totalBefore.get(currency), BigDecimal::add));
            totalAfter.put(currency, positionDTO.getClosingOrder().getTrades().stream().map(TradeDTO::getAmountValue).reduce(totalAfter.get(currency), BigDecimal::add));
        }
        // And now the fees.
        positionDTO.getOpeningOrder().getTrades().stream().filter(tradeDTO -> tradeDTO.getFee() != null).forEach(tradeDTO -> openingOrdersFees.add(tradeDTO.getFee()));
        positionDTO.getClosingOrder().getTrades().stream().filter(tradeDTO -> tradeDTO.getFee() != null).forEach(tradeDTO -> closingOrdersFees.add(tradeDTO.getFee()));
    });
    gains.keySet().forEach(currency -> {
        // We make the calculation.
        BigDecimal before = totalBefore.get(currency);
        BigDecimal after = totalAfter.get(currency);
        BigDecimal gainAmount = after.subtract(before);
        BigDecimal gainPercentage = ((after.subtract(before)).divide(before, HALF_UP)).multiply(ONE_HUNDRED_BIG_DECIMAL);
        GainDTO g = GainDTO.builder().percentage(gainPercentage.setScale(2, HALF_UP).doubleValue()).amount(CurrencyAmountDTO.builder().value(gainAmount).currency(currency).build()).openingOrderFees(openingOrdersFees).closingOrderFees(closingOrdersFees).build();
        gains.put(currency, g);
    });
    return gains;
}
Also used : RequiredArgsConstructor(lombok.RequiredArgsConstructor) Position(tech.cassandre.trading.bot.domain.Position) CLOSED(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSED) HashMap(java.util.HashMap) CurrencyAmountDTO(tech.cassandre.trading.bot.dto.util.CurrencyAmountDTO) LONG(tech.cassandre.trading.bot.dto.position.PositionTypeDTO.LONG) LinkedHashMap(java.util.LinkedHashMap) CassandreStrategyInterface(tech.cassandre.trading.bot.strategy.internal.CassandreStrategyInterface) BigDecimal(java.math.BigDecimal) OPENING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENING) PositionFlux(tech.cassandre.trading.bot.batch.PositionFlux) Locale(java.util.Locale) Map(java.util.Map) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) SHORT(tech.cassandre.trading.bot.dto.position.PositionTypeDTO.SHORT) LinkedList(java.util.LinkedList) FLOOR(java.math.RoundingMode.FLOOR) LinkedHashSet(java.util.LinkedHashSet) OPENED(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENED) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) BIGINTEGER_SCALE(tech.cassandre.trading.bot.util.math.MathConstants.BIGINTEGER_SCALE) CurrencyDTO(tech.cassandre.trading.bot.dto.util.CurrencyDTO) CassandreStrategy(tech.cassandre.trading.bot.strategy.internal.CassandreStrategy) NonNull(lombok.NonNull) PositionRepository(tech.cassandre.trading.bot.repository.PositionRepository) HALF_UP(java.math.RoundingMode.HALF_UP) GainDTO(tech.cassandre.trading.bot.dto.util.GainDTO) Set(java.util.Set) ZERO(java.math.BigDecimal.ZERO) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) Collectors(java.util.stream.Collectors) PositionCreationResultDTO(tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO) PositionTypeDTO(tech.cassandre.trading.bot.dto.position.PositionTypeDTO) List(java.util.List) PositionRulesDTO(tech.cassandre.trading.bot.dto.position.PositionRulesDTO) Stream(java.util.stream.Stream) BaseService(tech.cassandre.trading.bot.util.base.service.BaseService) ONE_HUNDRED_BIG_DECIMAL(tech.cassandre.trading.bot.util.math.MathConstants.ONE_HUNDRED_BIG_DECIMAL) OrderCreationResultDTO(tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO) Optional(java.util.Optional) TickerDTO(tech.cassandre.trading.bot.dto.market.TickerDTO) CurrencyAmountDTO(tech.cassandre.trading.bot.dto.util.CurrencyAmountDTO) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) GainDTO(tech.cassandre.trading.bot.dto.util.GainDTO) CurrencyDTO(tech.cassandre.trading.bot.dto.util.CurrencyDTO) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with Position

use of tech.cassandre.trading.bot.domain.Position in project cassandre-trading-bot by cassandre-tech.

the class PositionTest method checkLoadPositionFromDatabase.

@Test
@DisplayName("Check load position from database")
public void checkLoadPositionFromDatabase() {
    // =============================================================================================================
    // Check position 1 - OPENING.
    PositionDTO position1 = strategy.getPositions().get(1L);
    assertNotNull(position1);
    assertEquals(1L, position1.getUid());
    assertEquals(1L, position1.getPositionId());
    assertEquals(LONG, position1.getType());
    assertNotNull(position1.getStrategy());
    assertEquals(1, position1.getStrategy().getUid());
    assertEquals("01", position1.getStrategy().getStrategyId());
    assertEquals(new CurrencyPairDTO("BTC/USDT"), position1.getCurrencyPair());
    assertEquals(0, new BigDecimal("10").compareTo(position1.getAmount().getValue()));
    assertEquals(BTC, position1.getAmount().getCurrency());
    assertFalse(position1.getRules().isStopGainPercentageSet());
    assertFalse(position1.getRules().isStopLossPercentageSet());
    assertEquals(OPENING, position1.getStatus());
    assertEquals("BACKUP_OPENING_ORDER_01", position1.getOpeningOrder().getOrderId());
    assertTrue(position1.getOpeningOrder().getTrades().isEmpty());
    assertNull(position1.getClosingOrder());
    assertNull(position1.getLowestGainPrice());
    assertNull(position1.getHighestGainPrice());
    assertNull(position1.getLatestGainPrice());
    // Test equals.
    Optional<PositionDTO> position1Bis = strategy.getPositionByPositionId(1L);
    assertTrue(position1Bis.isPresent());
    assertEquals(position1, position1Bis.get());
    // =============================================================================================================
    // Check position 2 - OPENED.
    PositionDTO position2 = strategy.getPositions().get(2L);
    assertNotNull(position2);
    assertEquals(2L, position2.getUid());
    assertEquals(2L, position2.getPositionId());
    assertEquals(LONG, position2.getType());
    assertNotNull(position2.getStrategy());
    assertEquals(1, position2.getStrategy().getUid());
    assertEquals("01", position2.getStrategy().getStrategyId());
    assertEquals(new CurrencyPairDTO("BTC/USDT"), position2.getCurrencyPair());
    assertEquals(0, new BigDecimal("20").compareTo(position2.getAmount().getValue()));
    assertEquals(BTC, position2.getAmount().getCurrency());
    assertTrue(position2.getRules().isStopGainPercentageSet());
    assertEquals(10, position2.getRules().getStopGainPercentage());
    assertFalse(position2.getRules().isStopLossPercentageSet());
    assertEquals(OPENED, position2.getStatus());
    assertEquals("BACKUP_OPENING_ORDER_02", position2.getOpeningOrder().getOrderId());
    assertEquals(1, position2.getOpeningOrder().getTrades().size());
    assertTrue(position2.getOpeningOrder().getTrade("BACKUP_TRADE_01").isPresent());
    assertNull(position2.getClosingOrder());
    assertEquals(0, new BigDecimal("1").compareTo(position2.getLowestGainPrice().getValue()));
    assertEquals(USDT, position2.getLowestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("2").compareTo(position2.getHighestGainPrice().getValue()));
    assertEquals(USDT, position2.getHighestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("3").compareTo(position2.getLatestGainPrice().getValue()));
    assertEquals(USDT, position2.getLatestGainPrice().getCurrency());
    // =============================================================================================================
    // Check position 3 - CLOSING.
    PositionDTO position3 = strategy.getPositions().get(3L);
    assertNotNull(position3);
    assertEquals(3L, position3.getUid());
    assertEquals(3L, position3.getPositionId());
    assertEquals(LONG, position3.getType());
    assertNotNull(position3.getStrategy());
    assertEquals(1, position3.getStrategy().getUid());
    assertEquals("01", position3.getStrategy().getStrategyId());
    assertEquals(new CurrencyPairDTO("BTC/USDT"), position3.getCurrencyPair());
    assertEquals(0, new BigDecimal("30").compareTo(position3.getAmount().getValue()));
    assertEquals(BTC, position3.getAmount().getCurrency());
    assertFalse(position3.getRules().isStopGainPercentageSet());
    assertTrue(position3.getRules().isStopLossPercentageSet());
    assertEquals(20, position3.getRules().getStopLossPercentage());
    assertEquals(CLOSING, position3.getStatus());
    assertEquals("BACKUP_OPENING_ORDER_03", position3.getOpeningOrder().getOrderId());
    assertEquals(1, position3.getOpeningOrder().getTrades().size());
    assertTrue(position3.getOpeningOrder().getTrade("BACKUP_TRADE_02").isPresent());
    assertEquals("BACKUP_CLOSING_ORDER_01", position3.getClosingOrder().getOrderId());
    assertEquals(1, position3.getClosingOrder().getTrades().size());
    assertTrue(position3.getClosingOrder().getTrade("BACKUP_TRADE_04").isPresent());
    assertEquals(0, new BigDecimal("17").compareTo(position3.getLowestGainPrice().getValue()));
    assertEquals(USDT, position3.getLowestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("68").compareTo(position3.getHighestGainPrice().getValue()));
    assertEquals(USDT, position3.getHighestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("92").compareTo(position3.getLatestGainPrice().getValue()));
    assertEquals(USDT, position3.getLatestGainPrice().getCurrency());
    // =============================================================================================================
    // Check position 4 - CLOSED.
    PositionDTO position4 = strategy.getPositions().get(4L);
    assertNotNull(position4);
    assertEquals(4L, position4.getUid());
    assertEquals(4L, position4.getPositionId());
    assertEquals(LONG, position4.getType());
    assertNotNull(position4.getStrategy());
    assertEquals(1, position4.getStrategy().getUid());
    assertEquals("01", position4.getStrategy().getStrategyId());
    assertEquals(new CurrencyPairDTO("BTC/USDT"), position4.getCurrencyPair());
    assertEquals(0, new BigDecimal("40").compareTo(position4.getAmount().getValue()));
    assertEquals(BTC, position4.getAmount().getCurrency());
    assertTrue(position4.getRules().isStopGainPercentageSet());
    assertEquals(30, position4.getRules().getStopGainPercentage());
    assertTrue(position4.getRules().isStopLossPercentageSet());
    assertEquals(40, position4.getRules().getStopLossPercentage());
    assertEquals(CLOSED, position4.getStatus());
    assertEquals("BACKUP_OPENING_ORDER_04", position4.getOpeningOrder().getOrderId());
    assertEquals(1, position4.getOpeningOrder().getTrades().size());
    assertTrue(position4.getOpeningOrder().getTrade("BACKUP_TRADE_03").isPresent());
    assertEquals("BACKUP_CLOSING_ORDER_02", position4.getClosingOrder().getOrderId());
    assertEquals(1, position4.getClosingOrder().getTrades().size());
    assertTrue(position4.getClosingOrder().getTrade("BACKUP_TRADE_05").isPresent());
    assertEquals(0, new BigDecimal("17").compareTo(position4.getLowestGainPrice().getValue()));
    assertEquals(USDT, position4.getLowestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("68").compareTo(position4.getHighestGainPrice().getValue()));
    assertEquals(USDT, position4.getHighestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("93").compareTo(position4.getLatestGainPrice().getValue()));
    assertEquals(USDT, position4.getLatestGainPrice().getCurrency());
    // =============================================================================================================
    // Check position 5 - CLOSED with several trades.
    PositionDTO position5 = strategy.getPositions().get(5L);
    assertNotNull(position5);
    assertEquals(5L, position5.getUid());
    assertEquals(5L, position5.getPositionId());
    assertEquals(LONG, position5.getType());
    assertNotNull(position5.getStrategy());
    assertEquals(1, position5.getStrategy().getUid());
    assertEquals("01", position5.getStrategy().getStrategyId());
    assertEquals(new CurrencyPairDTO("ETH/USD"), position5.getCurrencyPair());
    assertEquals(0, new BigDecimal("50").compareTo(position5.getAmount().getValue()));
    assertEquals(ETH, position5.getAmount().getCurrency());
    assertTrue(position5.getRules().isStopGainPercentageSet());
    assertEquals(30, position5.getRules().getStopGainPercentage());
    assertTrue(position5.getRules().isStopLossPercentageSet());
    assertEquals(40, position5.getRules().getStopLossPercentage());
    assertEquals(CLOSED, position5.getStatus());
    assertEquals("BACKUP_OPENING_ORDER_05", position5.getOpeningOrder().getOrderId());
    assertEquals("BACKUP_CLOSING_ORDER_03", position5.getClosingOrder().getOrderId());
    assertEquals(0, new BigDecimal("17").compareTo(position5.getLowestGainPrice().getValue()));
    assertEquals(USD, position5.getLowestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("68").compareTo(position5.getHighestGainPrice().getValue()));
    assertEquals(USD, position5.getHighestGainPrice().getCurrency());
    assertEquals(0, new BigDecimal("94").compareTo(position5.getLatestGainPrice().getValue()));
    assertEquals(USD, position5.getLatestGainPrice().getCurrency());
    // Open trades.
    assertEquals(2, position5.getOpeningOrder().getTrades().size());
    assertTrue(position5.getOpeningOrder().getTrade("BACKUP_TRADE_06").isPresent());
    assertEquals("BACKUP_TRADE_06", position5.getOpeningOrder().getTrade("BACKUP_TRADE_06").get().getTradeId());
    assertTrue(position5.getOpeningOrder().getTrades().stream().anyMatch(t -> "BACKUP_TRADE_06".equals(t.getTradeId())));
    assertTrue(position5.getOpeningOrder().getTrade("BACKUP_TRADE_07").isPresent());
    assertTrue(position5.getOpeningOrder().getTrades().stream().anyMatch(t -> "BACKUP_TRADE_07".equals(t.getTradeId())));
    assertEquals("BACKUP_TRADE_07", position5.getOpeningOrder().getTrade("BACKUP_TRADE_07").get().getTradeId());
    // Close trades.
    assertEquals(3, position5.getClosingOrder().getTrades().size());
    assertTrue(position5.getClosingOrder().getTrade("BACKUP_TRADE_08").isPresent());
    assertTrue(position5.getClosingOrder().getTrades().stream().anyMatch(t -> "BACKUP_TRADE_08".equals(t.getTradeId())));
    assertEquals("BACKUP_TRADE_08", position5.getClosingOrder().getTrade("BACKUP_TRADE_08").get().getTradeId());
    assertTrue(position5.getClosingOrder().getTrade("BACKUP_TRADE_09").isPresent());
    assertTrue(position5.getClosingOrder().getTrades().stream().anyMatch(t -> "BACKUP_TRADE_09".equals(t.getTradeId())));
    assertEquals("BACKUP_TRADE_09", position5.getClosingOrder().getTrade("BACKUP_TRADE_09").get().getTradeId());
    assertTrue(position5.getClosingOrder().getTrade("BACKUP_TRADE_10").isPresent());
    assertTrue(position5.getClosingOrder().getTrades().stream().anyMatch(t -> "BACKUP_TRADE_10".equals(t.getTradeId())));
    assertEquals("BACKUP_TRADE_10", position5.getClosingOrder().getTrade("BACKUP_TRADE_10").get().getTradeId());
    // Check trade orders.
    final Iterator<TradeDTO> openTradesIterator = position5.getOpeningOrder().getTrades().iterator();
    assertEquals("BACKUP_TRADE_06", openTradesIterator.next().getTradeId());
    assertEquals("BACKUP_TRADE_07", openTradesIterator.next().getTradeId());
    final Iterator<TradeDTO> closeTradesIterator = position5.getClosingOrder().getTrades().iterator();
    assertEquals("BACKUP_TRADE_08", closeTradesIterator.next().getTradeId());
    assertEquals("BACKUP_TRADE_09", closeTradesIterator.next().getTradeId());
    assertEquals("BACKUP_TRADE_10", closeTradesIterator.next().getTradeId());
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) ASK(tech.cassandre.trading.bot.dto.trade.OrderTypeDTO.ASK) ZonedDateTime(java.time.ZonedDateTime) BEFORE_EACH_TEST_METHOD(org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) Position(tech.cassandre.trading.bot.domain.Position) Autowired(org.springframework.beans.factory.annotation.Autowired) ActiveProfiles(org.springframework.test.context.ActiveProfiles) CurrencyAmountDTO(tech.cassandre.trading.bot.dto.util.CurrencyAmountDTO) BigDecimal(java.math.BigDecimal) TradeFlux(tech.cassandre.trading.bot.batch.TradeFlux) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) USDT(tech.cassandre.trading.bot.dto.util.CurrencyDTO.USDT) OrderFlux(tech.cassandre.trading.bot.batch.OrderFlux) NEW(tech.cassandre.trading.bot.dto.trade.OrderStatusDTO.NEW) OPENED(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENED) ETH(tech.cassandre.trading.bot.dto.util.CurrencyDTO.ETH) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) Awaitility.await(org.awaitility.Awaitility.await) USD(tech.cassandre.trading.bot.dto.util.CurrencyDTO.USD) PositionRepository(tech.cassandre.trading.bot.repository.PositionRepository) PositionService(tech.cassandre.trading.bot.service.PositionService) TickerFlux(tech.cassandre.trading.bot.batch.TickerFlux) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) Test(org.junit.jupiter.api.Test) PositionCreationResultDTO(tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO) OrderRepository(tech.cassandre.trading.bot.repository.OrderRepository) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) TickerDTO(tech.cassandre.trading.bot.dto.market.TickerDTO) Property(tech.cassandre.trading.bot.test.util.junit.configuration.Property) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) CLOSED(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSED) PositionException(tech.cassandre.trading.bot.util.exception.PositionException) LONG(tech.cassandre.trading.bot.dto.position.PositionTypeDTO.LONG) BaseTest(tech.cassandre.trading.bot.test.util.junit.BaseTest) TestableCassandreStrategy(tech.cassandre.trading.bot.test.util.strategies.TestableCassandreStrategy) OPENING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENING) PositionFlux(tech.cassandre.trading.bot.batch.PositionFlux) BTC(tech.cassandre.trading.bot.dto.util.CurrencyDTO.BTC) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Configuration(tech.cassandre.trading.bot.test.util.junit.configuration.Configuration) Iterator(java.util.Iterator) CLOSING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSING) DisplayName(org.junit.jupiter.api.DisplayName) PositionRulesDTO(tech.cassandre.trading.bot.dto.position.PositionRulesDTO) PARAMETER_EXCHANGE_DRY(tech.cassandre.trading.bot.test.util.junit.configuration.ConfigurationExtension.PARAMETER_EXCHANGE_DRY) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) BigDecimal(java.math.BigDecimal) 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)

Aggregations

Position (tech.cassandre.trading.bot.domain.Position)9 PositionDTO (tech.cassandre.trading.bot.dto.position.PositionDTO)8 BigDecimal (java.math.BigDecimal)7 PositionCreationResultDTO (tech.cassandre.trading.bot.dto.position.PositionCreationResultDTO)6 Optional (java.util.Optional)5 CLOSED (tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSED)5 OPENED (tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENED)5 OPENING (tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENING)5 LONG (tech.cassandre.trading.bot.dto.position.PositionTypeDTO.LONG)5 OrderCreationResultDTO (tech.cassandre.trading.bot.dto.trade.OrderCreationResultDTO)5 PositionRepository (tech.cassandre.trading.bot.repository.PositionRepository)5 Iterator (java.util.Iterator)4 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)4 Assertions.assertFalse (org.junit.jupiter.api.Assertions.assertFalse)4 Assertions.assertNotNull (org.junit.jupiter.api.Assertions.assertNotNull)4 Assertions.assertNull (org.junit.jupiter.api.Assertions.assertNull)4 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)4 PositionFlux (tech.cassandre.trading.bot.batch.PositionFlux)4 TickerDTO (tech.cassandre.trading.bot.dto.market.TickerDTO)4 PositionRulesDTO (tech.cassandre.trading.bot.dto.position.PositionRulesDTO)4