예제 #1
0
        public Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            BasicHttpBinding binding         = new BasicHttpBinding();
            EndpointAddress  endPointAddress = new EndpointAddress("http://www.cbr.ru/DailyInfoWebServ/DailyInfo.asmx");
            DailyInfoSoap    client          = new DailyInfoSoapClient(binding, endPointAddress);

            Task <DataSet> fxRates = client.GetCursOnDateAsync(date);

            fxRates.Wait();
            DataTable table = fxRates.Result.Tables["ValuteCursOnDate"];

            string filterExpression = $"VchCode = '{currency}'";

            DataRow[] rows = table.Select(filterExpression);

            decimal.TryParse(rows[0]["Vnom"].ToString(), out decimal multiplier);
            decimal.TryParse(rows[0]["Vcurs"].ToString(), out decimal rate);
            decimal fxRate = rate / multiplier;

            bankResult.ExchangeRate = fxRate;

            return(Task.FromResult(bankResult));
        }
예제 #2
0
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            if (!SupportedCurrencies.ContainsKey(currency))
            {
                throw new NotImplementedException($"{bankName} does not support {currency}");
            }

            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            //https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF60632/datos/2020-03-01/2020-04-08?locale=es
            string startDate = date.ToString("yyyy-MM-dd");
            Uri    methodUri = new Uri($"{baseUrl}/{GetSeriesName(currency)}/datos/{startDate}/{startDate}?locale=en");

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Bmx-Token", bmxToken);
                try
                {
                    //decimal result = 0;
                    string json = "";
                    json = await client.DownloadStringTaskAsync(methodUri);

                    JObject jo = JsonConvert.DeserializeObject <JObject>(json);

                    JObject series = (JObject)jo.SelectToken("$.bmx.series[0]");
                    if (series.Property("datos") == null)
                    {
                        return(await GetRateAsync(currency, date.AddDays(-1)));
                    }

                    string rate        = jo.SelectToken("$.bmx.series[0].datos[0].dato").ToString();
                    string rateDatestr = jo.SelectToken("$.bmx.series[0].datos[0].fecha").ToString();
                    if (!decimal.TryParse(rate, out decimal result))
                    {
                        return(await GetRateAsync(currency, date.AddDays(-1)));
                    }

                    bankResult.ExchangeRate = result;
                    DateTime.TryParseExact(rateDatestr, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime rateDate);

                    bankResult.RateDate = rateDate;
                    return(bankResult);
                }
                catch (JsonException ex)
                {
                    Console.WriteLine(ex.Message);
                    return(bankResult);
                }
            }
        }
예제 #3
0
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            if (!SupportedCurrencies.ContainsKey(currency))
            {
                throw new NotImplementedException($"{bankName} does not support {currency}");
            }

            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };
            //https://sdw-wsrest.ecb.europa.eu/service/data/EXR/D.USD.EUR.SP00.A?startPeriod=2019-11-01&endPeriod=2019-11-04
            string startDate = date.ToString("yyyy-MM-dd");
            Uri    methodUri = new Uri($"{baseUrl}/{resource}/{flowRef}/D.{currency}.EUR.SP00.A?startPeriod={startDate}&endPeriod={startDate}");

            using (WebClient client = new WebClient())
            {
                try
                {
                    decimal result = 0;
                    string  xml    = await client.DownloadStringTaskAsync(methodUri);

                    if (!string.IsNullOrEmpty(xml))
                    {
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.LoadXml(xml);

                        XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
                        namespaceManager.AddNamespace("message", "http://www.sdmx.org/resources/sdmxml/schemas/v2_1/message");
                        namespaceManager.AddNamespace("generic", "http://www.sdmx.org/resources/sdmxml/schemas/v2_1/data/generic");
                        namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                        namespaceManager.AddNamespace("common", "http://www.sdmx.org/resources/sdmxml/schemas/v2_1/common");

                        string xmlPath = $"/message:GenericData/message:DataSet/generic:Series/generic:Obs/generic:ObsValue";
                        string rate    = xmlDocument.SelectSingleNode(xmlPath, namespaceManager).Attributes[0].Value;

                        decimal.TryParse(rate.ToString(), out result);
                        bankResult.ExchangeRate = decimal.Round(1 / result, 4);
                    }
                    else
                    {
                        return(await GetRateAsync(currency, date.AddDays(-1)));
                    }
                }
                catch
                {
                    return(bankResult);
                }
                return(bankResult);
            }
        }
