use of org.knowm.xchange.service.marketdata.params.CurrencyPairsParam in project XChange by knowm.
the class TickerFetchIntegration method getTickersTest.
@Test
public void getTickersTest() throws Exception {
CurrencyPairsParam pairsParam = () -> {
Set<CurrencyPair> pairs = new HashSet<>();
pairs.add(CurrencyPair.BTC_USD);
pairs.add(CurrencyPair.ETH_USD);
pairs.add(CurrencyPair.LTC_USD);
return pairs;
};
List<Ticker> tickerList = cmcMarketDataService.getTickers(pairsParam);
assertThat(tickerList).isNotNull();
assertThat(tickerList).isNotEmpty();
assertThat(tickerList.size()).isEqualTo(3);
}
use of org.knowm.xchange.service.marketdata.params.CurrencyPairsParam in project XChange by knowm.
the class CmcMarketDataService method getTickers.
@Override
public List<Ticker> getTickers(Params params) throws IOException {
if (!(params instanceof CurrencyPairsParam)) {
throw new IllegalArgumentException("Params must be instance of CurrencyPairsParam");
}
Collection<CurrencyPair> pairs = ((CurrencyPairsParam) params).getCurrencyPairs();
Set<Currency> baseSymbols = new HashSet<>();
Set<Currency> convertSymbols = new HashSet<>();
for (CurrencyPair pair : pairs) {
baseSymbols.add(pair.base);
convertSymbols.add(pair.counter);
}
Map<String, CmcTicker> cmcTickerMap = super.getCmcLatestQuotes(baseSymbols, convertSymbols);
return CmcAdapter.adaptTickerMap(cmcTickerMap);
}
use of org.knowm.xchange.service.marketdata.params.CurrencyPairsParam in project bitcoin-spring-boot-starter by theborakompanioni.
the class TickerCommandRunner method doRun.
@Override
@SneakyThrows
protected void doRun(ApplicationArguments args) {
log.debug("Fetch ticker on exchange {}", exchange);
Currency cryptoCurrency = Currency.BTC;
Currency fiatCurrency = Currency.getInstance(properties.getFiatCurrency());
CurrencyPair currencyPair = new CurrencyPair(cryptoCurrency, fiatCurrency);
boolean supportedCurrencyPair = exchange.getExchangeSymbols().contains(currencyPair);
if (!supportedCurrencyPair) {
throw new IllegalStateException("Currency pair is not supported: " + currencyPair);
}
CurrencyPairsParam currencyPairsParam = () -> Collections.singletonList(currencyPair);
List<Ticker> tickers = exchange.getMarketDataService().getTickers(currencyPairsParam);
tickers.forEach(ticker -> {
BigDecimal spreadAskBid = calcSpreadToAskPrice(ticker, ticker.getBid());
BigDecimal spreadAskHigh = calcSpreadToAskPrice(ticker, ticker.getHigh());
BigDecimal spreadAskLow = calcSpreadToAskPrice(ticker, ticker.getLow());
BigDecimal spreadAskOpen = calcSpreadToAskPrice(ticker, ticker.getOpen());
BigDecimal spreadAskLast = calcSpreadToAskPrice(ticker, ticker.getLast());
System.out.printf("Name \t%12s\t%10s\t%10s %n", "Value", "Instrument", "Spread");
System.out.printf("📈 Ask: \t%12s\t%10s%n", displayValue(ticker.getAsk()), ticker.getInstrument());
System.out.printf("📉 Bid: \t%12s\t%10s\t%10s%%%n", displayValue(ticker.getBid()), ticker.getInstrument(), spreadAskBid.toPlainString());
System.out.printf("- High: \t%12s\t%10s\t%10s%%%n", displayValue(ticker.getHigh()), ticker.getInstrument(), spreadAskHigh.toPlainString());
System.out.printf("- Low: \t%12s\t%10s\t%10s%%%n", displayValue(ticker.getLow()), ticker.getInstrument(), spreadAskLow.toPlainString());
System.out.printf("- Open: \t%12s\t%10s\t%10s%%%n", displayValue(ticker.getOpen()), ticker.getInstrument(), spreadAskOpen.toPlainString());
System.out.printf("- Last: \t%12s\t%10s\t%10s%%%n", displayValue(ticker.getLast()), ticker.getInstrument(), spreadAskLast.toPlainString());
});
}
use of org.knowm.xchange.service.marketdata.params.CurrencyPairsParam in project cassandre-trading-bot by cassandre-tech.
the class MarketServiceXChangeImplementation method getTickers.
@Override
@SuppressWarnings("checkstyle:DesignForExtension")
public Set<TickerDTO> getTickers(@NonNull final Set<CurrencyPairDTO> currencyPairs) {
try {
// We create the currency pairs parameter required by some exchanges.
CurrencyPairsParam params = () -> currencyPairs.stream().map(CURRENCY_MAPPER::mapToCurrencyPair).toList();
// Consume a token from the token bucket.
// If a token is not available this method will block until the refill adds one to the bucket.
bucket.asBlocking().consume(1);
logger.debug("Retrieving ticker for {} currency pair", currencyPairs.size());
final List<Ticker> tickers = marketDataService.getTickers(params);
return tickers.stream().map(TICKER_MAPPER::mapToTickerDTO).peek(t -> logger.debug(" - New ticker: {}", t)).collect(Collectors.toCollection(LinkedHashSet::new));
} catch (IOException e) {
logger.error("Error retrieving tickers: {}", e.getMessage());
return Collections.emptySet();
} catch (InterruptedException e) {
return Collections.emptySet();
}
}
use of org.knowm.xchange.service.marketdata.params.CurrencyPairsParam 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;
}
Aggregations