Beispiel #1
0
 public Task <Result <Price> > GetPriceAsync(ExamId examId)
 {
     return(Task.FromResult(Price.Create(
                                net: Money.Create(100, SupportedCurrencies.USD()).Value,
                                tax: Money.Create(0, SupportedCurrencies.USD()).Value,
                                _singleCurrencyPolicy)));
 }
Beispiel #2
0
        public static Response <decimal?> GetConversion(SupportedCurrencies ToCurrency)
        {
            //var str = Enum.GetName(typeof(Iso4217), ToCurrency);

            Response <decimal?> resp = new Response <decimal?>();

            var url = $"https://free.currencyconverterapi.com/api/v6/convert?q=USD_{Enum.GetName(typeof(SupportedCurrencies), ToCurrency)}&compact=ultra";

            using (var httpClient = new HttpClient())
            {
                var res = httpClient.GetAsync(url).Result;
                if (res.IsSuccessStatusCode)
                {
                    var str    = res.Content.ReadAsStringAsync().Result;
                    var result = JsonConvert.DeserializeObject <RootObject>(res.Content.ReadAsStringAsync().Result);
                    resp.Result = (decimal)result.Values.Values.First();
                }
                else
                {
                    resp.Errors.Add(res.ReasonPhrase);
                    resp.Result = null;
                }
            }
            return(resp);
        }
        public static Price CreatePrice(decimal net, decimal tax)
        {
            var netResult = Money.Create(net, SupportedCurrencies.USD());
            var taxResult = Money.Create(tax, SupportedCurrencies.USD());

            return(Price.Create(netResult.Value, taxResult.Value, MockObjectsBuilder.BuildSingleCurrencyPolicy(true)).Value);
        }
Beispiel #4
0
        public void ShouldReturnExpectedResult(decimal value, bool expected)
        {
            var money = Money.Create(value, SupportedCurrencies.CHF()).Value;

            var result = CommonErrors.GreaterThanOrEqualZero.Check(money);

            result.IsSuccess.Should().Be(expected);
        }
Beispiel #5
0
 public decimal GetExchangeLimit(SupportedCurrencies parsedCurrency)
 {
     return(parsedCurrency switch
     {
         SupportedCurrencies.USD => USDLimit,
         SupportedCurrencies.BRL => BRLLimit,
         _ => throw new InvalidCurrencyException("mocked"),
     });
        public void ShouldReturnExpectedResult(decimal net, decimal tax, bool expected, string because)
        {
            var netValue = Money.Create(net, SupportedCurrencies.USD()).Value;
            var taxValue = Money.Create(tax, SupportedCurrencies.USD()).Value;

            var priceResult = Price.Create(netValue, taxValue, MockObjectsBuilder.BuildSingleCurrencyPolicy(true));

            priceResult.IsSuccess.Should().Be(expected, because);
        }
Beispiel #7
0
        /// <summary>
        /// Finds the right Currency by the official naming. The most API's should match ISO 4217. If not it is possible to add another alternative key here
        /// </summary>
        /// <param name="key">The currency naming in three letters most likely ISO 4217 e.g. USD, EUR, CNY</param>
        /// <returns>The currency which matches the three letter naming</returns>
        /// <exception cref="CurrencyNotSupportedException"></exception>
        public CurrencyBase GetCurrency(String key)
        {
            key = key.ToUpperInvariant();
            // I have implemented two keys, because crypto currencies are not official yet and there are some inconsistencies e.g. Kraken (XBT) differs from Bitfinex (BTC)
            var currency = SupportedCurrencies.FirstOrDefault(x => x.Key == key || x.AlternativeKey == key);

            if (default(CurrencyBase) == currency)
            {
                throw new CurrencyNotSupportedException {
                          CurrencyKey = key
                };
            }
            return(currency);
        }
Beispiel #8
0
        public async Task Test_GetSupportedCurrenciesAsync()
        {
            var resp = await this.currencyClient.GetSupportedCurrenciesAsync("ACCESS_KEY");

            var expected = new SupportedCurrencies()
            {
                Currencies = new Dictionary <string, string>()
                {
                    { "AED", "United Arab Emirates Dirham" },
                    { "AFN", "Afghan Afghani" }
                }
            };

            Assert.AreEqual(resp.Currencies["AED"], expected.Currencies["AED"]);
        }
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            if (SupportedCurrencies.ContainsKey(currency))
            {
                using (WebClient client = new WebClient())
                {
                    try
                    {
                        RateDate = date;
                        string startDate = date.ToString("yyyyMMdd");
                        Uri    methodUri = new Uri($"{baseUrl}{currency}&{startDate}&json");
                        string json      = await client.DownloadStringTaskAsync(methodUri);

                        JArray ja = (JArray)JsonConvert.DeserializeObject(json);
                        if (ja.Count != 0)
                        {
                            decimal result = decimal.Zero;
                            decimal.TryParse(ja.SelectToken("$[0].rate").ToString(), out result);

                            bankResult.ExchangeRate = result;
                            return(bankResult);
                        }
                        else
                        {
                            return(await GetRateAsync(currency, date.AddDays(-1)));
                        }
                    }
                    catch
                    {
                        return(bankResult);
                    }
                };
            }
            else
            {
                return(bankResult);
            }
        }
        public SupportedCurrency GetCurrentCurrency()
        {
            // Check if the custom currency header is present
            var isHeaderPresent = httpContextAccessor.HttpContext.Request.Headers.TryGetValue(HEADER_CURRENCY, out StringValues stringValues);

            // Check if the currency is supported
            if (isHeaderPresent && SupportedCurrencies.Any(x => x.Code == stringValues.FirstOrDefault()))
            {
                return(SupportedCurrencies.FirstOrDefault(x => x.Code == stringValues.FirstOrDefault()));
            }
            else
            {
                return(SupportedCurrencies
                       .Where(x => x.IsDefault)
                       .FirstOrDefault());
            }
        }
