Exemplo n.º 1
0
        /// <summary>
        /// Parses amount string returned by Privatbank API.
        /// Returns null if failed to parse currency or value.
        /// </summary>
        /// <param name="amount">Amount string in format '-0.10 UAH'</param>
        /// <returns></returns>
        public override PrivatbankAmount Parse(string s)
        {
            if (string.IsNullOrWhiteSpace(s))
            {
                return(null);
            }

            string[] amountParts = s.Split(' ');

            if (amountParts.Length != 2)
            {
                return(null);
            }

            string  currency = ISO4217CurrencyCompatibility.GetActive(amountParts[1]);
            decimal?amount   = NullableDecimalConverter.Convert(amountParts[0]);

            if (string.IsNullOrWhiteSpace(currency) || !amount.HasValue)
            {
                return(null);
            }

            return(new PrivatbankAmount(currency, amount.Value));
        }
        /// <summary>
        /// Gets exchange rates of Privatbank.
        /// Reference: <https://api.privatbank.ua/#p24/exchange>
        /// </summary>
        /// <returns></returns>
        public async Task <IReadOnlyCollection <PrivatbankExchangeRate> > GetBankExchangeRatesAsync()
        {
            List <PrivatbankExchangeRate> result = new List <PrivatbankExchangeRate>();

            foreach (string type in currencyTypes)
            {
                HttpResponseMessage response = await _privatbankClient.GetPublicDataAsync($"pubinfo?json&exchange&coursid={type}");

                string json = await response.Content.ReadAsStringAsync();

                var ratesResponse = JsonConvert.DeserializeObject <IEnumerable <ExchangeRateResponse> >(json);

                IEnumerable <PrivatbankExchangeRate> rates = ratesResponse
                                                             .Select(r => new PrivatbankExchangeRate(
                                                                         ISO4217CurrencyCompatibility.GetActive(r.Ccy),
                                                                         ISO4217CurrencyCompatibility.GetActive(r.Base_ccy),
                                                                         r.Buy,
                                                                         r.Sale));

                result.AddRange(rates);
            }

            return(result);
        }