org.knowm.xchange.Exchange Java Examples

The following examples show how to use org.knowm.xchange.Exchange. 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: SingleCallTickerStrategyTest.java    From arbitrader with MIT License 6 votes vote down vote up
@Test
public void testGetTickers() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(tickerStrategy)
        .withTickers(
            true,
            Collections.singletonList(CurrencyPair.BTC_USD))
        .build();

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

    assertEquals(1, tickers.size());
    assertTrue(errorCollectorService.isEmpty());

    Ticker ticker = tickers.get(0);

    assertEquals(CurrencyPair.BTC_USD, ticker.getCurrencyPair());
}
 
Example #2
Source File: TickerService.java    From arbitrader with MIT License 6 votes vote down vote up
List<Ticker> getTickers(Exchange exchange, List<CurrencyPair> currencyPairs) {
    TickerStrategy tickerStrategy = (TickerStrategy)exchange.getExchangeSpecification().getExchangeSpecificParametersItem(TICKER_STRATEGY_KEY);

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

        tickers.forEach(ticker -> LOGGER.debug("Ticker: {} {} {}/{}",
            exchange.getExchangeSpecification().getExchangeName(),
            ticker.getCurrencyPair(),
            ticker.getBid(),
            ticker.getAsk()));

        return tickers;
    } catch (RuntimeException re) {
        LOGGER.debug("Unexpected runtime exception: " + re.getMessage(), re);
        errorCollectorService.collect(exchange, re);
    }

    return Collections.emptyList();
}
 
Example #3
Source File: BitfinexBaseService.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * Constructor
 *
 * @param exchange
 */
public BitfinexBaseService(Exchange exchange) {

  super(exchange);

  this.bitfinex =
      RestProxyFactory.createProxy(
          BitfinexAuthenticated.class,
          exchange.getExchangeSpecification().getSslUri(),
          getClientConfig());
  this.apiKey = exchange.getExchangeSpecification().getApiKey();
  this.signatureCreator =
      BitfinexHmacPostBodyDigest.createInstance(
          exchange.getExchangeSpecification().getSecretKey());
  this.payloadCreator = new BitfinexPayloadDigest();
}
 
Example #4
Source File: TickerService.java    From arbitrader with MIT License 6 votes vote down vote up
private boolean isInvalidExchangePair(Exchange longExchange, Exchange shortExchange, CurrencyPair currencyPair) {
    // both exchanges are the same
    if (longExchange == shortExchange) {
        return true;
    }

    // the "short" exchange doesn't support margin
    if (!exchangeService.getExchangeMetadata(shortExchange).getMargin()) {
        return true;
    }

    // the "short" exchange doesn't support margin on this currency pair
    if (exchangeService.getExchangeMetadata(shortExchange).getMarginExclude().contains(currencyPair)) {
        return true;
    }

    // this specific combination of exchanges/currency has been blocked in the configuration
    //noinspection RedundantIfStatement
    if (tradingConfiguration.getTradeBlacklist().contains(formatTradeCombination(longExchange, shortExchange, currencyPair))) {
        return true;
    }

    return false;
}
 
Example #5
Source File: BitZTradeServiceRaw.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public BitZTradeServiceRaw(Exchange exchange) {
  super(exchange);

  this.bitz =
      RestProxyFactory.createProxy(BitZ.class, exchange.getExchangeSpecification().getSslUri());
  this.bitzAuthenticated =
      RestProxyFactory.createProxy(
          BitZAuthenticated.class, exchange.getExchangeSpecification().getSslUri());

  // TODO: Implement Password
  this.tradePwd = "";

  this.apiKey = exchange.getExchangeSpecification().getApiKey();
  this.secretKey = exchange.getExchangeSpecification().getSecretKey();

  this.signer = BitZDigest.createInstance();
  this.nonceFactory = exchange.getNonceFactory();
}
 
