Search in sources :

Example 1 with CsvToBeanBuilder

use of com.opencsv.bean.CsvToBeanBuilder in project cassandre-trading-bot by cassandre-tech.

the class StrategiesAutoConfiguration method loadImportedTickers.

/**
 * Load imported tickers into database.
 */
private void loadImportedTickers() {
    // Deleting everything before import.
    importedTickersRepository.deleteAllInBatch();
    // Getting the list of files to import and insert them in database.
    logger.info("Importing tickers...");
    AtomicLong counter = new AtomicLong(0);
    getFilesToLoad().parallelStream().filter(resource -> resource.getFilename() != null).peek(resource -> logger.info("Importing file {}.", resource.getFilename())).forEach(resource -> {
        try {
            // Insert the tickers in database.
            new CsvToBeanBuilder<ImportedTicker>(Files.newBufferedReader(resource.getFile().toPath())).withType(ImportedTicker.class).withIgnoreLeadingWhiteSpace(true).build().parse().forEach(importedTicker -> {
                logger.debug("Importing ticker {}.", importedTicker);
                importedTicker.setId(counter.incrementAndGet());
                importedTickersRepository.save(importedTicker);
            });
        } catch (IOException e) {
            logger.error("Impossible to load imported tickers: {}.", e.getMessage());
        }
    });
    logger.info("{} tickers imported.", importedTickersRepository.count());
}
Also used : Arrays(java.util.Arrays) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TradeService(tech.cassandre.trading.bot.service.TradeService) ExchangeParameters(tech.cassandre.trading.bot.util.parameters.ExchangeParameters) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) StrategyRepository(tech.cassandre.trading.bot.repository.StrategyRepository) BASIC_STRATEGY(tech.cassandre.trading.bot.dto.strategy.StrategyTypeDTO.BASIC_STRATEGY) TradeFlux(tech.cassandre.trading.bot.batch.TradeFlux) CsvToBeanBuilder(com.opencsv.bean.CsvToBeanBuilder) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) Map(java.util.Map) OrderFlux(tech.cassandre.trading.bot.batch.OrderFlux) Resource(org.springframework.core.io.Resource) ImportedTicker(tech.cassandre.trading.bot.domain.ImportedTicker) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) UserService(tech.cassandre.trading.bot.service.UserService) AccountDTO(tech.cassandre.trading.bot.dto.user.AccountDTO) PositionRepository(tech.cassandre.trading.bot.repository.PositionRepository) ConfigurationException(tech.cassandre.trading.bot.util.exception.ConfigurationException) PositionService(tech.cassandre.trading.bot.service.PositionService) Set(java.util.Set) ZERO(java.math.BigDecimal.ZERO) TickerFlux(tech.cassandre.trading.bot.batch.TickerFlux) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) Collectors(java.util.stream.Collectors) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) UserDTO(tech.cassandre.trading.bot.dto.user.UserDTO) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) OrderRepository(tech.cassandre.trading.bot.repository.OrderRepository) Stream(java.util.stream.Stream) PositionServiceCassandreImplementation(tech.cassandre.trading.bot.service.PositionServiceCassandreImplementation) CassandreStrategy(tech.cassandre.trading.bot.strategy.CassandreStrategy) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) CassandreStrategyInterface(tech.cassandre.trading.bot.strategy.CassandreStrategyInterface) TradeRepository(tech.cassandre.trading.bot.repository.TradeRepository) TickerDTO(tech.cassandre.trading.bot.dto.market.TickerDTO) BASIC_TA4J_STRATEGY(tech.cassandre.trading.bot.dto.strategy.StrategyTypeDTO.BASIC_TA4J_STRATEGY) Strategy(tech.cassandre.trading.bot.domain.Strategy) BasicCassandreStrategy(tech.cassandre.trading.bot.strategy.BasicCassandreStrategy) HashSet(java.util.HashSet) OPENING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENING) StrategyDTO(tech.cassandre.trading.bot.dto.strategy.StrategyDTO) ConnectableFlux(reactor.core.publisher.ConnectableFlux) PositionFlux(tech.cassandre.trading.bot.batch.PositionFlux) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) ExchangeService(tech.cassandre.trading.bot.service.ExchangeService) BaseConfiguration(tech.cassandre.trading.bot.util.base.configuration.BaseConfiguration) ImportedTickersRepository(tech.cassandre.trading.bot.repository.ImportedTickersRepository) BasicTa4jCassandreStrategy(tech.cassandre.trading.bot.strategy.BasicTa4jCassandreStrategy) Files(java.nio.file.Files) IOException(java.io.IOException) CLOSING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSING) ApplicationContext(org.springframework.context.ApplicationContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) AccountFlux(tech.cassandre.trading.bot.batch.AccountFlux) Bean(org.springframework.context.annotation.Bean) Collections(java.util.Collections) AtomicLong(java.util.concurrent.atomic.AtomicLong) IOException(java.io.IOException) ImportedTicker(tech.cassandre.trading.bot.domain.ImportedTicker)