예제 #4
0
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            if (!SupportedCurrencies.ContainsKey(currency))
            {
                throw new NotImplementedException($"{bankName} does not support {currency}");
            }

            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            if (date < earliestDate)
            {
                return(bankResult);
            }

            //https://www.bankofcanada.ca/valet/observations/FXUSDCAD?start_date=2019-11-05&end_date=2019-11-05
            string startDate = date.ToString("yyyy-MM-dd");
            Uri    methodUri = new Uri($"{baseUrl}/observations/FX{currency}CAD?start_date={startDate}&end_date={startDate}");

            using (WebClient client = new WebClient())
            {
                try
                {
                    decimal result = 0;
                    string  json;
                    json = await client.DownloadStringTaskAsync(methodUri);

                    JObject jo = JsonConvert.DeserializeObject <JObject>(json);

                    JArray ja = (JArray)jo.SelectToken("$.observations");
                    if (ja.Count != 0)
                    {
                        string v = ja.SelectToken($"[0].FX{currency}CAD.v").ToString();
                        decimal.TryParse(v, out result);
                        bankResult.ExchangeRate = result;
                        return(bankResult);
                    }
                    else
                    {
                        return(await GetRateAsync(currency, date.AddDays(-1)));
                    }
                }
                catch
                {
                    return(bankResult);
                }
            }
        }
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            if (date < minDate)
            {
                return(bankResult);
            }

            if (SupportedCurrencies.ContainsKey(currency))
            {
                using (WebClient client = new WebClient())
                {
                    try
                    {
                        string startDate = date.ToString("yyyyMMdd");
                        Uri    methodUri = new Uri($"{baseUrl}{currency}&date={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;
                            DateTime.TryParseExact(ja.SelectToken("$[0].exchangedate").ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture,
                                                   DateTimeStyles.None, out DateTime rateDate);

                            bankResult.RateDate = rateDate;
                            return(bankResult);
                        }
                        else
                        {
                            return(await GetRateAsync(currency, date.AddDays(-1)));
                        }
                    }
                    catch
                    {
                        return(bankResult);
                    }
                };
            }
            else
            {
                return(bankResult);
            }
        }
        public Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            IBankResult emptyResult = new BankResult()
            {
                BankName     = bankName,
                HomeCurrency = homeCurrency,
                ExchangeRate = -1M,
                RateDate     = date
            };

            if (date < minDate)
            {
                return(Task.FromResult(emptyResult));
            }

            if (!SupportedCurrencies.ContainsKey(currency))
            {
                throw new NotImplementedException($"{bankName} does not support {currency}");
            }

            DownloadCsvFile();

            while (!parsed)
            {
            }
            var      fxRate = decimal.Zero;
            int      d      = 0;
            DataView dv     = new DataView(Dt);

            dv.Sort = "Date";
            while (fxRate == decimal.Zero)
            {
                int rowIndex = dv.Find(date.AddDays(-d).Date);
                if (rowIndex > 0)
                {
                    fxRate = (decimal)dv[rowIndex][currency];
                }
                else
                {
                    d++;
                }
            }
            IBankResult result = new BankResult()
            {
                BankName     = bankName,
                HomeCurrency = homeCurrency,
                ExchangeRate = decimal.Round(1 / fxRate, 4),
                RateDate     = date.AddDays(-d)
            };

            return(Task.FromResult(result));
        }
예제 #7
0
        public BankResult Test(string currency)
        {
            BankResult       bResult         = new BankResult();
            IForeignExchange foreignExchange = Terrasoft.Core.Factories.ClassFactory.Get <IForeignExchange>();

            Interfaces.IBankResult result = foreignExchange.GetRate(currency, DateTime.Now);

            bResult.BankName     = result.BankName;
            bResult.ExchangeRate = result.ExchangeRate;
            bResult.HomeCurrency = result.HomeCurrency;
            bResult.RateDate     = result.RateDate;

            return(bResult);
        }
