org.knowm.xchange.currency.Currency Java Examples

The following examples show how to use org.knowm.xchange.currency.Currency. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BitmexUtils.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public static void setBitmexAssetPairs(List<BitmexTicker> tickers) {

    for (BitmexTicker ticker : tickers) {
      String quote = ticker.getQuoteCurrency();
      String base = ticker.getRootSymbol();
      Currency baseCurrencyCode = Currency.getInstance(base);
      Currency quoteCurrencyCode = Currency.getInstance(quote);

      CurrencyPair pair = new CurrencyPair(base, quote);
      if (!assetPairMap.containsKey(ticker.getSymbol()) && !assetPairMap.containsValue(pair))
        assetPairMap.put(ticker.getSymbol(), pair);
      if (!assetsMap.containsKey(quote) && !assetsMap.containsValue(quoteCurrencyCode))
        assetsMap.put(quote, quoteCurrencyCode);
      if (!assetsMap.containsKey(base) && !assetsMap.containsValue(baseCurrencyCode))
        assetsMap.put(base, baseCurrencyCode);
    }
  }
 
Example #2
Source File: XChangeMetadataIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCurrencyMetaData() throws Exception {

    try (CamelContext camelctx = new DefaultCamelContext()) {

        Assume.assumeTrue(checkAPIConnection());

        camelctx.addRoutes(createRouteBuilder());
        camelctx.start();

        ProducerTemplate template = camelctx.createProducerTemplate();
        CurrencyMetaData metadata = template.requestBody("direct:currencyMetaData", Currency.ETH, CurrencyMetaData.class);
        Assert.assertNotNull("CurrencyMetaData not null", metadata);

        metadata = template.requestBodyAndHeader("direct:currencyMetaData", null, HEADER_CURRENCY, Currency.ETH, CurrencyMetaData.class);
        Assert.assertNotNull("CurrencyMetaData not null", metadata);
    }
}
 
Example #3
Source File: XChangeMetadataIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCurrencies() throws Exception {

    try (CamelContext camelctx = new DefaultCamelContext()) {

        Assume.assumeTrue(checkAPIConnection());

        camelctx.addRoutes(createRouteBuilder());
        camelctx.start();

        ProducerTemplate template = camelctx.createProducerTemplate();
        List<Currency> currencies = template.requestBody("direct:currencies", null, List.class);
        Assert.assertNotNull("Currencies not null", currencies);
        Assert.assertTrue("Contains ETH", currencies.contains(Currency.ETH));
    }
}
 
Example #4
Source File: BitfinexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public static ExchangeMetaData adaptMetaData(
    List<CurrencyPair> currencyPairs, ExchangeMetaData metaData) {

  Map<CurrencyPair, CurrencyPairMetaData> pairsMap = metaData.getCurrencyPairs();
  Map<Currency, CurrencyMetaData> currenciesMap = metaData.getCurrencies();
  for (CurrencyPair c : currencyPairs) {
    if (!pairsMap.containsKey(c)) {
      pairsMap.put(c, null);
    }
    if (!currenciesMap.containsKey(c.base)) {
      currenciesMap.put(c.base, null);
    }
    if (!currenciesMap.containsKey(c.counter)) {
      currenciesMap.put(c.counter, null);
    }
  }

  return metaData;
}
 
Example #5
Source File: BitfinexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public static ExchangeMetaData adaptMetaData(
    BitfinexAccountFeesResponse accountFeesResponse, ExchangeMetaData metaData) {
  Map<Currency, CurrencyMetaData> currencies = metaData.getCurrencies();
  final Map<Currency, BigDecimal> withdrawFees = accountFeesResponse.getWithdraw();
  withdrawFees.forEach(
      (currency, withdrawalFee) -> {
        if (currencies.get(currency) == null) {
          CurrencyMetaData currencyMetaData = new CurrencyMetaData(0, withdrawalFee);
          currencies.put(currency, currencyMetaData);
        } else {
          final CurrencyMetaData oldMetaData = currencies.get(currency);
          CurrencyMetaData newMetaData =
              new CurrencyMetaData(oldMetaData.getScale(), withdrawalFee);
          currencies.put(currency, newMetaData);
        }
      });
  return metaData;
}
 
