Search in sources :

Example 1 with Params

use of org.knowm.xchange.service.marketdata.params.Params in project XChange by knowm.

the class MarketDataFetchIntegration method Tests.

@Test
public void Tests() throws Exception, InterruptedException {
    // Ticker Test
    Thread.sleep(1000);
    Ticker ticker = btcTurkMarketDataService.getTicker(new CurrencyPair("BTC", "TRY"));
    System.out.println(ticker.toString());
    assertThat(ticker).isNotNull();
    Thread.sleep(1000);
    List<Ticker> tickers = btcTurkMarketDataService.getTickers(new Params() {
    });
    for (Ticker _ticker : tickers) {
        System.out.println(_ticker.toString());
        assertThat(_ticker).isNotNull();
    }
    Thread.sleep(1000);
    // TradesTest
    Trades trades = btcTurkMarketDataService.getTrades(CurrencyPair.BTC_TRY);
    assertThat(trades.getTrades().size()).isEqualTo(50);
    Thread.sleep(1000);
    trades = btcTurkMarketDataService.getTrades(CurrencyPair.BTC_TRY, 5);
    assertThat(trades.getTrades().size()).isEqualTo(5);
    Thread.sleep(1000);
    // OHCLTest
    List<BTCTurkOHLC> btcTurkBTCTurkOHLC = btcTurkMarketDataService.getBTCTurkOHLC(CurrencyPair.BTC_TRY);
    // Daily size is always changing
    assertThat(btcTurkBTCTurkOHLC.size()).isNotEqualTo(0);
    Thread.sleep(1000);
    List<BTCTurkOHLC> btcTurkBTCTurkOHLC2 = btcTurkMarketDataService.getBTCTurkOHLC(CurrencyPair.BTC_TRY, 2);
    assertThat(btcTurkBTCTurkOHLC2.size()).isEqualTo(2);
    // OrderBookTest
    Thread.sleep(1000);
    BTCTurkOrderBook btcTurkBTCTurkOrderBook = btcTurkMarketDataService.getBTCTurkOrderBook(CurrencyPair.BTC_TRY);
    assertThat(btcTurkBTCTurkOrderBook.getAsks().size()).isEqualTo(100);
    assertThat(btcTurkBTCTurkOrderBook.getBids().size()).isEqualTo(100);
}
Also used : Trades(org.knowm.xchange.dto.marketdata.Trades) Ticker(org.knowm.xchange.dto.marketdata.Ticker) Params(org.knowm.xchange.service.marketdata.params.Params) BTCTurkOrderBook(org.knowm.xchange.btcturk.dto.marketdata.BTCTurkOrderBook) BTCTurkOHLC(org.knowm.xchange.btcturk.dto.marketdata.BTCTurkOHLC) CurrencyPair(org.knowm.xchange.currency.CurrencyPair) Test(org.junit.Test) BTCTurkDemoUtilsTest(org.knowm.xchange.btcturk.service.BTCTurkDemoUtilsTest)

Example 2 with Params

use of org.knowm.xchange.service.marketdata.params.Params in project XChange by knowm.

the class MarketDataServiceIntegration method getTickers.