Example 2 with CsvToBeanBuilder

use of com.opencsv.bean.CsvToBeanBuilder in project Java-Tutorial by gpcodervn.

the class ParseCsvToBean method parseCSVtoBean.

public static void parseCSVtoBean(String filename) throws FileNotFoundException {
    ColumnPositionMappingStrategy<Country> strategy = new ColumnPositionMappingStrategy<Country>();
    strategy.setType(Country.class);
    String[] columns = new String[] { "id", "code", "name" };
    strategy.setColumnMapping(columns);
    CsvToBean<Country> csvToBean = new CsvToBeanBuilder<Country>(new FileReader(filename)).withMappingStrategy(strategy).withSeparator(DEFAULT_SEPARATOR).withQuoteChar(DEFAULT_QUOTE).withSkipLines(NUM_OF_LINE_SKIP).withIgnoreLeadingWhiteSpace(true).build();
    List<Country> countries = csvToBean.parse();
    for (Country country : countries) {
        System.out.println(country);
    }
}
Also used : ColumnPositionMappingStrategy(com.opencsv.bean.ColumnPositionMappingStrategy) CsvToBeanBuilder(com.opencsv.bean.CsvToBeanBuilder) FileReader(java.io.FileReader)

Example 3 with CsvToBeanBuilder

use of com.opencsv.bean.CsvToBeanBuilder in project di-authentication-api by alphagov.

the class DataMigrationHandler method handleRequest.

@Override
public String handleRequest(S3Event input, Context context) {
    for (S3EventNotification.S3EventNotificationRecord record : input.getRecords()) {
        String s3Key = record.getS3().getObject().getKey();
        String s3Bucket = record.getS3().getBucket().getName();
        LOG.info("New data transfer file {} detected", s3Key);
        S3Object object = client.getObject(s3Bucket, s3Key);
        InputStreamReader reader = new InputStreamReader(object.getObjectContent());
        CsvToBean<ImportRecord> importRecords = new CsvToBeanBuilder<ImportRecord>(reader).withType(ImportRecord.class).build();
        var records = importRecords.parse();
        int skip = 0;
        int count;
        do {
            var importBatch = records.stream().skip(skip).limit(BATCH_SIZE).collect(Collectors.toList());
            count = importBatch.size();
            skip = skip + count;
            LOG.info("Read {} records starting at {}", count, skip);
            var batch = buildImportBatch(importBatch, configurationService.getTermsAndConditionsVersion());
            authenticationService.bulkAdd(batch.stream().map(p -> p.getLeft()).collect(Collectors.toList()), batch.stream().map(p -> p.getRight()).collect(Collectors.toList()));
        } while (count == BATCH_SIZE);
        LOG.info("Imported {} records", skip);
    }
    return "Complete";
}
Also used : S3EventNotification(com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification) CsvToBeanBuilder(com.opencsv.bean.CsvToBeanBuilder) InputStreamReader(java.io.InputStreamReader) S3Object(com.amazonaws.services.s3.model.S3Object)

Example 4 with CsvToBeanBuilder

use of com.opencsv.bean.CsvToBeanBuilder in project cassandre-trading-bot by cassandre-tech.

the class TickerFluxMock method marketService.