Example #6
Source File: CoinbaseAccountService.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
@Override
public AccountInfo getAccountInfo() throws IOException {
  List<Wallet> wallets = new ArrayList<>();

  List<CoinbaseAccountData.CoinbaseAccount> coinbaseAccounts = getCoinbaseAccounts();
  for (CoinbaseAccountData.CoinbaseAccount coinbaseAccount : coinbaseAccounts) {
    CoinbaseAmount balance = coinbaseAccount.getBalance();
    Wallet wallet =
        new Wallet(
            coinbaseAccount.getId(),
            new Balance(Currency.getInstance(balance.getCurrency()), balance.getAmount()));
    wallets.add(wallet);
  }

  return new AccountInfo(wallets);
}
 
Example #7
Source File: CoinbaseAdapters.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public static UserTrade adaptTrade(CoinbaseTransfer transfer) {

    final OrderType orderType = adaptOrderType(transfer.getType());
    final CoinbaseMoney btcAmount = transfer.getBtcAmount();
    final BigDecimal originalAmount = btcAmount.getAmount();
    final String tradableIdentifier = btcAmount.getCurrency();
    final CoinbaseMoney subTotal = transfer.getSubtotal();
    final String transactionCurrency = subTotal.getCurrency();
    final BigDecimal price = subTotal.getAmount().divide(originalAmount, RoundingMode.HALF_EVEN);
    final Date timestamp = transfer.getCreatedAt();
    final String id = transfer.getTransactionId();
    final String transferId = transfer.getId();
    final BigDecimal feeAmount = transfer.getCoinbaseFee().getAmount();
    final String feeCurrency = transfer.getCoinbaseFee().getCurrency();

    return new UserTrade(
        orderType,
        originalAmount,
        new CurrencyPair(tradableIdentifier, transactionCurrency),
        price,
        timestamp,
        id,
        transferId,
        feeAmount,
        Currency.getInstance(feeCurrency));
  }
 
Example #8
Source File: HuobiAdapters.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
static ExchangeMetaData adaptToExchangeMetaData(
    HuobiAssetPair[] assetPairs, HuobiAsset[] assets, ExchangeMetaData staticMetaData) {

  HuobiUtils.setHuobiAssets(assets);
  HuobiUtils.setHuobiAssetPairs(assetPairs);

  Map<CurrencyPair, CurrencyPairMetaData> pairsMetaData = staticMetaData.getCurrencyPairs();
  Map<CurrencyPair, CurrencyPairMetaData> pairs = new HashMap<>();
  for (HuobiAssetPair assetPair : assetPairs) {
    CurrencyPair pair = adaptCurrencyPair(assetPair.getKey());
    pairs.put(pair, adaptPair(assetPair, pairsMetaData.getOrDefault(pair, null)));
  }

  Map<Currency, CurrencyMetaData> currenciesMetaData = staticMetaData.getCurrencies();
  Map<Currency, CurrencyMetaData> currencies = new HashMap<>();
  for (HuobiAsset asset : assets) {
    Currency currency = adaptCurrency(asset.getAsset());
    CurrencyMetaData metadata = currenciesMetaData.getOrDefault(currency, null);
    BigDecimal withdrawalFee = metadata == null ? null : metadata.getWithdrawalFee();
    int scale = metadata == null ? 8 : metadata.getScale();
    currencies.put(currency, new CurrencyMetaData(scale, withdrawalFee));
  }

  return new ExchangeMetaData(pairs, currencies, null, null, false);
}
 
Example #9
Source File: CoinbaseAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static AccountInfo adaptAccountInfo(CoinbaseUser user) {

    final String username = user.getEmail();
    final CoinbaseMoney money = user.getBalance();
    final Balance balance =
        new Balance(Currency.getInstance(money.getCurrency()), money.getAmount());

    final AccountInfo accountInfoTemporaryName = new AccountInfo(username, new Wallet(balance));
    return accountInfoTemporaryName;
  }
 
