org.knowm.xchange.currency.CurrencyPair Java Examples

The following examples show how to use org.knowm.xchange.currency.CurrencyPair. 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: TickerServiceTest.java    From arbitrader with MIT License 6 votes vote down vote up
@Test
public void testInitializeTickers() throws IOException {
    Exchange exchangeA = new ExchangeBuilder("ExchangeA", CURRENCY_PAIR)
        .withTickers(true, Collections.singletonList(CURRENCY_PAIR))
        .withTickerStrategy(singleCallTickerStrategy)
        .withExchangeMetaData()
        .withMarginSupported(true)
        .build();
    Exchange exchangeB = new ExchangeBuilder("ExchangeB", CURRENCY_PAIR)
        .withTickers(true, Arrays.asList(CURRENCY_PAIR, CurrencyPair.ETH_USD))
        .withTickerStrategy(singleCallTickerStrategy)
        .withExchangeMetaData()
        .withMarginSupported(false)
        .build();
    List<Exchange> exchanges = Arrays.asList(exchangeA, exchangeB);

    tickerService.initializeTickers(exchanges);

    assertEquals(1, tickerService.tradeCombinations.size());
    assertTrue(tickerService.tradeCombinations.contains(new TradeCombination(exchangeB, exchangeA, CURRENCY_PAIR)));
}
 
Example #2
Source File: BitmexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public static Trade adaptTrade(BitmexPublicTrade bitmexPublicTrade, CurrencyPair currencyPair) {

    OrderType type = adaptOrderType(bitmexPublicTrade.getSide());
    BigDecimal originalAmount = bitmexPublicTrade.getSize();
    Date timestamp = bitmexPublicTrade.getTime();
    // Date timestamp = adaptTimestamp(bitmexPublicTrade.getTime());
    // new Date((long) (bitmexPublicTrade.getTime()));

    return new Trade(
        type,
        originalAmount,
        currencyPair,
        bitmexPublicTrade.getPrice(),
        timestamp,
        String.valueOf(timestamp.getTime()));
  }
 
Example #3
Source File: BitmexMarketDataService.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {

  BitmexPrompt prompt = null;
  if (args != null && args.length > 0) {
    Object arg0 = args[0];
    if (arg0 instanceof BitmexPrompt) {
      prompt = (BitmexPrompt) arg0;
    } else {
      throw new ExchangeException("args[0] must be of type BitmexPrompt!");
    }
  }
  Object[] argsToPass = Arrays.copyOfRange(args, 1, args.length);
  return BitmexAdapters.adaptOrderBook(
      getBitmexDepth(BitmexAdapters.adaptCurrencyPair(currencyPair), prompt, argsToPass),
      currencyPair);
}
 
Example #4
Source File: XChangeMetadataIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCurrencyPairMetaData() throws Exception {

    try (CamelContext camelctx = new DefaultCamelContext()) {

        Assume.assumeTrue(checkAPIConnection());

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

        ProducerTemplate template = camelctx.createProducerTemplate();
        CurrencyPairMetaData metadata = template.requestBody("direct:currencyPairMetaData", CurrencyPair.EOS_ETH, CurrencyPairMetaData.class);
        Assert.assertNotNull("CurrencyPairMetaData not null", metadata);

        metadata = template.requestBodyAndHeader("direct:currencyPairMetaData", null, HEADER_CURRENCY_PAIR, CurrencyPair.EOS_ETH, CurrencyPairMetaData.class);
        Assert.assertNotNull("CurrencyPairMetaData not null", metadata);
    }
}
 
Example #5
Source File: StopOrder.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * @param type Either BID (buying) or ASK (selling)
 * @param originalAmount The amount to trade
 * @param currencyPair The identifier (e.g. BTC/USD)
 * @param id An id (usually provided by the exchange)
 * @param timestamp a Date object representing the order's timestamp according to the exchange's
 *     server, null if not provided
 * @param stopPrice In a BID this is the highest acceptable price, in an ASK this is the lowest
 *     acceptable price
 * @param limitPrice The limit price the order should be placed at once the stopPrice has been hit
 *     null for market
 * @param averagePrice the weighted average price of any fills belonging to the order
 * @param cumulativeAmount the amount that has been filled
 * @param status the status of the order at the exchange or broker
 */
public StopOrder(
    OrderType type,
    BigDecimal originalAmount,
    CurrencyPair currencyPair,
    String id,
    Date timestamp,
    BigDecimal stopPrice,
    BigDecimal limitPrice,
    BigDecimal averagePrice,
    BigDecimal cumulativeAmount,
    OrderStatus status) {

  super(
      type,
      originalAmount,
      currencyPair,
      id,
      timestamp,
      averagePrice,
      cumulativeAmount,
      BigDecimal.ZERO,
      status);
  this.stopPrice = stopPrice;
  this.limitPrice = limitPrice;
}
 