@Bean
@Primary
public MarketService marketService() {
    // Removes everything from table.
    backtestingCandleRepository.deleteAllInBatch();
    // Creates the mock.
    marketServiceBacktestingImplementation = new MarketServiceBacktestingImplementation(orderFlux, tradeFlux, orderRepository, tradeRepository, backtestingCandleRepository);
    // Getting the list of files to import and insert them in database.
    logger.info("Importing candles for backtesting...");
    Set<CurrencyPairDTO> currencyPairUsed = new HashSet<>();
    getCandlesFilesToLoad().stream().filter(resource -> resource.getFilename() != null).peek(resource -> logger.info("Importing {}...", resource.getFilename())).forEach(resource -> {
        try {
            // Insert the tickers in database.
            AtomicLong sequence = new AtomicLong(1);
            new CsvToBeanBuilder<ImportedCandle>(Files.newBufferedReader(resource.getFile().toPath())).withType(ImportedCandle.class).withIgnoreLeadingWhiteSpace(true).build().parse().forEach(importedCandle -> {
                logger.debug("Importing candle {}", importedCandle);
                BacktestingCandle candle = backtestingTickerMapper.mapToBacktestingCandle(importedCandle);
                // Specific fields in Backtesting candle.
                BacktestingCandleId id = new BacktestingCandleId();
                id.setTestSessionId(marketServiceBacktestingImplementation.getTestSessionId());
                id.setResponseSequenceId(sequence.getAndIncrement());
                id.setCurrencyPair(importedCandle.getCurrencyPair());
                candle.setId(id);
                // Save in database.
                backtestingCandleRepository.save(candle);
                // We build a list of currency pairs listed in files.
                currencyPairUsed.add(id.getCurrencyPairDTO());
            });
        } catch (IOException e) {
            logger.error("Impossible to load candles for backtesting: {}", e.getMessage());
        }
    });
    // Setting the flux size of each currency pair.
    currencyPairUsed.forEach(currencyPairDTO -> marketServiceBacktestingImplementation.getFluxSize().put(currencyPairDTO, backtestingCandleRepository.findByIdCurrencyPair(currencyPairDTO.toString()).size()));
    return marketServiceBacktestingImplementation;
}
Also used : Primary(org.springframework.context.annotation.Primary) Arrays(java.util.Arrays) RequiredArgsConstructor(lombok.RequiredArgsConstructor) LoggerFactory(org.slf4j.LoggerFactory) TestConfiguration(org.springframework.boot.test.context.TestConfiguration) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) HashSet(java.util.HashSet) TradeFlux(tech.cassandre.trading.bot.batch.TradeFlux) CsvToBeanBuilder(com.opencsv.bean.CsvToBeanBuilder) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) BacktestingTickerMapper(tech.cassandre.trading.bot.util.mapper.BacktestingTickerMapper) Mappers(org.mapstruct.factory.Mappers) OrderFlux(tech.cassandre.trading.bot.batch.OrderFlux) BacktestingCandleRepository(tech.cassandre.trading.bot.repository.BacktestingCandleRepository) MarketServiceBacktestingImplementation(tech.cassandre.trading.bot.service.MarketServiceBacktestingImplementation) Resource(org.springframework.core.io.Resource) Logger(org.slf4j.Logger) BacktestingCandleId(tech.cassandre.trading.bot.domain.BacktestingCandleId) Files(java.nio.file.Files) Set(java.util.Set) TickerFlux(tech.cassandre.trading.bot.batch.TickerFlux) IOException(java.io.IOException) ApplicationContext(org.springframework.context.ApplicationContext) ImportedCandle(tech.cassandre.trading.bot.domain.ImportedCandle) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) OrderRepository(tech.cassandre.trading.bot.repository.OrderRepository) MarketService(tech.cassandre.trading.bot.service.MarketService) Bean(org.springframework.context.annotation.Bean) TradeRepository(tech.cassandre.trading.bot.repository.TradeRepository) BacktestingCandle(tech.cassandre.trading.bot.domain.BacktestingCandle) Collections(java.util.Collections) AtomicLong(java.util.concurrent.atomic.AtomicLong) ImportedCandle(tech.cassandre.trading.bot.domain.ImportedCandle) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) MarketServiceBacktestingImplementation(tech.cassandre.trading.bot.service.MarketServiceBacktestingImplementation) IOException(java.io.IOException) BacktestingCandle(tech.cassandre.trading.bot.domain.BacktestingCandle) BacktestingCandleId(tech.cassandre.trading.bot.domain.BacktestingCandleId) HashSet(java.util.HashSet) Primary(org.springframework.context.annotation.Primary) Bean(org.springframework.context.annotation.Bean)

Example 5 with CsvToBeanBuilder

use of com.opencsv.bean.CsvToBeanBuilder in project cassandre-trading-bot by cassandre-tech.

the class StrategiesAutoConfiguration method loadCandlesFromFiles.

/**
 * Load candles in database.
 */