Example #6
Source File: ConditionService.java    From arbitrader with MIT License 6 votes vote down vote up
public boolean isBlackoutCondition(Exchange exchange) {
    if (!blackoutFile.exists() || !blackoutFile.canRead()) {
        return false;
    }

    try {
        List<String> lines = FileUtils.readLines(blackoutFile, Charset.defaultCharset());

        return lines
            .stream()
            .filter(line -> line.startsWith(exchange.getExchangeSpecification().getExchangeName()))
            .anyMatch(this::checkBlackoutWindow);

    } catch (IOException e) {
        LOGGER.error("Blackout file exists but cannot be read!", e);
    }

    return false;
}
 
Example #7
Source File: TickerServiceTest.java    From arbitrader with MIT License 6 votes vote down vote up
@Test
public void testGetTickers() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(singleCallTickerStrategy)
        .withTickers(
            true,
            Collections.singletonList(CurrencyPair.BTC_USD))
        .build();

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

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

    verify(exchange.getMarketDataService()).getTickers(any());
    verify(exchange.getMarketDataService(), never()).getTicker(any());
}
 
Example #8
Source File: TradingService.java    From arbitrader with MIT License 6 votes vote down vote up
BigDecimal getLimitPrice(Exchange exchange, CurrencyPair rawCurrencyPair, BigDecimal allowedVolume, Order.OrderType orderType) {
    CurrencyPair currencyPair = exchangeService.convertExchangePair(exchange, rawCurrencyPair);

    try {
        OrderBook orderBook = exchange.getMarketDataService().getOrderBook(currencyPair);
        List<LimitOrder> orders = orderType.equals(Order.OrderType.ASK) ? orderBook.getAsks() : orderBook.getBids();
        BigDecimal price;
        BigDecimal volume = BigDecimal.ZERO;

        for (LimitOrder order : orders) {
            price = order.getLimitPrice();
            volume = volume.add(order.getRemainingAmount());

            if (volume.compareTo(allowedVolume) > 0) {
                return price;
            }
        }
    } catch (IOException e) {
        LOGGER.error("IOE fetching {} {} order volume", exchange.getExchangeSpecification().getExchangeName(), currencyPair, e);
    }

    throw new RuntimeException("Not enough liquidity on exchange to fulfill required volume!");
}
 
Example #9
Source File: ParallelTickerStrategyTest.java    From arbitrader with MIT License 6 votes vote down vote up
@Test
public void testGetTickers() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(tickerStrategy)
        .withTickers(
            true,
            Collections.singletonList(CurrencyPair.BTC_USD))
        .build();

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

    assertEquals(1, tickers.size());
    assertTrue(errorCollectorService.isEmpty());

    Ticker ticker = tickers.get(0);

    assertEquals(CurrencyPair.BTC_USD, ticker.getCurrencyPair());
}
 
Example #10
Source File: Spread.java    From arbitrader with MIT License 6 votes vote down vote up
public Spread(
    CurrencyPair currencyPair,
    Exchange longExchange,
    Exchange shortExchange,
    Ticker longTicker,
    Ticker shortTicker,
    BigDecimal in,
    BigDecimal out) {

    this.currencyPair = currencyPair;
    this.longExchange = longExchange;
    this.shortExchange = shortExchange;
    this.longTicker = longTicker;
    this.shortTicker = shortTicker;
    this.in = in;
    this.out = out;
}
 
Example #11
Source File: TickerServiceTest.java    From arbitrader with MIT License 6 votes vote down vote up
@Test
public void testGetParallelTickers() throws IOException {
    Exchange exchange = new ExchangeBuilder("CrazyCoinz", CurrencyPair.BTC_USD)
        .withTickerStrategy(parallelTickerStrategy)
        .withTickers(
            false,
            Collections.singletonList(CurrencyPair.BTC_USD))
        .build();

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

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

    verify(exchange.getMarketDataService(), never()).getTickers(any());
    verify(exchange.getMarketDataService(), atLeastOnce()).getTicker(any());
}
 
Example #12
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 #13
Source File: FCoinBaseService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Constructor
 *
 * @param exchange
 */
public FCoinBaseService(Exchange exchange) {

  super(exchange);
  apiKey = exchange.getExchangeSpecification().getApiKey();
  fcoin =
      RestProxyFactory.createProxy(
          FCoin.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig());
  signatureCreator =
      FCoinDigest.createInstance(exchange.getExchangeSpecification().getSecretKey(), apiKey);
}
 