예제 #8
0
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            if (!SupportedCurrencies.ContainsKey(currency))
            {
                throw new NotImplementedException($"{bankName} does not support {currency}");
            }

            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            BasicHttpBinding binding         = new BasicHttpBinding();
            EndpointAddress  endPointAddress = new EndpointAddress("http://www.cbr.ru/DailyInfoWebServ/DailyInfo.asmx");
            DailyInfoSoap    client          = new DailyInfoSoapClient(binding, endPointAddress);

            //ArrayOfXElement fxRates = await client.GetCursOnDateAsync(date);
            Task <DataSet> fxRates = client.GetCursOnDateAsync(date);

            fxRates.Wait();

            //var list = fxRates.Nodes.Find(n => n.Name.LocalName == "diffgram");

            DataTable table = fxRates.Result.Tables["ValuteCursOnDate"];


            string filterExpression = $"VchCode = '{currency}'";

            if (table == null || table?.Rows.Count == 0)
            {
                return(bankResult);
            }
            DataRow[] rows = table.Select(filterExpression);

            decimal.TryParse(rows[0]["Vnom"].ToString(), out decimal multiplier);
            decimal.TryParse(rows[0]["Vcurs"].ToString(), out decimal rate);
            decimal fxRate = rate / multiplier;

            bankResult.ExchangeRate = fxRate;

            return(bankResult);
        }
예제 #9
0
        public async Task <IBankResult> GetRateAsync(string currency, DateTime date)
        {
            if (!SupportedCurrencies.ContainsKey(currency))
            {
                throw new NotImplementedException($"{bankName} does not support {currency}");
            }

            IBankResult bankResult = new BankResult()
            {
                ExchangeRate = -1m,
                RateDate     = date,
                HomeCurrency = homeCurrency,
                BankName     = bankName
            };

            if (date < earliestDate)
            {
                return(bankResult);
            }

            //TD=11&TM=May&TY=2020&into=GBP&rateview=D

            string D = date.ToString("dd", CultureInfo.InvariantCulture);
            string M = date.ToString("MMM", CultureInfo.InvariantCulture);
            string Y = date.ToString("yyyy", CultureInfo.InvariantCulture);


            Uri methodUri = new Uri($"{baseUrl}TD={D}&TM={M}&TY={Y}&into=GBP&rateview=D");

            using (WebClient client = new WebClient())
            {
                try
                {
                    string       htmlContent = client.DownloadString(methodUri);
                    HtmlDocument doc         = new HtmlDocument();
                    doc.LoadHtml(htmlContent);


                    var error = doc.GetElementbyId("editorial").ChildNodes.Where(x =>
                                                                                 x.Name == "p" &&
                                                                                 x.Attributes.Where(a => a.Value == "error").Count() > 0
                                                                                 );


                    if (error.Count() != 0)
                    {
                        return(await GetRateAsync(currency, date.AddDays(-1)));
                    }


                    var header = doc.GetElementbyId("editorial").ChildNodes
                                 .Where(x => x.Name == "table").FirstOrDefault().ChildNodes
                                 .Where(x => x.Name == "thead").FirstOrDefault().ChildNodes
                                 .Where(x => x.Name == "tr").FirstOrDefault().ChildNodes
                                 .Where(x => x.Name == "th");

                    List <string> caption = new List <string>();
                    foreach (var item in header)
                    {
                        if (item.ChildNodes.Count == 1)
                        {
                            caption.Add(item.ChildNodes.FirstOrDefault().InnerText);
                        }

                        if (item.ChildNodes.Count == 3)
                        {
                            string val = item.ChildNodes.Where(
                                x => x.Name == "#text" && !x.InnerText.Contains(";") && !x.InnerText.Contains("/")
                                ).FirstOrDefault().InnerText.Trim();
                            caption.Add(val);
                        }
                    }

                    var rows = doc.GetElementbyId("editorial").ChildNodes
                               .Where(x => x.Name == "table").FirstOrDefault().ChildNodes
                               .Where(x => x.Name == "tr");

                    foreach (var row in rows)
                    {
                        object[] r = new object[caption.Count];
                        int      i = 0;
                        foreach (var cell in row.ChildNodes.Where(x => x.Name == "td"))
                        {
                            string cellValue = cell.InnerText.Trim();
                            if (SupportedCurrencies.Where(v => v.Value == cellValue).Count() == 1)
                            {
                                string key = SupportedCurrencies.Where(v => v.Value == cellValue).FirstOrDefault().Key;
                                r[i] = key;
                            }

                            if (decimal.TryParse(cell.InnerText, out decimal rate))
                            {
                                r[i] = rate;
                            }
                            i++;
                        }

                        if (r[0]?.ToString() == currency)
                        {
                            bankResult.ExchangeRate = (decimal)r[1];
                            if (DateTime.TryParseExact(caption[1].Trim(), "dd MMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime rateDate))
                            {
                                bankResult.RateDate = rateDate;
                            }
                            return(bankResult);
                        }
                    }

                    return(bankResult);
                }
                catch
                {
                    return(bankResult);
                }
            }
        }