Example #6
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 #7
Source File: CoinbaseMarketDataService.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * @param args Optional Boolean. If true an additional call to retrieve the spot price history
 *     will be made and used to populate the 24 hour high and low values for the Ticker.
 * @return A Ticker with Coinbase's current buy price as the best ask, sell price as the best bid,
 *     spot price as the last value, and can optionally use the spot price history to find the 24
 *     hour high and low.
 */
@Override
public Ticker getTicker(CurrencyPair currencyPair, final Object... args) throws IOException {

  final String currency = currencyPair.counter.getCurrencyCode();
  final CoinbasePrice buyPrice = super.getCoinbaseBuyPrice(BigDecimal.ONE, currency);
  final CoinbasePrice sellPrice = super.getCoinbaseSellPrice(BigDecimal.ONE, currency);
  final CoinbaseMoney spotRate = super.getCoinbaseSpotRate(currency);

  final CoinbaseSpotPriceHistory coinbaseSpotPriceHistory =
      (args != null
              && args.length > 0
              && args[0] != null
              && args[0] instanceof Boolean
              && (Boolean) args[0])
          ? super.getCoinbaseHistoricalSpotRates()
          : null;

  return CoinbaseAdapters.adaptTicker(
      currencyPair, buyPrice, sellPrice, spotRate, coinbaseSpotPriceHistory);
}
 
Example #8
Source File: AlternateValueCalculator.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public float calculateValue(float baseAmount, Currency targetCurrency) throws ExchangeRateNotAvailableException {
    // convert the amount to btc first
    float btcAmount = calcBtcAmount(baseAmount);
    float targetValue;

    // if the target currency is btc we do nothing, otherwise we use the rate
    if (targetCurrency.equals(Currency.BTC)) {
        targetValue = btcAmount;
    } else {

        float fiatBtcPrice = exchangeRateProvider.getExchangeRate(new CurrencyPair(Currency.BTC, targetCurrency));
        targetValue = btcAmount * fiatBtcPrice;
    }

    return targetValue;
}
 
Example #9
Source File: ExchangeServiceTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testConvertExchangePairBase() {
    CurrencyPair currencyPair = CurrencyPair.BTC_USD;
    CurrencyPair converted = exchangeService.convertExchangePair(exchange, currencyPair);

    assertEquals(CurrencyPair.BTC_USDT, converted);
}
 
Example #10
Source File: BitmexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static BitmexDepth adaptDepth(BitmexPublicOrderList orders, CurrencyPair currencyPair) {

    BitmexDepth bitmexDepth = new BitmexDepth(new ArrayList<>(), new ArrayList<>());

    for (BitmexPublicOrder bitmexOrder : orders) {
      if (bitmexOrder.getSide().equals(BitmexSide.BUY)) bitmexDepth.getBids().add(bitmexOrder);
      else if (bitmexOrder.getSide().equals(BitmexSide.SELL))
        bitmexDepth.getAsks().add(bitmexOrder);
    }

    return bitmexDepth;
  }
 
Example #11
Source File: OkCoinAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static Ticker adaptTicker(OkCoinTickerResponse tickerResponse, CurrencyPair currencyPair) {
  final Date date = adaptDate(tickerResponse.getDate());
  return new Ticker.Builder()
      .currencyPair(currencyPair)
      .high(tickerResponse.getTicker().getHigh())
      .low(tickerResponse.getTicker().getLow())
      .bid(tickerResponse.getTicker().getBuy())
      .ask(tickerResponse.getTicker().getSell())
      .last(tickerResponse.getTicker().getLast())
      .volume(tickerResponse.getTicker().getVol())
      .timestamp(date)
      .build();
}
 
Example #12
Source File: OkCoinFuturesTradeService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public OkCoinFuturesOrderQueryParams(
    CurrencyPair currencyPair, FuturesContract futuresContract, String orderId) {
  super(orderId);
  this.currencyPair = currencyPair;
  this.futuresContract = futuresContract;
  this.orderId = orderId;
}
 
Example #13
Source File: SingleCallTickerStrategyTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetTickersExchangeException() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(tickerStrategy)
        .withTickers(new ExchangeException("Boom!"))
        .build();

    List<Ticker> tickers = tickerStrategy.getTickers(exchange, currencyPairs);

    assertTrue(tickers.isEmpty());
    assertFalse(errorCollectorService.isEmpty());
}
 
