Search in sources :

Example 1 with ApplicationArguments

use of org.springframework.boot.ApplicationArguments in project spring-native by spring-projects-experimental.

the class BuildTimeTestSpringApplication method run.

@Override
public GenericApplicationContext run(String... args) {
    ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    GenericApplicationContext context = createContext();
    context.setEnvironment(prepareEnvironment());
    prepareContext(context, applicationArguments);
    return context;
}
Also used : GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) ApplicationArguments(org.springframework.boot.ApplicationArguments) DefaultApplicationArguments(org.springframework.boot.DefaultApplicationArguments) DefaultApplicationArguments(org.springframework.boot.DefaultApplicationArguments)

Example 2 with ApplicationArguments

use of org.springframework.boot.ApplicationArguments in project bitcoin-spring-boot-starter by theborakompanioni.

the class KrakenBalanceCommandRunner method doRun.

@Override
@SneakyThrows
protected void doRun(ApplicationArguments args) {
    log.debug("Fetch balance on exchange {}", exchange);
    KrakenAccountService accountService = (KrakenAccountService) exchange.getAccountService();
    Map<String, BigDecimal> krakenBalance = accountService.getKrakenBalance();
    Map<String, BigDecimal> krakenPositiveBalances = krakenBalance.entrySet().stream().filter(it -> it.getValue().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    if (krakenPositiveBalances.isEmpty()) {
        System.out.println("❌ There is no currency pair with a positive balance.");
    } else {
        krakenPositiveBalances.forEach((currencyCode, balance) -> {
            System.out.printf("💰 %5s:\t%s%n", currencyCode, balance.toPlainString());
        });
    }
}
Also used : BigDecimal(java.math.BigDecimal) Slf4j(lombok.extern.slf4j.Slf4j) ApplicationArguments(org.springframework.boot.ApplicationArguments) SneakyThrows(lombok.SneakyThrows) KrakenExchange(org.knowm.xchange.kraken.KrakenExchange) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) Collectors(java.util.stream.Collectors) KrakenAccountService(org.knowm.xchange.kraken.service.KrakenAccountService) KrakenAccountService(org.knowm.xchange.kraken.service.KrakenAccountService) Map(java.util.Map) BigDecimal(java.math.BigDecimal) SneakyThrows(lombok.SneakyThrows)

Example 3 with ApplicationArguments

use of org.springframework.boot.ApplicationArguments in project bitcoin-spring-boot-starter by theborakompanioni.

the class KrakenRebalanceCommandRunner method doRun.