Example #14
Source File: ParallelTickerStrategyTest.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 #15
Source File: ParallelTickerStrategyTest.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 #16
Source File: StreamingTickerStrategyTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testInvalidExchange() throws Exception {
    Exchange nonStreamingExchange = new ExchangeBuilder("CrazyCoinz",CurrencyPair.BTC_USD).build();

    List<Ticker> result = streamingTickerStrategy.getTickers(nonStreamingExchange, List.of(CurrencyPair.BTC_USD));

    assertTrue(result.isEmpty());
}
 
Example #17
Source File: OkCoinBaseService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Constructor
 *
 * @param exchange
 */
public OkCoinBaseService(Exchange exchange) {

  super(exchange);

  useIntl =
      (Boolean)
          exchange.getExchangeSpecification().getExchangeSpecificParameters().get("Use_Intl");
}
 
Example #18
Source File: StreamingTickerStrategy.java    From arbitrader with MIT License 5 votes vote down vote up
@Override
public List<Ticker> getTickers(Exchange stdExchange, List<CurrencyPair> currencyPairs) {
    if (!(stdExchange instanceof StreamingExchange)) {
        LOGGER.warn("{} is not a streaming exchange", stdExchange.getExchangeSpecification().getExchangeName());
        return Collections.emptyList();
    }

    StreamingExchange exchange = (StreamingExchange)stdExchange;

    if (!tickers.containsKey(exchange)) {
        ProductSubscription.ProductSubscriptionBuilder builder = ProductSubscription.create();

        currencyPairs.forEach(builder::addTicker);

        exchange.connect(builder.build()).blockingAwait();
        subscriptions.addAll(subscribeAll(exchange, currencyPairs));
    }

    if (tickers.containsKey(exchange)) {
        return tickers.get(exchange).entrySet()
            .stream()
            .filter(entry -> currencyPairs.contains(entry.getKey()))
            .map(Map.Entry::getValue)
            .collect(Collectors.toList());
    }

    return Collections.emptyList();
}
 
Example #19
Source File: TickerService.java    From arbitrader with MIT License 5 votes vote down vote up
public void refreshTickers() {
    allTickers.clear();

    Map<Exchange, Set<CurrencyPair>> queue = new HashMap<>();

    // find the currencies that are actively in use for each exchange
    tradeCombinations.forEach(tradeCombination -> {
        Set<CurrencyPair> longCurrencies = queue.computeIfAbsent(tradeCombination.getLongExchange(), (key) -> new HashSet<>());
        Set<CurrencyPair> shortCurrencies = queue.computeIfAbsent(tradeCombination.getShortExchange(), (key) -> new HashSet<>());

        longCurrencies.add(tradeCombination.getCurrencyPair());
        shortCurrencies.add(tradeCombination.getCurrencyPair());
    });

    // for each exchange, fetch its active currencies
    queue.keySet().forEach(exchange -> {
        List<CurrencyPair> activePairs = new ArrayList<>(queue.get(exchange));

        try {
            LOGGER.debug("{} fetching tickers for: {}", exchange.getExchangeSpecification().getExchangeName(), activePairs);

            getTickers(exchange, activePairs)
                .forEach(ticker -> allTickers.put(tickerKey(exchange, ticker.getCurrencyPair()), ticker));
        } catch (ExchangeException e) {
            LOGGER.warn("Failed to fetch ticker for {}", exchange.getExchangeSpecification().getExchangeName());
        }
    });
}
 
Example #20
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 #21
Source File: BaseXChangeExchangeRateProvider.java    From consensusj with Apache License 2.0 5 votes vote down vote up
/**
 * Construct using an XChange Exchange class object for a set of currencies
 * @param exchangeClass Class of XChange exchange we are wrapping
 * @param pairs pairs to monitor
 */
public BaseXChangeExchangeRateProvider(Class<? extends Exchange> exchangeClass,
                                          CurrencyUnitPair... pairs) {
    this(exchangeClass.getName(),
            null,
            null,
            Arrays.asList(pairs));
}
 