Example #14
Source File: SpreadServiceTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    MockitoAnnotations.initMocks(this);

    longExchange = new ExchangeBuilder("Long", CurrencyPair.BTC_USD)
        .withExchangeMetaData()
        .build();
    shortExchange = new ExchangeBuilder("Short", CurrencyPair.BTC_USD)
        .withExchangeMetaData()
        .build();

    spreadService = new SpreadService();
}
 
Example #15
Source File: OkCoinTradeService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * OKEX does not support trade history in the usual way, it only provides a aggregated view on a
 * per order basis of how much the order has been filled and the average price. Individual trade
 * details are not available. As a consequence of this, the trades supplied by this method will
 * use the order ID as their trade ID, and will be subject to being amended if a partially filled
 * order if further filled. Supported parameters are {@link TradeHistoryParamCurrencyPair} and
 * {@link TradeHistoryParamPaging}, if not supplied then the query will default to BTC/USD or
 * BTC/CNY (depending on session configuration) and the last 200 trades.
 */
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
  Integer pageLength = null, pageNumber = null;
  if (params instanceof TradeHistoryParamPaging) {
    TradeHistoryParamPaging paging = (TradeHistoryParamPaging) params;
    pageLength = paging.getPageLength();
    pageNumber = paging.getPageNumber();
  }
  if (pageNumber == null) {
    pageNumber = 1; // pages start from 1
  }
  if (pageLength == null) {
    pageLength = 200; // 200 is the maximum number
  }

  CurrencyPair pair = null;
  if (params instanceof TradeHistoryParamCurrencyPair) {
    pair = ((TradeHistoryParamCurrencyPair) params).getCurrencyPair();
  }
  if (pair == null) {
    pair = useIntl ? CurrencyPair.BTC_USD : CurrencyPair.BTC_CNY;
  }

  OkCoinOrderResult orderHistory =
      getOrderHistory(
          OkCoinAdapters.adaptSymbol(pair),
          ORDER_STATUS_FILLED,
          pageNumber.toString(),
          pageLength.toString());
  return OkCoinAdapters.adaptTrades(orderHistory);
}
 
Example #16
Source File: BitfinexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static OrderBook adaptOrderBook(BitfinexDepth btceDepth, CurrencyPair currencyPair) {

    OrdersContainer asksOrdersContainer =
        adaptOrders(btceDepth.getAsks(), currencyPair, OrderType.ASK);
    OrdersContainer bidsOrdersContainer =
        adaptOrders(btceDepth.getBids(), currencyPair, OrderType.BID);

    return new OrderBook(
        new Date(Math.max(asksOrdersContainer.getTimestamp(), bidsOrdersContainer.getTimestamp())),
        asksOrdersContainer.getLimitOrders(),
        bidsOrdersContainer.getLimitOrders());
  }
 
Example #17
Source File: SingleCallTickerStrategyTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetTickersUndeclaredThrowableException() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(tickerStrategy)
        .withTickers(new UndeclaredThrowableException(new IOException("Boom!")))
        .build();

    List<Ticker> tickers = tickerStrategy.getTickers(exchange, currencyPairs);

    assertTrue(tickers.isEmpty());
    assertFalse(errorCollectorService.isEmpty());
}
 
Example #18
Source File: OrderBook.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
private static LimitOrder withAmount(LimitOrder limitOrder, BigDecimal tradeableAmount) {

    OrderType type = limitOrder.getType();
    CurrencyPair currencyPair = limitOrder.getCurrencyPair();
    String id = limitOrder.getId();
    Date date = limitOrder.getTimestamp();
    BigDecimal limit = limitOrder.getLimitPrice();
    return new LimitOrder(type, tradeableAmount, currencyPair, id, date, limit);
  }
 
Example #19
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 #20
Source File: BitfinexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static List<CurrencyPair> adaptCurrencyPairs(Collection<String> bitfinexSymbol) {

    List<CurrencyPair> currencyPairs = new ArrayList<>();
    for (String symbol : bitfinexSymbol) {
      currencyPairs.add(adaptCurrencyPair(symbol));
    }
    return currencyPairs;
  }
 
Example #21
Source File: BitmexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static Ticker adaptTicker(BitmexTicker bitmexTicker, CurrencyPair currencyPair) {

    Ticker.Builder builder = new Ticker.Builder();
    builder.open(bitmexTicker.getPrevClosePrice());
    builder.ask(bitmexTicker.getAskPrice());
    builder.bid(bitmexTicker.getBidPrice());
    builder.last(bitmexTicker.getLastPrice());
    builder.high(bitmexTicker.getHighPrice());
    builder.low(bitmexTicker.getLowPrice());
    builder.vwap(new BigDecimal(bitmexTicker.getVwap().longValue()));
    builder.volume(bitmexTicker.getVolume24h());
    builder.currencyPair(currencyPair);
    return builder.build();
  }
 
