Exemple #1
0
        public virtual async Task <ExchangeRatesList> GetExchangeRatesList(string BaseCurrencySymbol, params string[] TargetedCurrencies)
        {
            BaseCurrencySymbol = BaseCurrencySymbol.ToUpper();
            TargetedCurrencies = TargetedCurrencies.Select(e => e.ToUpper()).ToArray();
            if (!supportedCryptoCurrencies.ContainsKey(BaseCurrencySymbol))
            {
                throw new InvalidRequestException($"{BaseCurrencySymbol} is invalid or Unsupported Cryptocurrency");
            }
            if (TargetedCurrencies == null || TargetedCurrencies.Length == 0)
            {
                TargetedCurrencies = _config.DefaultTargetedCurrencies.ToArray();
            }
            else
            {
                var unsupportedCurrencies = TargetedCurrencies.Except(_config.SupportedTargetedCurrencies);
                if (unsupportedCurrencies.Count() == TargetedCurrencies.Length)
                {
                    throw new InvalidRequestException($"[{string.Join(",", unsupportedCurrencies)}] are Unsupported fiat currencies");
                }
                if (unsupportedCurrencies.Any())
                {
                    _logger.LogWarning("[{0}] are invalid or Unsupported fiat currencies", string.Join(",", unsupportedCurrencies));
                    TargetedCurrencies = TargetedCurrencies.Except(unsupportedCurrencies).ToArray();
                }
            }
            string cryptoCurId = supportedCryptoCurrencies[BaseCurrencySymbol].ToString();
            var    query       = HttpUtility.ParseQueryString(String.Empty);

            query["id"]      = cryptoCurId;
            query["convert"] = string.Join(",", TargetedCurrencies);
            query["aux"]     = "is_active"; // adding this parameter to reduce the size of the response
            var request = new HttpRequestMessage(HttpMethod.Get, $"/{_config.Version}/{_config.QuotesEndpoint}?{query}");

            request.Headers.Add(_config.APIKeyName, _config.APIKeyValue);
            var httpclient = _httpClientFactory.CreateClient(ServiceProviderName);
            var response   = await httpclient.SendAsync(request);

            var responseString = await response.Content.ReadAsStringAsync();

            var CoinmarketcapAPIResponse = JsonConvert.DeserializeObject <CoinmarketcapAPIQuotesResponse>(responseString);

            if (response.IsSuccessStatusCode)
            {
                if (CoinmarketcapAPIResponse?.Status?.ErrorCode == 0 &&
                    CoinmarketcapAPIResponse.Status.ErrorMessage == null &&
                    CoinmarketcapAPIResponse.Status.CreditCount > 0 &&
                    CoinmarketcapAPIResponse.Data?.Count > 0 &&
                    CoinmarketcapAPIResponse.Data.Count > 0 &&
                    CoinmarketcapAPIResponse.Data.ContainsKey(cryptoCurId)
                    )
                {
                    return(new ExchangeRatesList()
                    {
                        BaseCurrencySymbol = CoinmarketcapAPIResponse.Data[cryptoCurId].CryptoCurrencySymbol,
                        CurrenciesRates = CoinmarketcapAPIResponse.Data[cryptoCurId].Quote.Where(e => TargetedCurrencies.Contains(e.Key)).ToDictionary(key => key.Key, val => val.Value.Rate)
                    });
                }
            }
            throw new RestAPIException(ServiceProviderName, response.StatusCode, CoinmarketcapAPIResponse.Status.ErrorMessage);
        }
Exemple #2
0
        public override async Task <ExchangeRatesList> GetExchangeRatesList(string BaseCurrencySymbol, params string[] TargetedCurrencies)
        {
            BaseCurrencySymbol = BaseCurrencySymbol.ToUpper();
            TargetedCurrencies = TargetedCurrencies.Select(e => e.ToUpper()).ToArray();
            if (!supportedCurrencies.Contains(BaseCurrencySymbol))
            {
                throw new InvalidRequestException($"{BaseCurrencySymbol} is Unsupported currency");
            }
            if (TargetedCurrencies == null || TargetedCurrencies.Length == 0)
            {
                TargetedCurrencies = _config.DefaultTargetedCurrencies.ToArray();
            }

            List <string>     newTargets        = new List <string>();
            ExchangeRatesList exchangeRatesList = new ExchangeRatesList()
            {
                BaseCurrencySymbol = BaseCurrencySymbol
            };

            foreach (var targetedcurrency in TargetedCurrencies)
            {
                decimal rate;
                if (_memoryCache.TryGetValue(GetCacheKey(BaseCurrencySymbol, targetedcurrency), out rate))
                {
                    exchangeRatesList.CurrenciesRates.Add(targetedcurrency, rate);
                }
                else
                {
                    newTargets.Add(targetedcurrency);
                }
            }
            if (newTargets.Count > 0)
            {
                _logger.LogInformation($"Requesting ExchangeRates of {string.Join(",", newTargets)} from {ServiceProviderName} Provider");
                var rates = await base.GetExchangeRatesList(BaseCurrencySymbol, newTargets.ToArray());

                foreach (var rate in rates.CurrenciesRates)
                {
                    _memoryCache.Set(GetCacheKey(BaseCurrencySymbol, rate.Key), rate.Value, DateTimeOffset.Now.AddMinutes(_config.ExpiredAfterInMinutes));
                    exchangeRatesList.CurrenciesRates.Add(rate.Key, rate.Value);
                }
            }
            return(exchangeRatesList);
        }
        public virtual async Task <ExchangeRatesList> GetExchangeRatesList(string BaseCurrencySymbol, params string[] TargetedCurrencies)
        {
            // validate the input parameters
            BaseCurrencySymbol = BaseCurrencySymbol.ToUpper();
            TargetedCurrencies = TargetedCurrencies.Select(e => e.ToUpper()).ToArray();
            if (!supportedCurrencies.Contains(BaseCurrencySymbol))
            {
                throw new InvalidRequestException($"{BaseCurrencySymbol} is Unsupported currency");
            }
            if (TargetedCurrencies == null || TargetedCurrencies.Length == 0)
            {
                TargetedCurrencies = _config.DefaultTargetedCurrencies.ToArray();
            }
            else
            {
                var unsupportedCurrencies = TargetedCurrencies.Except(supportedCurrencies);
                if (unsupportedCurrencies.Count() == TargetedCurrencies.Length)
                {
                    throw new InvalidRequestException($"[{string.Join(",", unsupportedCurrencies)}] are Unsupported currencies");
                }
                if (unsupportedCurrencies.Any())
                {
                    _logger.LogWarning("[{0}] are invalid or Unsupported currencies", string.Join(",", unsupportedCurrencies));
                    TargetedCurrencies = TargetedCurrencies.Except(unsupportedCurrencies).ToArray();
                }
            }

            // calling the currency exchange provider
            var query = HttpUtility.ParseQueryString(string.Empty);

            query["base"]    = BaseCurrencySymbol;
            query["symbols"] = string.Join(",", TargetedCurrencies);
            var exchangeratesAPIResponse = await SendRequestAsync(query.ToString());

            return(new ExchangeRatesList()
            {
                BaseCurrencySymbol = exchangeratesAPIResponse.BaseCurrency,
                CurrenciesRates = exchangeratesAPIResponse.Rates
            });
        }