Example #10
Source File: BitmexUtils.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static Currency translateBitmexCurrency(String currencyIn) {

    Currency currencyOut = bitmexCurrencies.inverse().get(currencyIn);

    if (currencyOut == null) {
      throw new ExchangeException("Bitmex does not support the currency code " + currencyIn);
    }
    return currencyOut;
  }
 
Example #11
Source File: BiboxAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static FundingRecord adaptDeposit(BiboxWithdrawal w) {
  return new FundingRecord(
      w.toAddress,
      w.getCreatedAt(),
      Currency.getInstance(w.coinSymbol),
      w.amountReal,
      null,
      null,
      Type.WITHDRAWAL,
      convertStatus(w.status),
      null,
      null,
      null);
}
 
Example #12
Source File: AlternateValueUtils.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private static String getSymbol(Currency currency) {
    if (currency.equals(Currency.BTC))
        return "Ƀ";
    else if (currency.equals(Currency.USD))
        return "$";
    else if (currency.equals(Currency.EUR))
        return "€";
    else if (currency.equals(Currency.CNY))
        return "¥";

    // should never happen:
    return "";
}
 
Example #13
Source File: BinanceBalance.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public BinanceBalance(
    @JsonProperty("asset") String asset,
    @JsonProperty("free") BigDecimal free,
    @JsonProperty("locked") BigDecimal locked) {
  this.currency = Currency.getInstance(asset);
  this.locked = locked;
  this.free = free;
}
 
Example #14
Source File: BiboxAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
private static Balance adaptBalance(BiboxCoin coin) {
  return new Balance.Builder()
      .currency(Currency.getInstance(coin.getSymbol()))
      .available(coin.getBalance())
      .frozen(coin.getFreeze())
      .total(coin.getBalance().add(coin.getFreeze()))
      .build();
}
 
Example #15
Source File: BinanceAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static CurrencyPair convert(String symbol) {
  // Iterate by base currency priority at binance.
  for (Currency base : Arrays.asList(Currency.BTC, Currency.ETH, Currency.BNB, Currency.USDT)) {
    if (symbol.contains(base.toString())) {
      String counter = symbol.replace(base.toString(), "");
      return new CurrencyPair(base, new Currency(counter));
    }
  }
  throw new IllegalArgumentException("Could not parse currency pair from '" + symbol + "'");
}
 
Example #16
Source File: BitmexUtils.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static Currency translateBitmexCurrencyCode(String currencyIn) {

    Currency currencyOut = assetsMap.get(currencyIn);
    if (currencyOut == null) {
      throw new ExchangeException("Bitmex does not support the currency code " + currencyIn);
    }
    return currencyOut.getCommonlyUsedCurrency();
  }
 
Example #17
Source File: BiboxAccountService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public List<FundingRecord> getFundingHistory(TradeHistoryParams params) {

  if (!(params instanceof TradeHistoryParamCurrency)) {
    throw new RuntimeException("You must provide the currency for funding history @ Bibox.");
  }
  Currency c = ((TradeHistoryParamCurrency) params).getCurrency();
  if (c == null) {
    throw new RuntimeException("You must provide the currency for funding history @ Bibox.");
  }

  boolean deposits = false;
  boolean withdrawals = false;
  if (params instanceof HistoryParamsFundingType) {
    HistoryParamsFundingType typeParams = (HistoryParamsFundingType) params;
    Type type = typeParams.getType();
    deposits = type == null || type == Type.DEPOSIT;
    withdrawals = type == null || type == Type.WITHDRAWAL;
  }
  BiboxFundsCommandBody body = new BiboxFundsCommandBody(c.getCurrencyCode());
  ArrayList<FundingRecord> result = new ArrayList<>();
  if (deposits) {
    requestBiboxDeposits(body).getItems().forEach(d -> result.add(BiboxAdapters.adaptDeposit(d)));
  }
  if (withdrawals) {
    requestBiboxWithdrawals(body)
        .getItems()
        .forEach(d -> result.add(BiboxAdapters.adaptDeposit(d)));
  }
  return result;
}
 