Example #22
Source File: SingleCallTickerStrategyTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetTickersIOException() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(tickerStrategy)
        .withTickers(new IOException("Boom!"))
        .build();

    List<Ticker> tickers = tickerStrategy.getTickers(exchange, currencyPairs);

    assertTrue(tickers.isEmpty());
    assertFalse(errorCollectorService.isEmpty());
}
 
Example #23
Source File: TickerServiceTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetTickersException() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(singleCallTickerStrategy)
        .withTickers(new ExchangeException("Boom!"))
        .build();

    List<Ticker> tickers = tickerService.getTickers(exchange, currencyPairs);

    assertTrue(tickers.isEmpty());
    assertFalse(errorCollectorService.isEmpty());

    verify(exchange.getMarketDataService()).getTickers(any());
    verify(exchange.getMarketDataService(), never()).getTicker(any());
}
 
Example #24
Source File: LimitOrder.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * @param type Either BID (buying) or ASK (selling)
 * @param originalAmount The amount to trade
 * @param currencyPair The identifier (e.g. BTC/USD)
 * @param id An id (usually provided by the exchange)
 * @param timestamp a Date object representing the order's timestamp according to the exchange's
 *     server, null if not provided
 * @param limitPrice In a BID this is the highest acceptable price, in an ASK this is the lowest
 *     acceptable price
 */
public LimitOrder(
    OrderType type,
    BigDecimal originalAmount,
    CurrencyPair currencyPair,
    String id,
    Date timestamp,
    BigDecimal limitPrice) {

  super(type, originalAmount, currencyPair, id, timestamp);
  this.limitPrice = limitPrice;
}
 
Example #25
Source File: BitZUtils.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static CurrencyPair toCurrencyPair(String pairstring) {
  String[] parts = pairstring.split("_");

  if (parts.length == 2) {
    Currency base = Currency.getInstanceNoCreate(parts[0]);
    Currency counter = Currency.getInstanceNoCreate(parts[1]);

    if (base != null && counter != null) {
      return new CurrencyPair(base, counter);
    }
  }

  return null;
}
 
Example #26
Source File: BiboxMarketDataServiceRaw.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public List<BiboxDeals> getBiboxDeals(CurrencyPair currencyPair, Integer depth)
    throws IOException {
  try {
    BiboxResponse<List<BiboxDeals>> response =
        bibox.deals(DEALS_CMD, BiboxAdapters.toBiboxPair(currencyPair), depth);
    throwErrors(response);
    return response.getResult();
  } catch (BiboxException e) {
    throw new ExchangeException(e.getMessage(), e);
  }
}
 
Example #27
Source File: Poloniex.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private Stream<PoloniexTicker> getTickers() {

        return getTickersKeyedByCurrencyPair().entrySet().stream()
            .map(e -> {
                String pair = e.getKey();
                PoloniexMarketData data = e.getValue();
                String[] symbols = pair.split("_"); // e.g. BTC_USD => [BTC, USD]
                return new PoloniexTicker(data, new CurrencyPair(symbols[0], symbols[1]));
            });
    }
 
Example #28
Source File: BitfinexAdapters.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static Trade adaptPublicTrade(BitfinexPublicTrade trade, CurrencyPair currencyPair) {

    OrderType orderType = trade.getType();
    BigDecimal amount = trade.getAmount();
    BigDecimal price = trade.getPrice();
    Date date = DateUtils.fromMillisUtc(trade.getTimestamp());
    final String tradeId = String.valueOf(trade.getTradeId());
    return new Trade(orderType, amount, currencyPair, price, date, tradeId);
  }
 
Example #29
Source File: OkCoinFuturesMarketDataService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
  if (args != null && args.length > 0) {
    return OkCoinAdapters.adaptOrderBook(
        getFuturesDepth(currencyPair, (FuturesContract) args[0]), currencyPair);
  } else {
    return OkCoinAdapters.adaptOrderBook(
        getFuturesDepth(currencyPair, futuresContract), currencyPair);
  }
}
 
Example #30
Source File: ExchangeRateStorage.java    From android-wallet-app with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized float getExchangeRate(CurrencyPair currencyPair) throws ExchangeRateNotAvailableException {
    float NOT_AVAILABLE = -1;
    float exchangeRate = sharedPreferences.getFloat(getKey(currencyPair), NOT_AVAILABLE);

    if (exchangeRate == NOT_AVAILABLE)
        throw new ExchangeRateNotAvailableException(currencyPair);

    return exchangeRate;
}