Beispiel #11
0
        public async Task Test_GetSupportedCurrencies_InvalidRequestAsync()
        {
            var resp = await this.currencyClient.GetSupportedCurrenciesAsync("0abc1d892b869d7fa2f528a05984eb9");

            var expected = new SupportedCurrencies()
            {
                Success = false,
                Error   = new Error()
                {
                    Type = "invalid_access_key",
                    Code = 101,
                    Info = "You have not supplied a valid API Access Key. [Technical Support: [email protected]]"
                }
            };

            resp.Should().BeEquivalentTo <SupportedCurrencies>(expected);
        }
Beispiel #12
0
        public async Task Test_GetSupportedCurrenciesAsync_Mock()
        {
            var res      = new Mock <ICurrencyLayerClient>();
            var mockData = JsonConvert.DeserializeObject <SupportedCurrencies>(File.ReadAllText(@".\MockData\supportedCurrencies.json"));

            res.Setup(h => h.GetSupportedCurrenciesAsync(It.IsAny <string>())).Returns(Task.FromResult(mockData));

            var expected = new SupportedCurrencies()
            {
                Currencies = new Dictionary <string, string>()
                {
                    { "AED", "United Arab Emirates Dirham" },
                    { "AFN", "Afghan Afghani" }
                }
            };

            var actual = await res.Object.GetSupportedCurrenciesAsync("jsafda");

            Assert.AreEqual(expected.Currencies["AED"], actual.Currencies["AED"]);
        }
Beispiel #13
0
        /// <summary>
        /// Provided a normalized currency, it returns instance of ExchangeHelper in order to
        /// get things such as Current Rate or Currency Purchase Limit
        /// </summary>
        /// <param name="parsedCurrency">Enum SupportedCurrencies</param>
        /// <returns>An instance of one strategy of currencies</returns>
        private ExchangeHelper GetExchangeHelperByCurrency(SupportedCurrencies parsedCurrency)
        {
            ExchangeHelper exchangeRate;

            switch (parsedCurrency)
            {
            case SupportedCurrencies.USD:
                exchangeRate = new ExchangeHelper(new UsdCurrency(_httpClient, _logger));
                break;

            case SupportedCurrencies.BRL:
                exchangeRate = new ExchangeHelper(new BrlCurrency(_httpClient, _logger));
                break;

            default:
                _logger.LogCritical("There is an invalid currency in the supported currencies");
                throw new NotImplementedException("Unexpected error: check the GetValidCurrencyFromISO method, there is a not supported currency");
            }

            return(exchangeRate);
        }
Beispiel #14
0
        /*public double GetEarningsInUsd(ICurrency currency)
         * {
         *  Dictionary<DateTime, Dictionary<ICurrency, double>> balanceHistory = BalanceHistory;
         *
         *
         *  double balance = 0.0;
         *  double previousBalance = 0.0;
         *  foreach (KeyValuePair<DateTime, Dictionary<ICurrency, double>> balanceHistoricalEntry in balanceHistory)
         *  {
         *      if (!balanceHistoricalEntry.Value.ContainsKey(currency))
         *      {
         *        continue;
         *      }
         *
         *      IDictionary<ICurrency, double> entry = balanceHistoricalEntry.Value;
         *      if (Math.Abs(previousBalance - entry[currency]) > double.Epsilon)
         *      {
         *          IExchangeRate exchangeRate = _exchangeRates.First(exrat => exrat.ReferenceCurrency == currency);
         *          double price = exchangeRate.GetPriceInUsd(balanceHistoricalEntry.Key, currency);
         *
         *
         *      }
         *      previousBalance = balanceEntry[currency];
         *  }
         * }*/
        public void RefreshHoldings()
        {
            AccountInfo accountInfo = BinanceDataPool.GetAccountInfo();

            Dictionary <ICurrency, double> balances = new Dictionary <ICurrency, double>();

            foreach (AccountInfo.Balance balance in accountInfo.balances)
            {
                double balanceD = double.Parse(balance.free);

                ICurrency currency = SupportedCurrencies.FirstOrDefault(curr => curr.Symbol == balance.asset);
                if (currency != null)
                {
                    balances.Add(currency, balanceD);
                }
            }

            Dictionary <DateTime, Dictionary <ICurrency, double> > balanceHistory = _balanceHistory.Where(pair => pair.Key > DateTime.Now - MaxHistory)
                                                                                    .ToDictionary(pair => pair.Key, pair => pair.Value);

            balanceHistory.Add(DateTime.Now, balances);
            _balanceHistory = balanceHistory;
        }
Beispiel #15
0
 public async Task <CurrencyRateDto> GetCurrencyRate(SupportedCurrencies baseCurrency, SupportedCurrencies toCurrency)
 {
     return(await GetCurrencyRate(baseCurrency.GetStringValue(), toCurrency.GetStringValue()));
 }
Beispiel #16
0
 public decimal GetExchangeLimit(SupportedCurrencies parsedCurrency) => GetExchangeHelperByCurrency(parsedCurrency).GetExchangeLimit();
Beispiel #17
0
 public Task <decimal> GetExchangeRateAsync(SupportedCurrencies parsedCurrency) => GetExchangeHelperByCurrency(parsedCurrency).GetExchangeRateAsync();