Example #18
Source File: BitfinexMarketDataServiceRaw.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public BitfinexPublicFundingTrade[] getBitfinexPublicFundingTrades(
    Currency currency, int limitTrades, long startTimestamp, long endTimestamp, int sort)
    throws IOException {
  try {
    return bitfinex.getPublicFundingTrades(
        "f" + currency.toString(), limitTrades, startTimestamp, endTimestamp, sort);
  } catch (HttpStatusIOException e) {
    throw handleException(new BitfinexException(e.getHttpBody()));
  }
}
 
Example #19
Source File: OkCoinAccountService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public OkCoinFundingHistoryParams(
    final Integer pageNumber,
    final Integer pageLength,
    final Currency currency,
    FundingRecord.Type type) {
  super(pageLength, pageNumber);
  this.currency = currency;
  this.type = type;
}
 
Example #20
Source File: CoinbasePrice.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public CoinbasePrice(BigDecimal amount, Currency currency) {
  Assert.notNull(currency, "Null currency");
  Assert.notNull(amount, "Null amount");
  this.currency = currency;
  this.amount = amount;

  toString = String.format("%.2f %s", amount, currency);
}
 
Example #21
Source File: ExchangeRateUpdater.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
public ExchangeRateUpdater(Currency baseCurrency, ExchangeRateStorage priceStorage) {
    this.storage = priceStorage;
    this.baseCurrencyBtcPair = new CurrencyPair(baseCurrency, Currency.BTC);

    exchanges = new HashMap<>();
    exchanges.put(baseCurrencyBtcPair, ExchangeFactory.INSTANCE.createExchange(BitfinexExchange.class.getName()));
    exchanges.put(CurrencyPair.BTC_USD, ExchangeFactory.INSTANCE.createExchange(BitfinexExchange.class.getName()));
    exchanges.put(CurrencyPair.BTC_EUR, ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName()));
    exchanges.put(CurrencyPair.BTC_CNY, ExchangeFactory.INSTANCE.createExchange(OkCoinExchange.class.getName()));

    // add more currencies/exchange pairs (btc/fiat) here
}
 
Example #22
Source File: BitmexAccountService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public String requestDepositAddress(Currency currency, String... args) throws IOException {
  String currencyCode = currency.getCurrencyCode();

  // bitmex seems to use a lowercase 't' in XBT
  // can test this here - https://testnet.bitmex.com/api/explorer/#!/User/User_getDepositAddress
  // uppercase 'T' will return 'Unknown currency code'
  if (currencyCode.equals("XBT")) {
    currencyCode = "XBt";
  }
  return requestDepositAddress(currencyCode);
}
 
Example #23
Source File: Balance.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Returns a zero balance.
 *
 * @param currency the balance currency.
 * @return a zero balance.
 */
public static Balance zero(Currency currency) {

  return new Balance(
      currency,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO);
}
 
Example #24
Source File: AlternateValueManager.java    From android-wallet-app with GNU General Public License v3.0 5 votes vote down vote up
public float convert(long iotaAmount, Currency currency) throws ExchangeRateNotAvailableException {
    Currency baseCurrency = Utils.getBaseCurrency();
    AlternateValueCalculator calculator = new AlternateValueCalculator(baseCurrency,
            new ExchangeRateStorage(PreferenceManager.getDefaultSharedPreferences(context)));

    // convert the iota to mega iota assuming that iota will be traded in mega iotas

    double walletBalanceGigaIota = jota.utils.IotaUnitConverter.convertUnits(iotaAmount, IotaUnits.IOTA, IotaUnits.MEGA_IOTA);
    return calculator.calculateValue((float) walletBalanceGigaIota, currency);
}
 