@Override
@SneakyThrows({ IllegalStateException.class, IOException.class })
protected void doRun(ApplicationArguments args) {
    log.debug("Calculate rebalance on exchange {}", exchange);
    if (!dryRun.isEnabled()) {
        throw new IllegalStateException("Currently only implemented with '--dry-run' option");
    }
    BigDecimal bitcoinTargetPercentage = Optional.ofNullable(args.getOptionValues("target")).flatMap(it -> it.stream().findFirst()).map(BigDecimal::new).orElse(defaultBitcoinTargetPercentage);
    // target percentage must be between 0 and 1
    boolean targetParamIsWithinBounds = bitcoinTargetPercentage.compareTo(BigDecimal.ZERO) >= 0 && bitcoinTargetPercentage.compareTo(BigDecimal.ONE) <= 0;
    if (!targetParamIsWithinBounds) {
        throw new IllegalStateException("Invalid target percentage param: " + bitcoinTargetPercentage);
    }
    Currency bitcoin = Currency.BTC;
    Currency fiatCurrency = Currency.getInstance(properties.getFiatCurrency());
    CurrencyPair currencyPair = new CurrencyPair(bitcoin, fiatCurrency);
    boolean supportedCurrencyPair = exchange.getExchangeSymbols().contains(currencyPair);
    if (!supportedCurrencyPair) {
        throw new IllegalStateException("Currency pair is not supported: " + currencyPair);
    }
    // ---------------------------------------------- balance
    KrakenAccountService accountService = (KrakenAccountService) exchange.getAccountService();
    Map<String, BigDecimal> krakenBalance = accountService.getKrakenBalance();
    Map<String, BigDecimal> krakenPositiveBalances = krakenBalance.entrySet().stream().filter(it -> it.getValue().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    if (krakenPositiveBalances.isEmpty()) {
        System.out.println("❌ There is no currency pair with a positive balance.");
        return;
    }
    BigDecimal bitcoinBalanceValue = bitcoin.getCurrencyCodes().stream().filter(it -> krakenBalance.containsKey("X" + it)).map(it -> krakenBalance.get("X" + it)).findFirst().or(() -> Optional.ofNullable(krakenBalance.get(bitcoin.getCurrencyCode()))).orElse(BigDecimal.ZERO);
    Money bitcoinBalance = Money.of(bitcoinBalanceValue, bitcoinCurrencyUnit);
    BigDecimal fiatBalanceValue = Optional.ofNullable(krakenBalance.get("Z" + fiatCurrency.getCurrencyCode())).or(() -> Optional.ofNullable(krakenBalance.get(fiatCurrency.getCurrencyCode()))).orElse(BigDecimal.ZERO);
    Money fiatBalance = Money.of(fiatBalanceValue, fiatCurrency.getCurrencyCode());
    // ---------------------------------------------- balance - end
    // ---------------------------------------------- ask/bid
    KrakenMarketDataService marketDataService = (KrakenMarketDataService) exchange.getMarketDataService();
    Ticker ticker = marketDataService.getTicker(currencyPair);
    // ---------------------------------------------- ask/bid - end
    Money oneBitcoin = Money.of(BigDecimal.ONE, "BTC");
    Money oneBitcoinInFiat = Money.of(ticker.getAsk(), fiatCurrency.getCurrencyCode());
    System.out.printf("📎 %s = %s%n", moneyFormat.format(oneBitcoin), moneyFormat.format(oneBitcoinInFiat));
    Money bitcoinInFiat = oneBitcoinInFiat.multiply(bitcoinBalance.getNumber());
    Money totalInFiat = fiatBalance.add(bitcoinInFiat);
    Money fiatInBitcoin = Money.of(fiatBalance.divide(oneBitcoinInFiat.getNumber()).getNumber(), bitcoinCurrencyUnit);
    Money totalInBitcoin = bitcoinBalance.add(fiatInBitcoin);
    BigDecimal percentageOfBalanceInBtc = bitcoinBalance.getNumberStripped().divide(totalInBitcoin.getNumberStripped(), RoundingMode.HALF_UP).setScale(4, RoundingMode.HALF_UP).movePointRight(2);
    System.out.printf("💰 Balance BTC (%s%%): %s (%s)%n", percentageOfBalanceInBtc, moneyFormat.format(bitcoinBalance), moneyFormat.format(bitcoinInFiat));
    BigDecimal percentageOfBalanceInFiat = fiatInBitcoin.getNumberStripped().divide(totalInBitcoin.getNumberStripped(), RoundingMode.HALF_UP).setScale(4, RoundingMode.HALF_UP).movePointRight(2);
    System.out.printf("💰 Balance FIAT (%s%%): %s (%s)%n", percentageOfBalanceInFiat, moneyFormat.format(fiatBalance), moneyFormat.format(fiatInBitcoin));
    System.out.printf("   (_Hypothetical_ Total Balances: %s or %s)%n", moneyFormat.format(totalInBitcoin), moneyFormat.format(totalInFiat));
    Money bitcoinTargetBalance = totalInBitcoin.multiply(bitcoinTargetPercentage);
    System.out.printf("📎 Target Balance BTC (%s%%): %s%n", bitcoinTargetPercentage.multiply(BigDecimal.valueOf(100)), moneyFormat.format(bitcoinTargetBalance));
    Money missingBitcoin = bitcoinTargetBalance.subtract(bitcoinBalance);
    Money missingBitcoinInFiat = oneBitcoinInFiat.multiply(missingBitcoin.getNumber());
    MonetaryAmount source = missingBitcoinInFiat;
    MonetaryAmount target = missingBitcoin;
    boolean buyBitcoin = missingBitcoin.isPositive();
    if (!buyBitcoin) {
        MonetaryAmount tmp = source.abs();
        source = target.abs();
        target = tmp;
    }
    System.out.printf("📈 You should use %s to get %s%n", moneyFormat.format(source), moneyFormat.format(target));
}
Also used : BitcoinAutoDcaExampleProperties(org.tbk.bitcoin.autodca.example.BitcoinAutoDcaExampleProperties) ApplicationArguments(org.springframework.boot.ApplicationArguments) SneakyThrows(lombok.SneakyThrows) KrakenMarketDataService(org.knowm.xchange.kraken.service.KrakenMarketDataService) CurrencyUnit(javax.money.CurrencyUnit) MonetaryAmountFormat(javax.money.format.MonetaryAmountFormat) KrakenAccountService(org.knowm.xchange.kraken.service.KrakenAccountService) BigDecimal(java.math.BigDecimal) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) RoundingMode(java.math.RoundingMode) Monetary(javax.money.Monetary) Ticker(org.knowm.xchange.dto.marketdata.Ticker) DryRunOption(org.tbk.bitcoin.autodca.example.BitcoinAutoDcaExampleApplicationConfig.DryRunOption) Money(org.javamoney.moneta.Money) KrakenExchange(org.knowm.xchange.kraken.KrakenExchange) IOException(java.io.IOException) BitcoinAmountFormatProvider(org.tbk.bitcoin.format.BitcoinAmountFormatProvider) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) Currency(org.knowm.xchange.currency.Currency) MonetaryFormats(javax.money.format.MonetaryFormats) Optional(java.util.Optional) CurrencyPair(org.knowm.xchange.currency.CurrencyPair) MonetaryAmount(javax.money.MonetaryAmount) MonetaryAmount(javax.money.MonetaryAmount) KrakenMarketDataService(org.knowm.xchange.kraken.service.KrakenMarketDataService) Ticker(org.knowm.xchange.dto.marketdata.Ticker) BigDecimal(java.math.BigDecimal) Money(org.javamoney.moneta.Money) Currency(org.knowm.xchange.currency.Currency) KrakenAccountService(org.knowm.xchange.kraken.service.KrakenAccountService) Map(java.util.Map) CurrencyPair(org.knowm.xchange.currency.CurrencyPair) SneakyThrows(lombok.SneakyThrows)