private void loadCandlesFromFiles() {
    // Deleting everything before import.
    importedCandleRepository.deleteAllInBatch();
    // Getting the list of files to import and insert them in database.
    logger.info("Importing candles...");
    AtomicLong counter = new AtomicLong(0);
    getFilesToLoad("classpath*:candles-to-import*csv").stream().filter(resource -> resource.getFilename() != null).peek(resource -> logger.info("Importing candles from {}", resource.getFilename())).forEach(resource -> {
        try {
            // Insert the tickers in database.
            new CsvToBeanBuilder<ImportedCandle>(Files.newBufferedReader(resource.getFile().toPath())).withType(ImportedCandle.class).withIgnoreLeadingWhiteSpace(true).build().parse().forEach(importedCandle -> {
                logger.debug("Importing candle {}", importedCandle);
                importedCandle.setUid(counter.incrementAndGet());
                importedCandleRepository.save(importedCandle);
            });
        } catch (IOException e) {
            logger.error("Impossible to load imported candles: {}", e.getMessage());
        }
    });
    logger.info("{} candles imported", importedCandleRepository.count());
}
Also used : Arrays(java.util.Arrays) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TradeService(tech.cassandre.trading.bot.service.TradeService) ExchangeParameters(tech.cassandre.trading.bot.util.parameters.ExchangeParameters) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) StrategyRepository(tech.cassandre.trading.bot.repository.StrategyRepository) CassandreStrategyInterface(tech.cassandre.trading.bot.strategy.internal.CassandreStrategyInterface) TradeFlux(tech.cassandre.trading.bot.batch.TradeFlux) CsvToBeanBuilder(com.opencsv.bean.CsvToBeanBuilder) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) Map(java.util.Map) OrderFlux(tech.cassandre.trading.bot.batch.OrderFlux) Resource(org.springframework.core.io.Resource) ImportedTicker(tech.cassandre.trading.bot.domain.ImportedTicker) PositionDTO(tech.cassandre.trading.bot.dto.position.PositionDTO) UserService(tech.cassandre.trading.bot.service.UserService) AccountDTO(tech.cassandre.trading.bot.dto.user.AccountDTO) PositionRepository(tech.cassandre.trading.bot.repository.PositionRepository) ConfigurationException(tech.cassandre.trading.bot.util.exception.ConfigurationException) PositionService(tech.cassandre.trading.bot.service.PositionService) Set(java.util.Set) ZERO(java.math.BigDecimal.ZERO) TickerFlux(tech.cassandre.trading.bot.batch.TickerFlux) TradeDTO(tech.cassandre.trading.bot.dto.trade.TradeDTO) Collectors(java.util.stream.Collectors) OrderDTO(tech.cassandre.trading.bot.dto.trade.OrderDTO) UserDTO(tech.cassandre.trading.bot.dto.user.UserDTO) ImportedTickerRepository(tech.cassandre.trading.bot.repository.ImportedTickerRepository) Configuration(org.springframework.context.annotation.Configuration) ImportedCandle(tech.cassandre.trading.bot.domain.ImportedCandle) List(java.util.List) OrderRepository(tech.cassandre.trading.bot.repository.OrderRepository) Stream(java.util.stream.Stream) CassandreStrategy(tech.cassandre.trading.bot.strategy.CassandreStrategy) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) TradeRepository(tech.cassandre.trading.bot.repository.TradeRepository) TickerDTO(tech.cassandre.trading.bot.dto.market.TickerDTO) Strategy(tech.cassandre.trading.bot.domain.Strategy) HashSet(java.util.HashSet) OPENING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.OPENING) StrategyDTO(tech.cassandre.trading.bot.dto.strategy.StrategyDTO) ConnectableFlux(reactor.core.publisher.ConnectableFlux) PositionFlux(tech.cassandre.trading.bot.batch.PositionFlux) ImportedCandleRepository(tech.cassandre.trading.bot.repository.ImportedCandleRepository) CurrencyPairDTO(tech.cassandre.trading.bot.dto.util.CurrencyPairDTO) ExchangeService(tech.cassandre.trading.bot.service.ExchangeService) BaseConfiguration(tech.cassandre.trading.bot.util.base.configuration.BaseConfiguration) Files(java.nio.file.Files) CassandreStrategyDependencies(tech.cassandre.trading.bot.strategy.internal.CassandreStrategyDependencies) IOException(java.io.IOException) CassandreStrategyConfiguration(tech.cassandre.trading.bot.strategy.internal.CassandreStrategyConfiguration) CLOSING(tech.cassandre.trading.bot.dto.position.PositionStatusDTO.CLOSING) ApplicationContext(org.springframework.context.ApplicationContext) AtomicLong(java.util.concurrent.atomic.AtomicLong) AccountFlux(tech.cassandre.trading.bot.batch.AccountFlux) Collections(java.util.Collections) AtomicLong(java.util.concurrent.atomic.AtomicLong) ImportedCandle(tech.cassandre.trading.bot.domain.ImportedCandle) IOException(java.io.IOException)

Aggregations

CsvToBeanBuilder (com.opencsv.bean.CsvToBeanBuilder)13 IOException (java.io.IOException)7 Files (java.nio.file.Files)4 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 HashSet (java.util.HashSet)4 List (java.util.List)4 Set (java.util.Set)4 AtomicLong (java.util.concurrent.atomic.AtomicLong)4 Collectors (java.util.stream.Collectors)4 File (java.io.File)3 FileReader (java.io.FileReader)3 Reader (java.io.Reader)3 ZERO (java.math.BigDecimal.ZERO)3 Map (java.util.Map)3 Optional (java.util.Optional)3 RequiredArgsConstructor (lombok.RequiredArgsConstructor)3 ApplicationContext (org.springframework.context.ApplicationContext)3 Resource (org.springframework.core.io.Resource)3 PathMatchingResourcePatternResolver (org.springframework.core.io.support.PathMatchingResourcePatternResolver)3