Skip to content

Commit

Permalink
Starter - configuration review #880
Browse files Browse the repository at this point in the history
  • Loading branch information
straumat committed Jan 31, 2022
1 parent 3eb87fc commit d34c39a
Show file tree
Hide file tree
Showing 10 changed files with 196 additions and 208 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ sudo apt-get -y install git

## [Java](https://openjdk.java.net/install/)
```bash
sudo apt-get -y install openjdk-11-jdk
sudo apt-get -y install openjdk-17-jdk
```

## [Maven](https://maven.apache.org/)
Expand Down
3 changes: 2 additions & 1 deletion docs/docs/ressources/how-tos/how-to-review-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ description: How to review Cassandre code
* No new line between method start ({) and method end (}).
* When a variable represents an id, say it in the name like 'carId'.
* When a variable is DTO, say it in the name like `carDTO`.
* Check logs texts.
* Check logs texts.
* No point at the end of logs texts.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public GraphQLAPIKeyAuthenticationManager(final String newKey) {
public final Authentication authenticate(final Authentication authentication) throws AuthenticationException {
String principal = (String) authentication.getPrincipal();
if (key != null && !key.equals(principal)) {
throw new BadCredentialsException("The API key was not found or not the expected value.");
throw new BadCredentialsException("The API key was not found or not the expected valueUnknownExchangeTest.checkErrorMessages");
}
authentication.setAuthenticated(true);
return authentication;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
* DatabaseAutoConfiguration configures the database.
*/
@Configuration
@EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider")
@EntityScan(basePackages = "tech.cassandre.trading.bot.domain")
@EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider")
@EnableJpaRepositories(basePackages = "tech.cassandre.trading.bot.repository")
public class DatabaseAutoConfiguration extends BaseConfiguration {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,6 @@
@RequiredArgsConstructor
public class ExchangeAutoConfiguration extends BaseConfiguration {

/** XChange user sandbox parameter. */
private static final String USE_SANDBOX_PARAMETER = "Use_Sandbox";

/** XChange passphrase parameter. */
private static final String PASSPHRASE_PARAMETER = "passphrase";

/** Unauthorized http status code. */
private static final int UNAUTHORIZED_STATUS_CODE = 401;

Expand Down Expand Up @@ -112,34 +106,22 @@ public class ExchangeAutoConfiguration extends BaseConfiguration {
@PostConstruct
public void configure() {
try {
// Instantiate exchange.
// Instantiate exchange class.
Class<? extends Exchange> exchangeClass = Class.forName(getExchangeClassName()).asSubclass(Exchange.class);
ExchangeSpecification exchangeSpecification = new ExchangeSpecification(exchangeClass);

// Exchange configuration.
exchangeSpecification.setExchangeSpecificParametersItem(USE_SANDBOX_PARAMETER, exchangeParameters.getModes().getSandbox());
exchangeSpecification.setUserName(exchangeParameters.getUsername());
exchangeSpecification.setExchangeSpecificParametersItem(PASSPHRASE_PARAMETER, exchangeParameters.getPassphrase());
exchangeSpecification.setApiKey(exchangeParameters.getKey());
exchangeSpecification.setSecretKey(exchangeParameters.getSecret());
exchangeSpecification.getResilience().setRateLimiterEnabled(true);

// Specific parameters.
if (exchangeParameters.getProxyHost() != null) {
exchangeSpecification.setProxyHost(exchangeParameters.getProxyHost());
}
if (exchangeParameters.getProxyPort() != null) {
exchangeSpecification.setProxyPort(exchangeParameters.getProxyPort());
}
if (exchangeParameters.getSslUri() != null) {
exchangeSpecification.setSslUri(exchangeParameters.getSslUri());
}
if (exchangeParameters.getPlainTextUri() != null) {
exchangeSpecification.setPlainTextUri(exchangeParameters.getPlainTextUri());
}
if (exchangeParameters.getHost() != null) {
exchangeSpecification.setHost(exchangeParameters.getHost());
}
exchangeSpecification.setExchangeSpecificParametersItem("Use_Sandbox", exchangeParameters.getModes().getSandbox());
exchangeSpecification.setExchangeSpecificParametersItem("passphrase", exchangeParameters.getPassphrase());
exchangeSpecification.setProxyHost(exchangeParameters.getProxyHost());
exchangeSpecification.setProxyPort(exchangeParameters.getProxyPort());
exchangeSpecification.setSslUri(exchangeParameters.getSslUri());
exchangeSpecification.setPlainTextUri(exchangeParameters.getPlainTextUri());
exchangeSpecification.setHost(exchangeParameters.getHost());
if (exchangeParameters.getPort() != null) {
exchangeSpecification.setPort(Integer.parseInt(exchangeParameters.getPort()));
}
Expand All @@ -151,16 +133,16 @@ public void configure() {
xChangeTradeService = xChangeExchange.getTradeService();

// Force login to check credentials.
logger.info("Exchange connection with {} driver.", exchangeParameters.getDriverClassName());
logger.info("Exchange connection with driver {}", exchangeParameters.getDriverClassName());
xChangeAccountService.getAccountInfo();
logger.info("Exchange connection with username {} successful (Dry mode: {} / Sandbox: {})",
logger.info("Exchange connection successful with username {} (Dry mode: {} / Sandbox: {})",
exchangeParameters.getUsername(),
exchangeParameters.getModes().getDry(),
exchangeParameters.getModes().getSandbox());
} catch (ClassNotFoundException e) {
// If we can't find the exchange class.
throw new ConfigurationException("Impossible to find the exchange you requested: " + exchangeParameters.getDriverClassName(),
"Choose a valid exchange (https://github.com/knowm/XChange) and add the dependency to Cassandre");
throw new ConfigurationException("Impossible to find the exchange driver class you requested: " + exchangeParameters.getDriverClassName(),
"Choose and configure a valid exchange (https://trading-bot.cassandre.tech/learn/exchange-connection-configuration.html#how-does-it-works)");
} catch (HttpStatusIOException e) {
if (e.getHttpStatusCode() == UNAUTHORIZED_STATUS_CODE) {
// Authorization failure.
Expand All @@ -182,23 +164,18 @@ public void configure() {
* @return XChange class name
*/
private String getExchangeClassName() {
// If the name contains a dot, it means that it's the XChange class name.
// If the name contains a dot, it means that the user set the complete XChange class name in the configuration.
if (exchangeParameters.getDriverClassName() != null && exchangeParameters.getDriverClassName().contains(".")) {
return exchangeParameters.getDriverClassName();
} else {
// Try to guess the XChange class package name from the exchange name parameter.
return "org.knowm.xchange." // Package (org.knowm.xchange.).
.concat(exchangeParameters.getDriverClassName().toLowerCase()) // domain (kucoin).
.concat(".") // A dot (.)
.concat(exchangeParameters.getDriverClassName().substring(0, 1).toUpperCase()) // First letter uppercase (K).
.concat(exchangeParameters.getDriverClassName().substring(1).toLowerCase()) // The rest of the exchange name (ucoin).
.concat("Exchange"); // Adding exchange (Exchange).
}

// XChange class package name and suffix.
final String xChangeClassPackage = "org.knowm.xchange.";
final String xChangeCLassSuffix = "Exchange";

// Returns the XChange package name from exchange name.
assert exchangeParameters.getDriverClassName() != null;
return xChangeClassPackage // Package (org.knowm.xchange.).
.concat(exchangeParameters.getDriverClassName().toLowerCase()) // domain (kucoin).
.concat(".") // A dot (.)
.concat(exchangeParameters.getDriverClassName().substring(0, 1).toUpperCase()) // First letter uppercase (K).
.concat(exchangeParameters.getDriverClassName().substring(1).toLowerCase()) // The rest of the exchange name (ucoin).
.concat(xChangeCLassSuffix); // Adding exchange (Exchange).
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,26 @@

/**
* ScheduleAutoConfiguration configures the flux calls.
* Three scheduled tasks:
* - One calling account flux.
* - One calling ticker flux.
* - One calling order & trade flux.
*/
@Configuration
@Profile("!schedule-disabled")
@Configuration
@EnableScheduling
@RequiredArgsConstructor
public class ScheduleAutoConfiguration extends BaseConfiguration {

/** Scheduler pool size. */
private static final int SCHEDULER_POOL_SIZE = 3;

/** Start delay in milliseconds. */
/** Start delay in milliseconds (1 000 ms = 1 second). */
private static final int START_DELAY_IN_MILLISECONDS = 1_000;

/** Termination delay in milliseconds. */
/** Termination delay in milliseconds (10 000 ms = 10 seconds). */
private static final int TERMINATION_DELAY_IN_MILLISECONDS = 10_000;

/** Thread prefix for schedulers. */
private static final String THREAD_NAME_PREFIX = "cassandre-flux-";

/** Flux continues to run as long as enabled is set to true. */
private final AtomicBoolean enabled = new AtomicBoolean(true);

Expand All @@ -53,28 +54,6 @@ public class ScheduleAutoConfiguration extends BaseConfiguration {
/** Trade flux. */
private final TradeFlux tradeFlux;

/**
* Configure the task scheduler.
*
* @return task scheduler
*/
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationMillis(TERMINATION_DELAY_IN_MILLISECONDS);
scheduler.setThreadNamePrefix(THREAD_NAME_PREFIX);
scheduler.setPoolSize(SCHEDULER_POOL_SIZE);
scheduler.setErrorHandler(t -> {
try {
logger.error("Error in scheduled tasks: {}", t.getMessage());
} catch (Exception e) {
logger.error("Error in scheduled tasks: {}", e.getMessage());
}
});
return scheduler;
}

/**
* Recurrent calls to the account flux.
*/
Expand Down Expand Up @@ -108,11 +87,33 @@ public void orderAndTradeFluxUpdate() {

/**
* This method is called before the application shutdown.
* We stop the flux.
* We stop calling the flux.
*/
@PreDestroy
public void shutdown() {
enabled.set(false);
}

/**
* Configure the task scheduler.
*
* @return task scheduler
*/
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationMillis(TERMINATION_DELAY_IN_MILLISECONDS);
scheduler.setThreadNamePrefix("cassandre-flux-");
scheduler.setPoolSize(SCHEDULER_POOL_SIZE);
scheduler.setErrorHandler(throwable -> {
try {
logger.error("Error in scheduled tasks: {}", throwable.getMessage());
} catch (Exception exception) {
logger.error("Error in scheduled tasks: {}", exception.getMessage());
}
});
return scheduler;
}

}

0 comments on commit d34c39a

Please sign in to comment.