Example 4 with ApplicationArguments

use of org.springframework.boot.ApplicationArguments in project bookmark by FleyX.

the class MqConfiguration method run.

@Override
public void run(ApplicationArguments args) {
    Map<String, Object> map = context.getBeansWithAnnotation(MqConsumer.class);
    map.values().forEach(item -> {
        if (!(item instanceof RedisConsumer)) {
            log.warn("注意检测到被@EsConsumer注解的类{}未实现RedisConsumer接口", item.getClass().getCanonicalName());
            return;
        }
        MqConsumer[] annotations = item.getClass().getAnnotationsByType(MqConsumer.class);
        MqConsumer annotation = annotations[0];
        topicMap.computeIfAbsent(annotation.value(), k -> new ArrayList<>()).add((RedisConsumer) item);
    });
    log.info("redis订阅信息汇总完毕!!!!!!");
    // 由一个线程始终循环获取es队列数据
    threadPoolExecutor.execute(loop());
}
Also used : ApplicationArguments(org.springframework.boot.ApplicationArguments) ApplicationRunner(org.springframework.boot.ApplicationRunner) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) MqConsumer(com.fanxb.bookmark.common.annotation.MqConsumer) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) ApplicationContext(org.springframework.context.ApplicationContext) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RedisConsumer(com.fanxb.bookmark.common.entity.redis.RedisConsumer) DisposableBean(org.springframework.beans.factory.DisposableBean) Map(java.util.Map) ThreadPoolFactory(com.fanxb.bookmark.common.factory.ThreadPoolFactory) RedisUtil(com.fanxb.bookmark.common.util.RedisUtil) MqConsumer(com.fanxb.bookmark.common.annotation.MqConsumer) RedisConsumer(com.fanxb.bookmark.common.entity.redis.RedisConsumer) ArrayList(java.util.ArrayList)