Example #22
Source File: TickerServiceTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testRefreshTickers() 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();

    tickerService.tradeCombinations.add(new TradeCombination(exchangeB, exchangeA, CURRENCY_PAIR));

    tickerService.refreshTickers();

    assertEquals(3, tickerService.allTickers.size());
    assertNotNull(tickerService.tickerKey(exchangeA, CURRENCY_PAIR));
    assertNotNull(tickerService.tickerKey(exchangeB, CURRENCY_PAIR));

    // TODO we get this last one due to inaccurate mocking within getTickers()
    // in a real situation we'd only get the first two
    assertNotNull(tickerService.tickerKey(exchangeB, CurrencyPair.ETH_USD));
}
 
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: TradingServiceTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetVolumeForOrderNotAvailable() throws IOException {
    doReturn(new BigDecimal("90.0"))
        .when(tradingService)
        .getAccountBalance(any(Exchange.class), any(Currency.class), anyInt());

    BigDecimal volume = tradingService.getVolumeForOrder(
            longExchange,
            currencyPair,
            "notAvailable",
            new BigDecimal("50.0"));

    assertEquals(new BigDecimal("90.0"), volume);
}
 
Example #25
Source File: TradingServiceTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetVolumeForOrderIOException() throws IOException {
    doReturn(new BigDecimal("90.0"))
        .when(tradingService)
        .getAccountBalance(any(Exchange.class), any(Currency.class), anyInt());

    BigDecimal volume = tradingService.getVolumeForOrder(
            longExchange,
            currencyPair,
            "ioe",
            new BigDecimal("50.0"));

    assertEquals(new BigDecimal("90.0"), volume);
}
 
Example #26
Source File: OkCoinAccountServiceRaw.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Constructor
 *
 * @param exchange
 */
protected OkCoinAccountServiceRaw(Exchange exchange) {

  super(exchange);

  tradepwd =
      (String) exchange.getExchangeSpecification().getExchangeSpecificParametersItem("tradepwd");
}
 
Example #27
Source File: ExchangeFeeCacheTest.java    From arbitrader with MIT License 5 votes vote down vote up
@Test
public void testGetUnknownExchange() {
    Exchange altExchange = mock(Exchange.class);
    ExchangeSpecification altSpec = mock(ExchangeSpecification.class);

    when(altExchange.getExchangeSpecification()).thenReturn(altSpec);
    when(altSpec.getExchangeName()).thenReturn("AltEx");

    assertNull(exchangeFeeCache.getCachedFee(altExchange, currencyPair));
}
 
Example #28
Source File: OKCoinBaseTradeService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Constructor
 *
 * @param exchange
 */
protected OKCoinBaseTradeService(Exchange exchange) {

  super(exchange);

  okCoin =
      RestProxyFactory.createProxy(
          OkCoin.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig());
  apikey = exchange.getExchangeSpecification().getApiKey();
  secretKey = exchange.getExchangeSpecification().getSecretKey();
}
 
Example #29
Source File: DefaultOpenOrdersParamCurrencyPair.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public static List<CurrencyPair> getPairs(OpenOrdersParams params, Exchange exchange) {
  List<CurrencyPair> pairs = new ArrayList<>();
  if (params instanceof OpenOrdersParamCurrencyPair) {
    final CurrencyPair paramsCp = ((OpenOrdersParamCurrencyPair) params).getCurrencyPair();
    if (paramsCp != null) {
      pairs.add(paramsCp);
    }
  }
  if (pairs.isEmpty()) {
    pairs = exchange.getExchangeSymbols();
  }
  return pairs;
}
 
Example #30
Source File: HuobiBaseService.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public HuobiBaseService(Exchange exchange) {
  super(exchange);
  huobi =
      RestProxyFactory.createProxy(
          Huobi.class, exchange.getExchangeSpecification().getSslUri(), getClientConfig());
  signatureCreator =
      HuobiDigest.createInstance(exchange.getExchangeSpecification().getSecretKey());
}