use of tech.cassandre.trading.bot.dto.trade.OrderTypeDTO.ASK in project cassandre-trading-bot by cassandre-tech.
the class TradeServiceTest method checkCreateBuyAndSellOrder.
@Test
@DisplayName("Check buy and sell order creation")
public void checkCreateBuyAndSellOrder() {
assertTrue(strategy.getConfiguration().isDryMode());
// To create an order in dry mode, we need an existing price for the position currency pair.
await().until(() -> strategy.getTickersUpdatesReceived().size() >= 1);
// What we expect.
final String orderId01 = "DRY_ORDER_000000001";
final String tradeId01 = "DRY_TRADE_000000001";
final String orderId02 = "DRY_ORDER_000000002";
final String tradeId02 = "DRY_TRADE_000000002";
// Check that everything is empty.
assertEquals(0, tradeService.getOrders().size());
assertEquals(0, tradeService.getTrades().size());
// =============================================================================================================
// We create a buy order.
final OrderCreationResultDTO buyMarketOrder01 = strategy.createBuyMarketOrder(ETH_BTC, new BigDecimal("0.001"));
assertTrue(buyMarketOrder01.isSuccessful());
assertEquals(orderId01, buyMarketOrder01.getOrder().getOrderId());
// Testing the received order.
await().until(() -> strategy.getOrdersUpdatesReceived().stream().anyMatch(o -> o.getOrderId().equals(orderId01) && o.getStatus().equals(FILLED)));
final Optional<OrderDTO> order01 = strategy.getOrdersUpdatesReceived().stream().filter(o -> o.getOrderId().equals(orderId01)).filter(o -> o.getStatus().equals(FILLED)).findFirst();
assertTrue(order01.isPresent());
assertEquals(1, order01.get().getUid());
assertEquals(orderId01, order01.get().getOrderId());
assertEquals(BID, order01.get().getType());
assertNotNull(order01.get().getStrategy());
assertEquals(1, order01.get().getStrategy().getUid());
assertEquals("01", order01.get().getStrategy().getStrategyId());
assertEquals(ETH_BTC, order01.get().getCurrencyPair());
assertEquals(0, new BigDecimal("0.001").compareTo(order01.get().getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency(), order01.get().getAmount().getCurrency());
assertEquals(0, new BigDecimal("0.2").compareTo(order01.get().getAveragePrice().getValue()));
assertEquals(ETH_BTC.getQuoteCurrency(), order01.get().getAveragePrice().getCurrency());
assertNull(order01.get().getLimitPrice());
assertNull(order01.get().getLeverage());
assertEquals(FILLED, order01.get().getStatus());
assertEquals(0, new BigDecimal("0.001").compareTo(order01.get().getCumulativeAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency(), order01.get().getCumulativeAmount().getCurrency());
assertNull(order01.get().getUserReference());
assertNotNull(order01.get().getTimestamp());
// Testing the received trade.
await().until(() -> strategy.getTradesUpdatesReceived().stream().anyMatch(o -> o.getTradeId().equals(tradeId01)));
final Optional<TradeDTO> trade01 = strategy.getTradesUpdatesReceived().stream().filter(o -> o.getTradeId().equals(tradeId01)).findFirst();
assertTrue(trade01.isPresent());
assertEquals(1, trade01.get().getUid());
assertEquals(tradeId01, trade01.get().getTradeId());
assertEquals(BID, trade01.get().getType());
assertEquals(orderId01, trade01.get().getOrderId());
assertEquals(ETH_BTC, trade01.get().getCurrencyPair());
assertEquals(0, new BigDecimal("0.001").compareTo(trade01.get().getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency(), trade01.get().getAmount().getCurrency());
assertEquals(0, new BigDecimal("0.2").compareTo(trade01.get().getPrice().getValue()));
assertEquals(ETH_BTC.getQuoteCurrency(), trade01.get().getPrice().getCurrency());
assertNull(trade01.get().getFee());
assertNull(trade01.get().getUserReference());
assertNotNull(trade01.get().getTimestamp());
// =============================================================================================================
// We create a sell order, so we could check order numbers and type.
final OrderCreationResultDTO buyMarketOrder02 = strategy.createSellMarketOrder(ETH_BTC, new BigDecimal("0.002"));
assertTrue(buyMarketOrder02.isSuccessful());
assertEquals(orderId02, buyMarketOrder02.getOrder().getOrderId());
// Testing the received order.
await().until(() -> strategy.getOrdersUpdatesReceived().stream().anyMatch(o -> o.getOrderId().equals(orderId02) && o.getStatus().equals(FILLED)));
final Optional<OrderDTO> order02 = strategy.getOrdersUpdatesReceived().stream().filter(o -> o.getOrderId().equals(orderId02)).filter(o -> o.getStatus().equals(FILLED)).findFirst();
assertTrue(order02.isPresent());
assertEquals(2, order02.get().getUid());
assertEquals(orderId02, order02.get().getOrderId());
assertEquals(ASK, order02.get().getType());
assertNotNull(order02.get().getStrategy());
assertEquals(1, order02.get().getStrategy().getUid());
assertEquals("01", order02.get().getStrategy().getStrategyId());
assertEquals(ETH_BTC, order02.get().getCurrencyPair());
assertEquals(0, new BigDecimal("0.002").compareTo(order02.get().getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency(), order02.get().getAmount().getCurrency());
assertEquals(0, new BigDecimal("0.2").compareTo(order02.get().getAveragePrice().getValue()));
assertEquals(ETH_BTC.getQuoteCurrency(), order02.get().getAveragePrice().getCurrency());
assertNull(order02.get().getLimitPrice());
assertNull(order02.get().getLeverage());
assertEquals(FILLED, order02.get().getStatus());
assertEquals(0, new BigDecimal("0.002").compareTo(order02.get().getCumulativeAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency(), order02.get().getCumulativeAmount().getCurrency());
assertNull(order02.get().getUserReference());
assertNotNull(order02.get().getTimestamp());
// Testing the received trade.
await().until(() -> strategy.getTradesUpdatesReceived().stream().anyMatch(o -> o.getTradeId().equals(tradeId02)));
final Optional<TradeDTO> trade02 = strategy.getTradesUpdatesReceived().stream().filter(o -> o.getTradeId().equals(tradeId02)).findFirst();
assertTrue(trade02.isPresent());
assertEquals(2, trade02.get().getUid());
assertEquals(tradeId02, trade02.get().getTradeId());
assertEquals(ASK, trade02.get().getType());
assertEquals(orderId02, trade02.get().getOrderId());
assertEquals(ETH_BTC, trade02.get().getCurrencyPair());
assertEquals(0, new BigDecimal("0.002").compareTo(trade02.get().getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency(), trade02.get().getAmount().getCurrency());
assertEquals(0, new BigDecimal("0.2").compareTo(trade02.get().getPrice().getValue()));
assertEquals(ETH_BTC.getQuoteCurrency(), trade02.get().getPrice().getCurrency());
assertNull(trade02.get().getFee());
assertNull(trade02.get().getUserReference());
assertNotNull(trade02.get().getTimestamp());
}
use of tech.cassandre.trading.bot.dto.trade.OrderTypeDTO.ASK in project cassandre-trading-bot by cassandre-tech.
the class PositionTest method checkSavedDataDuringPositionLifecycle.
@Test
@DisplayName("Check saved data during position lifecycle")
public void checkSavedDataDuringPositionLifecycle() {
// First ticker emitted for dry mode - MANDATORY.
tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).timestamp(createZonedDateTime(1)).last(new BigDecimal("0.01")).build());
await().untilAsserted(() -> assertEquals(1, strategy.getTickersUpdatesReceived().size()));
// =============================================================================================================
// A position is created on ETH/BTC - ID 6.
// We buy 1 ETH for 0.01 BTC.
// Waiting for order DRY_ORDER_000000001.
final PositionCreationResultDTO positionResult = strategy.createLongPosition(ETH_BTC, new BigDecimal("1"), PositionRulesDTO.builder().stopGainPercentage(// 1 000% max gain.
1000f).stopLossPercentage(// 100% max lost.
100f).build());
assertTrue(positionResult.isSuccessful());
final long positionId = positionResult.getPosition().getUid();
// =============================================================================================================
// Still "OPENING".
// Two tickers arrived - min and max gain should not be set as the position is still in OPENING status.
// Check that the position was correctly created.
// The corresponding order and trade will arrive in few seconds.
// In the meantime, the position should be in OPENING status.
await().untilAsserted(() -> assertEquals(OPENING, getPosition(positionId).getStatus()));
Position p = getPosition(positionId);
assertEquals(positionId, p.getUid());
assertEquals(positionId, p.getPositionId());
assertEquals(LONG, p.getType());
assertEquals(1, p.getStrategy().getUid());
assertEquals("01", p.getStrategy().getStrategyId());
assertEquals(ETH_BTC.toString(), p.getCurrencyPair());
assertEquals(0, new BigDecimal("1").compareTo(p.getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency().toString(), p.getAmount().getCurrency());
assertEquals(1000, p.getStopGainPercentageRule());
assertEquals(100, p.getStopLossPercentageRule());
assertEquals(OPENING, p.getStatus());
assertEquals("DRY_ORDER_000000001", p.getOpeningOrder().getOrderId());
assertNull(p.getClosingOrder());
assertNull(p.getClosingOrder());
assertNull(p.getLowestGainPrice());
assertNull(p.getHighestGainPrice());
ZonedDateTime createdOn = p.getCreatedOn();
ZonedDateTime updatedON = p.getUpdatedOn();
assertNotNull(createdOn);
assertNotNull(updatedON);
// We should have one more position and one more trade in database.
await().untilAsserted(() -> assertEquals(6, positionRepository.count()));
// =============================================================================================================
// The position should now be OPENED.
// We are in dry mode, we wait for order and trade to arrive, position will now be opened.
await().untilAsserted(() -> {
orderFlux.update();
tradeFlux.update();
assertEquals(OPENED, getPosition(positionId).getStatus());
});
// Check the position data in database.
p = getPosition(positionId);
assertEquals(positionId, p.getUid());
assertEquals(positionId, p.getPositionId());
assertEquals(LONG, p.getType());
assertEquals(1, p.getStrategy().getUid());
assertEquals("01", p.getStrategy().getStrategyId());
assertEquals(ETH_BTC.toString(), p.getCurrencyPair());
assertEquals(0, new BigDecimal("1").compareTo(p.getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency().toString(), p.getAmount().getCurrency());
assertEquals(1000, p.getStopGainPercentageRule());
assertEquals(100, p.getStopLossPercentageRule());
assertEquals(OPENED, p.getStatus());
assertEquals("DRY_ORDER_000000001", p.getOpeningOrder().getOrderId());
assertFalse(p.getOpeningOrder().getTrades().isEmpty());
assertTrue(p.getOpeningOrder().getTrades().stream().anyMatch(t -> "DRY_TRADE_000000001".equals(t.getTradeId())));
assertNull(p.getClosingOrder());
// =============================================================================================================
// Now that the position is OPENED, we are sending tickers to see if lowest, highest and latest price change.
// First ticker arrives (500% gain) - min and max gain should be set to that value.
tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).last(new BigDecimal("0.06")).build());
await().untilAsserted(() -> assertNotNull(getPosition(positionId).getLatestGainPrice()));
await().untilAsserted(() -> assertEquals(0, new BigDecimal("0.06").compareTo(getPosition(positionId).getLatestGainPrice().getValue())));
// Second ticker arrives (100% gain) - min gain should be set to that value.
tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).last(new BigDecimal("0.02")).build());
await().untilAsserted(() -> assertEquals(0, new BigDecimal("0.02").compareTo(getPosition(positionId).getLatestGainPrice().getValue())));
// Third ticker arrives (200% gain) - nothing should change.
tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).last(new BigDecimal("0.03")).build());
await().untilAsserted(() -> assertEquals(0, new BigDecimal("0.03").compareTo(getPosition(positionId).getLatestGainPrice().getValue())));
// Fourth ticker arrives (50% loss) - min gain should be set to that value.
tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).last(new BigDecimal("0.005")).build());
await().untilAsserted(() -> assertEquals(0, new BigDecimal("0.005").compareTo(getPosition(positionId).getLatestGainPrice().getValue())));
// Fifth ticker arrives (600% gain) - max gain should be set to that value.
tickerFlux.emitValue(TickerDTO.builder().currencyPair(ETH_BTC).last(new BigDecimal("0.07")).build());
await().untilAsserted(() -> assertEquals(0, new BigDecimal("0.07").compareTo(getPosition(positionId).getLatestGainPrice().getValue())));
// Check lowest & highest in database.
await().untilAsserted(() -> assertEquals(6, strategy.getTickersUpdatesReceived().size()));
assertTrue(getPositionDTO(positionId).getLowestCalculatedGain().isPresent());
assertTrue(getPositionDTO(positionId).getHighestCalculatedGain().isPresent());
assertEquals(0, new BigDecimal("0.005").compareTo(getPositionDTO(positionId).getLowestGainPrice().getValue()));
assertEquals(ETH_BTC.getQuoteCurrency(), getPositionDTO(positionId).getLowestGainPrice().getCurrency());
assertEquals(0, new BigDecimal("0.07").compareTo(getPositionDTO(positionId).getHighestGainPrice().getValue()));
assertEquals(ETH_BTC.getQuoteCurrency(), getPositionDTO(positionId).getHighestGainPrice().getCurrency());
assertEquals(-50, getPositionDTO(positionId).getLowestCalculatedGain().get().getPercentage());
assertEquals(600, getPositionDTO(positionId).getHighestCalculatedGain().get().getPercentage());
// Check that the new data was inserted in database.
await().untilAsserted(() -> assertEquals(6, positionRepository.count()));
assertEquals(createdOn, getPosition(positionId).getCreatedOn());
assertTrue(updatedON.isBefore(getPosition(positionId).getUpdatedOn()));
// =============================================================================================================
// The status should now be CLOSING. We are going to receive two trades to close.
// Closing the trade - min and max should not change.
PositionDTO pDTO = getPositionDTO(positionId);
final OrderDTO order2 = OrderDTO.builder().orderId("DRY_ORDER_000000002").type(ASK).strategy(strategyDTO).currencyPair(ETH_BTC).amount(new CurrencyAmountDTO("1", ETH_BTC.getBaseCurrency())).averagePrice(new CurrencyAmountDTO("1.00003", ETH_BTC.getQuoteCurrency())).limitPrice(new CurrencyAmountDTO("1.00005", ETH_BTC.getQuoteCurrency())).leverage("leverage3").status(NEW).cumulativeAmount(new CurrencyAmountDTO("1.00002", ETH_BTC.getBaseCurrency())).userReference("MY_REF_3").timestamp(createZonedDateTime("01-01-2020")).build();
pDTO.closePositionWithOrder(order2);
positionFlux.emitValue(pDTO);
orderFlux.emitValue(order2);
await().untilAsserted(() -> assertTrue(() -> orderRepository.findByOrderId("DRY_ORDER_000000002").isPresent()));
positionFlux.emitValue(pDTO);
// The first close trade arrives, status should not change as it's not the total amount.
tradeFlux.emitValue(TradeDTO.builder().tradeId("000002").type(ASK).orderId("DRY_ORDER_000000002").currencyPair(ETH_BTC).amount(new CurrencyAmountDTO("0.5", ETH_BTC.getBaseCurrency())).price(new CurrencyAmountDTO("1", ETH_BTC.getQuoteCurrency())).build());
await().untilAsserted(() -> assertEquals(1, getPositionDTO(positionId).getClosingOrder().getTrades().size()));
assertEquals(CLOSING, getPositionDTO(positionId).getStatus());
// The second close trade arrives, status should change as the total of trades quantities equals order quantity.
tradeFlux.emitValue(TradeDTO.builder().tradeId("000003").type(ASK).orderId("DRY_ORDER_000000002").currencyPair(ETH_BTC).amount(new CurrencyAmountDTO("0.5", ETH_BTC.getBaseCurrency())).price(new CurrencyAmountDTO("1", ETH_BTC.getQuoteCurrency())).build());
await().untilAsserted(() -> assertEquals(2, getPositionDTO(positionId).getClosingOrder().getTrades().size()));
await().untilAsserted(() -> assertEquals(CLOSED, getPositionDTO(positionId).getStatus()));
// =============================================================================================================
// We should now be CLOSED as we received the two trades.
// Check saved position.
await().until(() -> getPosition(positionId).getStatus().equals(CLOSED));
p = getPosition(positionId);
assertEquals(positionId, p.getUid());
assertEquals(positionId, p.getPositionId());
assertEquals(LONG, p.getType());
assertEquals(1, p.getStrategy().getUid());
assertEquals("01", p.getStrategy().getStrategyId());
assertEquals(ETH_BTC.toString(), p.getCurrencyPair());
assertEquals(0, new BigDecimal("1").compareTo(p.getAmount().getValue()));
assertEquals(ETH_BTC.getBaseCurrency().toString(), p.getAmount().getCurrency());
assertEquals(1000, p.getStopGainPercentageRule());
assertEquals(100, p.getStopLossPercentageRule());
assertEquals(CLOSED, p.getStatus());
assertEquals("DRY_ORDER_000000001", p.getOpeningOrder().getOrderId());
assertEquals("DRY_ORDER_000000002", p.getClosingOrder().getOrderId());
assertEquals(1, p.getOpeningOrder().getTrades().size());
assertEquals(2, p.getClosingOrder().getTrades().size());
assertTrue(p.getOpeningOrder().getTrades().stream().anyMatch(t -> "DRY_TRADE_000000001".equals(t.getTradeId())));
assertTrue(p.getClosingOrder().getTrades().stream().anyMatch(t -> "000002".equals(t.getTradeId())));
assertTrue(p.getClosingOrder().getTrades().stream().anyMatch(t -> "000003".equals(t.getTradeId())));
assertEquals(0, new BigDecimal("0.005").compareTo(p.getLowestGainPrice().getValue()));
assertEquals(0, new BigDecimal("0.07").compareTo(p.getHighestGainPrice().getValue()));
assertEquals(0, new BigDecimal("0.07").compareTo(p.getLatestGainPrice().getValue()));
}
Aggregations