private static void getTickers() throws IOException {
    Exchange exchange = getExchange();
    MarketDataService marketDataService = exchange.getMarketDataService();
    try {
        Params params = null;
        List<Ticker> tickers = marketDataService.getTickers(params);
        System.out.println("======get tickers======");
        System.out.println(tickers);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : EXXExchange(org.knowm.xchange.exx.EXXExchange) Exchange(org.knowm.xchange.Exchange) MarketDataService(org.knowm.xchange.service.marketdata.MarketDataService) Ticker(org.knowm.xchange.dto.marketdata.Ticker) Params(org.knowm.xchange.service.marketdata.params.Params) IOException(java.io.IOException)

Example 3 with Params

use of org.knowm.xchange.service.marketdata.params.Params in project XChange by knowm.

the class QuoineMarketDataServiceTest method testGetTickersWrongParamType.

@Test(expected = IllegalArgumentException.class)
public void testGetTickersWrongParamType() throws IOException {
    Params params = new Params() {
    };
    service.getTickers(params);
}
Also used : Params(org.knowm.xchange.service.marketdata.params.Params) Test(org.junit.Test)

Example 4 with Params

use of org.knowm.xchange.service.marketdata.params.Params in project haveno by haveno-dex.

the class ExchangeRateProvider method doGet.

/**
 * @param exchangeClass Class of the {@link Exchange} for which the rates should be
 *                      polled
 * @return Exchange rates for Bisq-supported fiat currencies and altcoins in the
 * specified {@link Exchange}
 *
 * @see CurrencyUtil#getAllSortedFiatCurrencies()
 * @see CurrencyUtil#getAllSortedCryptoCurrencies()
 */
protected Set<ExchangeRate> doGet(Class<? extends Exchange> exchangeClass) {
    Set<ExchangeRate> result = new HashSet<ExchangeRate>();
    // Initialize XChange objects
    Exchange exchange = ExchangeFactory.INSTANCE.createExchange(exchangeClass.getName());
    MarketDataService marketDataService = exchange.getMarketDataService();
    // Retrieve all currency pairs supported by the exchange
    List<CurrencyPair> allCurrencyPairsOnExchange = exchange.getExchangeSymbols();
    // Find out which currency pairs we are interested in polling ("desired pairs")
    // This will be the intersection of:
    // 1) the pairs available on the exchange, and
    // 2) the pairs Bisq considers relevant / valid
    // This will result in two lists of desired pairs (fiat and alts)
    // Find the desired fiat pairs (pair format is BTC-FIAT)
    List<CurrencyPair> desiredFiatPairs = allCurrencyPairsOnExchange.stream().filter(cp -> cp.base.equals(Currency.BTC)).filter(cp -> getSupportedFiatCurrencies().contains(cp.counter.getCurrencyCode())).collect(Collectors.toList());
    // Find the desired altcoin pairs (pair format is ALT-BTC)
    List<CurrencyPair> desiredCryptoPairs = allCurrencyPairsOnExchange.stream().filter(cp -> cp.counter.equals(Currency.BTC)).filter(cp -> getSupportedCryptoCurrencies().contains(cp.base.getCurrencyCode())).collect(Collectors.toList());
    // Retrieve in bulk all tickers offered by the exchange
    // The benefits of this approach (vs polling each ticker) are twofold:
    // 1) the polling of the exchange is faster (one HTTP call vs several)
    // 2) it's easier to stay below any API rate limits the exchange might have
    List<Ticker> tickersRetrievedFromExchange = new ArrayList<>();
    try {
        tickersRetrievedFromExchange = marketDataService.getTickers(new CurrencyPairsParam() {

            /**
             * The {@link MarketDataService#getTickers(Params)} interface requires a
             * {@link CurrencyPairsParam} argument when polling for tickers in bulk.
             * This parameter is meant to indicate a list of currency pairs for which
             * the tickers should be polled. However, the actual implementations for
             * the different exchanges differ, for example:
             * - some will ignore it (and retrieve all available tickers)
             * - some will require it (and will fail if a null or empty list is given)
             * - some will properly handle it
             *
             * We take a simplistic approach, namely:
             * - for providers that require such a filter, specify one
             * - for all others, do not specify one
             *
             * We make this distinction using
             * {@link ExchangeRateProvider#requiresFilterDuringBulkTickerRetrieval}
             *
             * @return Filter (list of desired currency pairs) to be used during bulk
             * ticker retrieval
             */
            @Override
            public Collection<CurrencyPair> getCurrencyPairs() {
                // (list of pairs which should be retrieved)
                if (requiresFilterDuringBulkTickerRetrieval()) {
                    return Stream.of(desiredFiatPairs, desiredCryptoPairs).flatMap(Collection::stream).collect(Collectors.toList());
                }
                // simply return all available tickers
                return Collections.emptyList();
            }
        });
        if (tickersRetrievedFromExchange.isEmpty()) {
            // work. See requiresFilterDuringBulkTickerRetrieval()
            throw new IllegalArgumentException("No tickers retrieved, " + "exchange requires explicit filter argument during bulk retrieval?");
        }
    } catch (NotYetImplementedForExchangeException e) {
        // Thrown when a provider has no marketDataService.getTickers() implementation
        // either because the exchange API does not provide it, or because it has not
        // been implemented yet in the knowm xchange library
        // In this case (retrieval of bulk tickers is not possible) retrieve the
        // tickers one by one
        List<Ticker> finalTickersRetrievedFromExchange = tickersRetrievedFromExchange;
        Stream.of(desiredFiatPairs, desiredCryptoPairs).flatMap(Collection::stream).collect(Collectors.toList()).forEach(cp -> {
            try {
                // like ResilienceSpecification (needs knowm xchange libs v5)
                if (getMarketDataCallDelay() > 0) {
                    Thread.sleep(getMarketDataCallDelay());
                }
                Ticker ticker = marketDataService.getTicker(cp);
                finalTickersRetrievedFromExchange.add(ticker);
            } catch (IOException | InterruptedException ioException) {
                ioException.printStackTrace();
                log.error("Could not query tickers for " + getName(), e);
            }
        });
    } catch (// Errors reported by the exchange (rate limit, etc)
    ExchangeException | // Errors while trying to connect to the API (timeouts, etc)
    IOException | // requiresFilterDuringBulkTickerRetrieval() and have it return true )
    IllegalArgumentException e) {
        // Catch and handle all other possible exceptions
        // If there was a problem with polling this exchange, return right away,
        // since there are no results to parse and process
        log.error("Could not query tickers for provider " + getName(), e);
        return result;
    }
    // Create an ExchangeRate for each desired currency pair ticker that was retrieved
    Predicate<Ticker> isDesiredFiatPair = t -> desiredFiatPairs.contains(t.getCurrencyPair());
    Predicate<Ticker> isDesiredCryptoPair = t -> desiredCryptoPairs.contains(t.getCurrencyPair());
    tickersRetrievedFromExchange.stream().filter(// Only consider desired pairs
    isDesiredFiatPair.or(isDesiredCryptoPair)).forEach(t -> {
        // All tickers here match all requirements
        // We have two kinds of currency pairs, BTC-FIAT and ALT-BTC
        // In the first one, BTC is the first currency of the pair
        // In the second type, BTC is listed as the second currency
        // Distinguish between the two and create ExchangeRates accordingly
        // In every Bisq ExchangeRate, BTC is one currency in the pair
        // Extract the other currency from the ticker, to create ExchangeRates
        String otherExchangeRateCurrency;
        if (t.getCurrencyPair().base.equals(Currency.BTC)) {
            otherExchangeRateCurrency = t.getCurrencyPair().counter.getCurrencyCode();
        } else {
            otherExchangeRateCurrency = t.getCurrencyPair().base.getCurrencyCode();
        }
        result.add(new ExchangeRate(otherExchangeRateCurrency, t.getLast(), // Some exchanges do not provide timestamps
        t.getTimestamp() == null ? new Date() : t.getTimestamp(), this.getName()));
    });
    return result;
}
Also used : Arrays(java.util.Arrays) TradeCurrency(bisq.core.locale.TradeCurrency) CurrencyPairsParam(org.knowm.xchange.service.marketdata.params.CurrencyPairsParam) Date(java.util.Date) Params(org.knowm.xchange.service.marketdata.params.Params) Exchange(org.knowm.xchange.Exchange) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) PriceProvider(bisq.price.PriceProvider) Duration(java.time.Duration) CurrencyUtil(bisq.core.locale.CurrencyUtil) NotYetImplementedForExchangeException(org.knowm.xchange.exceptions.NotYetImplementedForExchangeException) ExchangeFactory(org.knowm.xchange.ExchangeFactory) Ticker(org.knowm.xchange.dto.marketdata.Ticker) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ExchangeException(org.knowm.xchange.exceptions.ExchangeException) Currency(org.knowm.xchange.currency.Currency) List(java.util.List) MarketDataService(org.knowm.xchange.service.marketdata.MarketDataService) Stream(java.util.stream.Stream) Environment(org.springframework.core.env.Environment) CurrencyPair(org.knowm.xchange.currency.CurrencyPair) Collections(java.util.Collections) Ticker(org.knowm.xchange.dto.marketdata.Ticker) ArrayList(java.util.ArrayList) NotYetImplementedForExchangeException(org.knowm.xchange.exceptions.NotYetImplementedForExchangeException) IOException(java.io.IOException) CurrencyPairsParam(org.knowm.xchange.service.marketdata.params.CurrencyPairsParam) Date(java.util.Date) Exchange(org.knowm.xchange.Exchange) MarketDataService(org.knowm.xchange.service.marketdata.MarketDataService) ArrayList(java.util.ArrayList) List(java.util.List) NotYetImplementedForExchangeException(org.knowm.xchange.exceptions.NotYetImplementedForExchangeException) ExchangeException(org.knowm.xchange.exceptions.ExchangeException) HashSet(java.util.HashSet) CurrencyPair(org.knowm.xchange.currency.CurrencyPair)

Example 5 with Params

use of org.knowm.xchange.service.marketdata.params.Params in project XChange by knowm.

the class QuoineMarketDataService method getTickers.

@Override
public List<Ticker> getTickers(Params params) throws IOException {
    if (!(params instanceof CurrencyPairsParam)) {
        throw new IllegalArgumentException("Params must be instance of CurrencyPairsParam");
    }
    CurrencyPairsParam pairs = (CurrencyPairsParam) params;
    QuoineProduct[] products = getQuoineProducts();
    return Arrays.stream(products).filter(product -> pairs.getCurrencyPairs().stream().anyMatch(pair -> product.getBaseCurrency().equals(pair.base.getCurrencyCode()) && product.getQuotedCurrency().equals(pair.counter.getCurrencyCode()))).map(product -> QuoineAdapters.adaptTicker(product, buildCurrencyPair(product))).collect(Collectors.toList());
}
Also used : Arrays(java.util.Arrays) Ticker(org.knowm.xchange.dto.marketdata.Ticker) CurrencyPairsParam(org.knowm.xchange.service.marketdata.params.CurrencyPairsParam) NotAvailableFromExchangeException(org.knowm.xchange.exceptions.NotAvailableFromExchangeException) Params(org.knowm.xchange.service.marketdata.params.Params) IOException(java.io.IOException) Exchange(org.knowm.xchange.Exchange) Collectors(java.util.stream.Collectors) OrderBook(org.knowm.xchange.dto.marketdata.OrderBook) Trades(org.knowm.xchange.dto.marketdata.Trades) QuoineAdapters(org.knowm.xchange.quoine.QuoineAdapters) QuoineProduct(org.knowm.xchange.quoine.dto.marketdata.QuoineProduct) List(java.util.List) MarketDataService(org.knowm.xchange.service.marketdata.MarketDataService) QuoineOrderBook(org.knowm.xchange.quoine.dto.marketdata.QuoineOrderBook) CurrencyPair(org.knowm.xchange.currency.CurrencyPair) QuoineProduct(org.knowm.xchange.quoine.dto.marketdata.QuoineProduct) CurrencyPairsParam(org.knowm.xchange.service.marketdata.params.CurrencyPairsParam)

Aggregations

Params (org.knowm.xchange.service.marketdata.params.Params)5 Ticker (org.knowm.xchange.dto.marketdata.Ticker)4 IOException (java.io.IOException)3 Exchange (org.knowm.xchange.Exchange)3 CurrencyPair (org.knowm.xchange.currency.CurrencyPair)3 MarketDataService (org.knowm.xchange.service.marketdata.MarketDataService)3 Arrays (java.util.Arrays)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 Test (org.junit.Test)2 Trades (org.knowm.xchange.dto.marketdata.Trades)2 CurrencyPairsParam (org.knowm.xchange.service.marketdata.params.CurrencyPairsParam)2 CurrencyUtil (bisq.core.locale.CurrencyUtil)1 TradeCurrency (bisq.core.locale.TradeCurrency)1 PriceProvider (bisq.price.PriceProvider)1 Duration (java.time.Duration)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Date (java.util.Date)1