Skip to content

Commit

Permalink
Renaming foreign key from ID to UID #880
Browse files Browse the repository at this point in the history
  • Loading branch information
straumat committed Feb 7, 2022
1 parent bfc502d commit 8d17d70
Show file tree
Hide file tree
Showing 42 changed files with 1,971 additions and 1,893 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ protected final Set<AccountDTO> getNewValues() {
.values()
.stream()
.peek(accountDTO -> logger.debug("Retrieved account from exchange: {}", accountDTO))
// We consider that we have a new value to send to strategies in those cases:
// We consider that we have a new value to send to strategies in two cases:
// - New value (AccountDTO) is already in previous values but balances are different.
// - New value (accountDTO) doesn't exist at all in previous values.
// - New value (AccountDTO) doesn't exist at all in previous values.
.filter(accountDTO -> !Objects.equals(accountDTO, previousValues.get(accountDTO.getAccountId())))
.peek(accountDTO -> logger.debug("Updated account: {}", accountDTO))
// We add or replace the new value in the previous values.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import tech.cassandre.trading.bot.strategy.BasicCassandreStrategy;
import tech.cassandre.trading.bot.strategy.BasicTa4jCassandreStrategy;
import tech.cassandre.trading.bot.strategy.CassandreStrategy;
import tech.cassandre.trading.bot.strategy.internal.CassandreStrategyConfiguration;
import tech.cassandre.trading.bot.strategy.internal.CassandreStrategyDependencies;
import tech.cassandre.trading.bot.strategy.internal.CassandreStrategyInterface;
import tech.cassandre.trading.bot.util.base.configuration.BaseConfiguration;
Expand Down Expand Up @@ -202,14 +203,10 @@ public void configure() {
}
strategyDTO.initializeLastPositionIdUsed(positionRepository.getLastPositionIdUsedByStrategy(strategyDTO.getUid()));

// Gives configuration information to the strategy.
strategy.setDryModeIndicator(exchangeParameters.getModes().getDry());

// Initialize accounts values in strategy.
// Setting up configuration, dependencies and accounts in strategy.
strategy.initializeAccounts(user.getAccounts());

// Setting dependencies in strategy.
strategy.setDependencies(getCassandreStrategyDependencies(strategyDTO));
strategy.setConfiguration(getCassandreStrategyConfiguration(strategyDTO));
strategy.setDependencies(getCassandreStrategyDependencies());

// Calling user defined initialize() method.
strategy.initialize();
Expand Down Expand Up @@ -339,15 +336,25 @@ private UserDTO checkConfiguration(final Map<String, Object> strategies) {
}

/**
* Returns cassandre strategy dependencies.
* Returns cassandre strategy configuration.
*
* @param strategyDTO strategy
* @return cassandre strategy configuration
*/
private CassandreStrategyConfiguration getCassandreStrategyConfiguration(final StrategyDTO strategyDTO) {
return CassandreStrategyConfiguration.builder()
.strategyDTO(strategyDTO)
.dryMode(exchangeParameters.getModes().getDry())
.build();
}

/**
* Returns cassandre strategy dependencies.
*
* @return cassandre strategy dependencies
*/
private CassandreStrategyDependencies getCassandreStrategyDependencies(final StrategyDTO strategyDTO) {
private CassandreStrategyDependencies getCassandreStrategyDependencies() {
return CassandreStrategyDependencies.builder()
// Data.
.strategy(strategyDTO)
// Flux.
.positionFlux(positionFlux)
// Repositories.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public class Order extends BaseDomain {

/** The strategy that created the order. */
@ManyToOne(fetch = EAGER)
@JoinColumn(name = "FK_STRATEGY_ID", updatable = false)
@JoinColumn(name = "FK_STRATEGY_UID", updatable = false)
private Strategy strategy;

/** Currency pair. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public class Position extends BaseDomain {

/** The strategy that created the position. */
@ManyToOne(fetch = EAGER)
@JoinColumn(name = "FK_STRATEGY_ID", updatable = false)
@JoinColumn(name = "FK_STRATEGY_UID", updatable = false)
private Strategy strategy;

/** The currency-pair. */
Expand Down Expand Up @@ -105,12 +105,12 @@ public class Position extends BaseDomain {

/** The order created to open the position. */
@OneToOne(fetch = EAGER, cascade = ALL)
@JoinColumn(name = "FK_OPENING_ORDER_ID")
@JoinColumn(name = "FK_OPENING_ORDER_UID")
private Order openingOrder;

/** The order created to close the position. */
@OneToOne(fetch = EAGER, cascade = ALL)
@JoinColumn(name = "FK_CLOSING_ORDER_ID")
@JoinColumn(name = "FK_CLOSING_ORDER_UID")
private Order closingOrder;

/** Price of the lowest gain reached by this position. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public class Trade extends BaseDomain {

/** The order responsible for this trade. */
@ManyToOne
@JoinColumn(name = "FK_ORDER_ID", nullable = false)
@JoinColumn(name = "FK_ORDER_UID", nullable = false)
private Order order;

/** Currency pair. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class StrategyDTO {
/** An identifier that uniquely identifies the strategy - Comes from the Java annotation. */
String strategyId;

/** Strategy type - Comes from the Java strategy inheritence. */
/** Strategy type - Comes from the Java strategy inheritance. */
StrategyTypeDTO type;

/** Strategy name - Comes from the Java annotation. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
Expand Down Expand Up @@ -64,7 +63,7 @@ public Set<TickerDTO> getTickers(@NonNull final Set<CurrencyPairDTO> currencyPai
CurrencyPairsParam params = () -> currencyPairs
.stream()
.map(CURRENCY_MAPPER::mapToCurrencyPair)
.collect(Collectors.toCollection(LinkedList::new));
.toList();

// Consume a token from the token bucket.
// If a token is not available this method will block until the refill adds one to the bucket.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,12 @@ private PositionCreationResultDTO createPosition(final CassandreStrategy strateg
// =========================================================================================================
// Creates the position in database.
Position position = new Position();
position.setStrategy(STRATEGY_MAPPER.mapToStrategy(strategy.getStrategyDTO()));
position.setStrategy(STRATEGY_MAPPER.mapToStrategy(strategy.getConfiguration().getStrategyDTO()));
position = positionRepository.save(position);

// =========================================================================================================
// Creates the position dto.
PositionDTO p = new PositionDTO(position.getUid(), type, strategy.getStrategyDTO(), currencyPair, amount, orderCreationResult.getOrder(), rules);
PositionDTO p = new PositionDTO(position.getUid(), type, strategy.getConfiguration().getStrategyDTO(), currencyPair, amount, orderCreationResult.getOrder(), rules);
positionRepository.save(POSITION_MAPPER.mapToPosition(p));
logger.debug("Position {} opened with order {}",
p.getPositionId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ private OrderCreationResultDTO createMarketOrder(final CassandreStrategyInterfac
OrderDTO order = OrderDTO.builder()
.orderId(tradeService.placeMarketOrder(m))
.type(orderTypeDTO)
.strategy(strategy.getStrategyDTO())
.strategy(strategy.getConfiguration().getStrategyDTO())
.currencyPair(currencyPair)
.amount(CurrencyAmountDTO.builder()
.value(amount)
Expand Down Expand Up @@ -208,7 +208,7 @@ private OrderCreationResultDTO createLimitOrder(final CassandreStrategyInterface
OrderDTO order = OrderDTO.builder()
.orderId(tradeService.placeLimitOrder(l))
.type(orderTypeDTO)
.strategy(strategy.getStrategyDTO())
.strategy(strategy.getConfiguration().getStrategyDTO())
.currencyPair(currencyPair)
.amount(CurrencyAmountDTO.builder()
.value(amount)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* <p>
* These are the classes used to manage a position.
* - CassandreStrategyInterface list the methods a strategy type must implement to be able to interact with the Cassandre framework.
* - CassandreStrategyConfiguration contains the configuration of the strategy.
* - CassandreStrategyDependencies contains all the dependencies required by a strategy and provided by the Cassandre framework.
* - CassandreStrategyImplementation is the default implementation of CassandreStrategyInterface, this code manages the interaction between Cassandre framework and a strategy.
* - CassandreStrategy (class) is the class that every strategy used by user ({@link BasicCassandreStrategy} or {@link BasicTa4jCassandreStrategy}) must extend. It contains methods to access data and manage orders, trades, positions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* <p>
* These are the classes used to manage a position.
* - CassandreStrategyInterface list the methods a strategy type must implement to be able to interact with the Cassandre framework.
* - CassandreStrategyConfiguration contains the configuration of the strategy.
* - CassandreStrategyDependencies contains all the dependencies required by a strategy and provided by the Cassandre framework.
* - CassandreStrategyImplementation is the default implementation of CassandreStrategyInterface, this code manages the interaction between Cassandre framework and a strategy.
* - CassandreStrategy (class) is the class that every strategy used by user ({@link BasicCassandreStrategy} or {@link BasicTa4jCassandreStrategy}) must extend. It contains methods to access data and manage orders, trades, positions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* <p>
* These are the classes used to manage a position.
* - CassandreStrategyInterface list the methods a strategy type must implement to be able to interact with the Cassandre framework.
* - CassandreStrategyConfiguration contains the configuration of the strategy.
* - CassandreStrategyDependencies contains all the dependencies required by a strategy and provided by the Cassandre framework.
* - CassandreStrategyImplementation is the default implementation of CassandreStrategyInterface, this code manages the interaction between Cassandre framework and a strategy.
* - CassandreStrategy (class) is the class that every strategy used by user ({@link BasicCassandreStrategy} or {@link BasicTa4jCassandreStrategy}) must extend. It contains methods to access data and manage orders, trades, positions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import java.math.BigDecimal;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand All @@ -34,6 +33,7 @@
* <p>
* These are the classes used to manage a position.
* - CassandreStrategyInterface list the methods a strategy type must implement to be able to interact with the Cassandre framework.
* - CassandreStrategyConfiguration contains the configuration of the strategy.
* - CassandreStrategyDependencies contains all the dependencies required by a strategy and provided by the Cassandre framework.
* - CassandreStrategyImplementation is the default implementation of CassandreStrategyInterface, this code manages the interaction between Cassandre framework and a strategy.
* - CassandreStrategy (class) is the class that every strategy used by user ({@link BasicCassandreStrategy} or {@link BasicTa4jCassandreStrategy}) must extend. It contains methods to access data and manage orders, trades, positions.
Expand Down Expand Up @@ -106,17 +106,17 @@ public final Map<CurrencyPairDTO, TickerDTO> getLastTickers() {
return lastTickers;
}


/**
* Return the list of imported tickers (ordered by timestamp).
*
* @return imported tickers
*/
public final List<TickerDTO> getImportedTickers() {
return dependencies.getImportedTickersRepository().findByOrderByTimestampAsc()
return dependencies.getImportedTickersRepository()
.findByOrderByTimestampAsc()
.stream()
.map(TICKER_MAPPER::mapToTickerDTO)
.collect(Collectors.toCollection(LinkedList::new));
.toList();
}

/**
Expand All @@ -126,10 +126,11 @@ public final List<TickerDTO> getImportedTickers() {
* @return imported tickers
*/
public final List<TickerDTO> getImportedTickers(final CurrencyPairDTO currencyPair) {
return dependencies.getImportedTickersRepository().findByCurrencyPairOrderByTimestampAsc(currencyPair.toString())
return dependencies.getImportedTickersRepository()
.findByCurrencyPairOrderByTimestampAsc(currencyPair.toString())
.stream()
.map(TICKER_MAPPER::mapToTickerDTO)
.collect(Collectors.toCollection(LinkedList::new));
.toList();
}

// =================================================================================================================
Expand All @@ -143,7 +144,7 @@ public final List<TickerDTO> getImportedTickers(final CurrencyPairDTO currencyPa
public final Map<String, OrderDTO> getOrders() {
return dependencies.getOrderRepository().findByOrderByTimestampAsc()
.stream()
.filter(order -> order.getStrategy().getStrategyId().equals(getStrategyDTO().getStrategyId()))
.filter(order -> order.getStrategy().getStrategyId().equals(configuration.getStrategyId()))
.map(ORDER_MAPPER::mapToOrderDTO)
.collect(Collectors.toMap(OrderDTO::getOrderId, orderDTO -> orderDTO));
}
Expand Down Expand Up @@ -172,7 +173,7 @@ public final Optional<OrderDTO> getOrderByOrderId(final String orderId) {
public final Map<String, TradeDTO> getTrades() {
return dependencies.getTradeRepository().findByOrderByTimestampAsc()
.stream()
.filter(trade -> trade.getOrder().getStrategy().getStrategyId().equals(getStrategyDTO().getStrategyId()))
.filter(trade -> trade.getOrder().getStrategy().getStrategyId().equals(configuration.getStrategyId()))
.map(TRADE_MAPPER::mapToTradeDTO)
.collect(Collectors.toMap(TradeDTO::getTradeId, tradeDTO -> tradeDTO));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package tech.cassandre.trading.bot.strategy.internal;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
import tech.cassandre.trading.bot.dto.strategy.StrategyDTO;
import tech.cassandre.trading.bot.strategy.BasicCassandreStrategy;
import tech.cassandre.trading.bot.strategy.BasicTa4jCassandreStrategy;

import static lombok.AccessLevel.PRIVATE;

/**
* CassandreStrategyConfiguration contains the configuration of the strategy.
* <p>
* These are the classes used to manage a position.
* - CassandreStrategyInterface list the methods a strategy type must implement to be able to interact with the Cassandre framework.
* - CassandreStrategyConfiguration contains the configuration of the strategy.
* - CassandreStrategyDependencies contains all the dependencies required by a strategy and provided by the Cassandre framework.
* - CassandreStrategyImplementation is the default implementation of CassandreStrategyInterface, this code manages the interaction between Cassandre framework and a strategy.
* - CassandreStrategy (class) is the class that every strategy used by user ({@link BasicCassandreStrategy} or {@link BasicTa4jCassandreStrategy}) must extend. It contains methods to access data and manage orders, trades, positions.
* - CassandreStrategy (interface) is the annotation allowing you Cassandre to recognize a user strategy.
* - BasicCassandreStrategy - User inherits this class this one to make a basic strategy.
* - BasicCassandreStrategy - User inherits this class this one to make a strategy with ta4j.
*/
@Value
@Builder
@AllArgsConstructor(access = PRIVATE)
@SuppressWarnings("checkstyle:VisibilityModifier")
public class CassandreStrategyConfiguration {

/** Strategy. */
StrategyDTO strategyDTO;

/** Dry mode. */
boolean dryMode;

/**
* Returns strategy uid in database.
*
* @return strategy uid
*/
long getStrategyUid() {
return strategyDTO.getUid();
}

/**
* Returns strategy id in annotation.
*
* @return strategy id
*/
String getStrategyId() {
return strategyDTO.getStrategyId();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import lombok.Builder;
import lombok.Value;
import tech.cassandre.trading.bot.batch.PositionFlux;
import tech.cassandre.trading.bot.dto.strategy.StrategyDTO;
import tech.cassandre.trading.bot.repository.ImportedTickersRepository;
import tech.cassandre.trading.bot.repository.OrderRepository;
import tech.cassandre.trading.bot.repository.PositionRepository;
Expand All @@ -22,6 +21,7 @@
* <p>
* These are the classes used to manage a position.
* - CassandreStrategyInterface list the methods a strategy type must implement to be able to interact with the Cassandre framework.
* - CassandreStrategyConfiguration contains the configuration of the strategy.
* - CassandreStrategyDependencies contains all the dependencies required by a strategy and provided by the Cassandre framework.
* - CassandreStrategyImplementation is the default implementation of CassandreStrategyInterface, this code manages the interaction between Cassandre framework and a strategy.
* - CassandreStrategy (class) is the class that every strategy used by user ({@link BasicCassandreStrategy} or {@link BasicTa4jCassandreStrategy}) must extend. It contains methods to access data and manage orders, trades, positions.
Expand All @@ -35,12 +35,6 @@
@SuppressWarnings("checkstyle:VisibilityModifier")
public class CassandreStrategyDependencies {

// =================================================================================================================
// Data.

/** Strategy. */
StrategyDTO strategy;

// =================================================================================================================
// Flux.

Expand Down

0 comments on commit 8d17d70

Please sign in to comment.