Example #25
Source File: BitmexAccountServiceRaw.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public List<BitmexWalletTransaction> getBitmexWalletSummary(Currency ccy)
    throws ExchangeException {

  try {
    return updateRateLimit(
        bitmex.getWalletSummary(
            apiKey, exchange.getNonceFactory(), signatureCreator, ccy.getCurrencyCode()));
  } catch (IOException e) {
    throw handleError(e);
  }
}
 
Example #26
Source File: Balance.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Constructs a balance. The <code>borrowed</code> and <code>loaned</code> will be zero.
 *
 * @param currency the underlying currency of this balance.
 * @param total the total amount of the <code>currency</code> in this balance, including the
 *     <code>available</code> and <code>frozen</code>.
 * @param available the amount of the <code>currency</code> in this balance that is available to
 *     trade.
 * @param frozen the frozen amount of the <code>currency</code> in this balance that is locked in
 *     trading.
 */
public Balance(Currency currency, BigDecimal total, BigDecimal available, BigDecimal frozen) {

  this(
      currency,
      total,
      available,
      frozen,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO);
}
 
Example #27
Source File: OkCoinAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static UserTrades adaptTradeHistory(
    OkCoinFuturesTradeHistoryResult[] okCoinFuturesTradeHistoryResult) {

  List<UserTrade> trades = new ArrayList<>();
  long lastTradeId = 0;
  for (OkCoinFuturesTradeHistoryResult okCoinFuturesTrade : okCoinFuturesTradeHistoryResult) {
    //  if (okCoinFuturesTrade.getType().equals(OkCoinFuturesTradeHistoryResult.TransactionType.))
    // { // skip account deposits and withdrawals.
    OrderType orderType =
        okCoinFuturesTrade.getType().equals(TransactionType.sell) ? OrderType.ASK : OrderType.BID;
    BigDecimal originalAmount = BigDecimal.valueOf(okCoinFuturesTrade.getAmount());
    BigDecimal price = okCoinFuturesTrade.getPrice();
    Date timestamp = new Date(okCoinFuturesTrade.getTimestamp());
    long transactionId = okCoinFuturesTrade.getId();
    if (transactionId > lastTradeId) {
      lastTradeId = transactionId;
    }
    final String tradeId = String.valueOf(transactionId);
    final String orderId = String.valueOf(okCoinFuturesTrade.getId());
    final CurrencyPair currencyPair = CurrencyPair.BTC_USD;

    BigDecimal feeAmont = BigDecimal.ZERO;
    UserTrade trade =
        new UserTrade(
            orderType,
            originalAmount,
            currencyPair,
            price,
            timestamp,
            tradeId,
            orderId,
            feeAmont,
            Currency.getInstance(currencyPair.counter.getCurrencyCode()));
    trades.add(trade);
  }

  return new UserTrades(trades, lastTradeId, TradeSortType.SortByID);
}
 
Example #28
Source File: Balance.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Constructs a balance, the {@link #available} will be the same as the <code>total</code>, and
 * the {@link #frozen} is zero. The <code>borrowed</code> and <code>loaned</code> will be zero.
 *
 * @param currency The underlying currency
 * @param total The total
 */
public Balance(Currency currency, BigDecimal total) {

  this(
      currency,
      total,
      total,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO,
      BigDecimal.ZERO);
}
 
Example #29
Source File: BitmexAccountServiceRaw.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public List<BitmexWalletTransaction> getBitmexWalletHistory(Currency ccy)
    throws ExchangeException {

  try {
    return updateRateLimit(
        bitmex.getWalletHistory(
            apiKey, exchange.getNonceFactory(), signatureCreator, ccy.getCurrencyCode()));
  } catch (IOException e) {
    throw handleError(e);
  }
}
 
Example #30
Source File: HuobiAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static FundingRecord adaptFundingRecord(HuobiFundingRecord r) {

    return new FundingRecord(
        r.getAddress(),
        r.getCreatedAt(),
        Currency.getInstance(r.getCurrency()),
        r.getAmount(),
        Long.toString(r.getId()),
        r.getTxhash(),
        r.getType(),
        adaptFundingStatus(r),
        null,
        r.getFee(),
        null);
  }