Example 5 with ApplicationArguments

use of org.springframework.boot.ApplicationArguments in project j-jdbc by jingshouyan.

the class DataInitAutoConfiguration method run.

@Override
public void run(ApplicationArguments args) {
    Map<String, VersionHandler> map = ctx.getBeansOfType(VersionHandler.class);
    List<VersionHandler> handlers = Lists.newArrayList(map.values());
    Collections.sort(handlers);
    String latest = versionDao.latestVersion().map(DataInitVersion::getVersion).orElse("");
    handlers.stream().filter(h -> isNew(h.version(), latest)).forEach(h -> {
        DataInitVersion version = new DataInitVersion();
        version.setVersion(h.version());
        version.setClazz(h.getClass().getName());
        versionDao.insert(version);
        try {
            h.action();
            version.setSuccess(true);
            versionDao.update(version);
        } catch (Throwable e) {
            version.setSuccess(false);
            version.setMessage(e.getMessage());
            version.forDelete();
            versionDao.update(version);
            throw e;
        }
    });
}
Also used : Ordered(org.springframework.core.Ordered) Order(org.springframework.core.annotation.Order) ApplicationArguments(org.springframework.boot.ApplicationArguments) VersionHandler(com.github.jingshouyan.jdbc.data.init.action.VersionHandler) ApplicationRunner(org.springframework.boot.ApplicationRunner) VersionUtil(com.github.jingshouyan.jdbc.comm.util.VersionUtil) Autowired(org.springframework.beans.factory.annotation.Autowired) DataInitVersionDao(com.github.jingshouyan.jdbc.data.init.dao.DataInitVersionDao) ApplicationContext(org.springframework.context.ApplicationContext) ComponentScan(org.springframework.context.annotation.ComponentScan) Configuration(org.springframework.context.annotation.Configuration) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Lists(com.google.common.collect.Lists) DataInitVersion(com.github.jingshouyan.jdbc.data.init.entity.DataInitVersion) Map(java.util.Map) Collections(java.util.Collections) DataInitVersion(com.github.jingshouyan.jdbc.data.init.entity.DataInitVersion) VersionHandler(com.github.jingshouyan.jdbc.data.init.action.VersionHandler)

Aggregations

ApplicationArguments (org.springframework.boot.ApplicationArguments)18 Slf4j (lombok.extern.slf4j.Slf4j)8 ApplicationRunner (org.springframework.boot.ApplicationRunner)7 DefaultApplicationArguments (org.springframework.boot.DefaultApplicationArguments)7 List (java.util.List)5 Map (java.util.Map)5 IOException (java.io.IOException)4 Collectors (java.util.stream.Collectors)4 Lists (com.google.common.collect.Lists)3 BigDecimal (java.math.BigDecimal)3 Arrays (java.util.Arrays)3 Objects.requireNonNull (java.util.Objects.requireNonNull)3 TimeUnit (java.util.concurrent.TimeUnit)3 SneakyThrows (lombok.SneakyThrows)3 KrakenExchange (org.knowm.xchange.kraken.KrakenExchange)3 Autowired (org.springframework.beans.factory.annotation.Autowired)3 ApplicationContextHolder (cn.hippo4j.common.config.ApplicationContextHolder)2 StringUtil (cn.hippo4j.common.toolkit.StringUtil)2 ThreadFactoryBuilder (cn.hippo4j.core.executor.support.ThreadFactoryBuilder)2 DynamicThreadPoolServiceLoader (cn.hippo4j.core.spi.DynamicThreadPoolServiceLoader)2