Example #1
0
        public void testDerived()
        {
            Currency EUR = new EURCurrency(), USD = new USDCurrency(), GBP = new GBPCurrency();

             ExchangeRate eur_usd = new ExchangeRate(EUR, USD, 1.2042);
             ExchangeRate eur_gbp = new ExchangeRate(EUR, GBP, 0.6612);

             ExchangeRate derived = ExchangeRate.chain(eur_usd, eur_gbp);

             Money m1 = 50000.0 * GBP;
             Money m2 = 100000.0 * USD;

             Money.conversionType = Money.ConversionType.NoConversion;

             Money calculated = derived.exchange(m1);
             Money expected = new Money(m1.value*eur_usd.rate/eur_gbp.rate, USD);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             calculated = derived.exchange(m2);
             expected = new Money(m2.value*eur_gbp.rate/eur_usd.rate, GBP);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }
        }
Example #2
0
        public void testBaseCurrency()
        {
            Currency EUR = new EURCurrency(), GBP = new GBPCurrency(), USD = new USDCurrency();

            Money m1 = 50000.0 * GBP;
            Money m2 = 100000.0 * EUR;
            Money m3 = 500000.0 * USD;

            ExchangeRateManager.Instance.clear();
            ExchangeRate eur_usd = new ExchangeRate(EUR, USD, 1.2042);
            ExchangeRate eur_gbp = new ExchangeRate(EUR, GBP, 0.6612);
            ExchangeRateManager.Instance.Add(eur_usd);
            ExchangeRateManager.Instance.Add(eur_gbp);

            Money.conversionType = Money.ConversionType.BaseCurrencyConversion;
            Money.BaseCurrency = EUR;

            Money calculated = m1 * 3.0 + 2.5 * m2 - m3 / 5.0;

            Rounding round = Money.BaseCurrency.rounding;
            double x = round.Round(m1.value * 3.0 / eur_gbp.rate) + 2.5 * m2.value
                    - round.Round(m3.value / (5.0 * eur_usd.rate));
            Money expected = new Money(x, EUR);

            Money.conversionType = Money.ConversionType.NoConversion;

            if (calculated != expected)
            {
                Assert.Fail("Wrong result: expected: " + expected + "calculated: " + calculated);
            }
        }
Example #3
0
        public void testDirect()
        {
            Currency EUR = new EURCurrency(), USD = new USDCurrency();

             ExchangeRate eur_usd = new ExchangeRate(EUR, USD, 1.2042);

             Money m1 = 50000.0 * EUR;
             Money m2 = 100000.0 * USD;

             Money.conversionType = Money.ConversionType.NoConversion;

             Money calculated = eur_usd.exchange(m1);
             Money expected = new Money(m1.value*eur_usd.rate, USD);

             if (!Utils.close(calculated, expected))
             {
               Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             calculated = eur_usd.exchange(m2);
             expected = new Money(m2.value/eur_usd.rate, EUR);

             if (!Utils.close(calculated, expected))
             {
               Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }
        }
 public Guid AddExchangeRate(AddExchangeRateCommand command)
 {
   var exchangeRate = new ExchangeRate()
   {
     ExchangeRateId = Guid.NewGuid(),
     Price = command.Price,
     Name = command.Name
   };
   _exchangeRateService.Insert(exchangeRate);
   _unitOfWork.SaveChanges();
   return exchangeRate.ExchangeRateId;
 }
        public override string GetStepParameters()
        {
            var parameters = new List <string>();

            parameters.Add(Name != null ? Name.ToStepValue() : "$");
            parameters.Add(Description != null ? Description.ToStepValue() : "$");
            parameters.Add(RelatingMonetaryUnit != null ? RelatingMonetaryUnit.ToStepValue() : "$");
            parameters.Add(RelatedMonetaryUnit != null ? RelatedMonetaryUnit.ToStepValue() : "$");
            parameters.Add(ExchangeRate != null ? ExchangeRate.ToStepValue() : "$");
            parameters.Add(RateDateTime != null ? RateDateTime.ToStepValue() : "$");
            parameters.Add(RateSource != null ? RateSource.ToStepValue() : "$");

            return(string.Join(", ", parameters.ToArray()));
        }
Example #6
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ExchangeRate exchangeRate = db.ExchangeRates.Find(id);

            if (exchangeRate == null)
            {
                return(HttpNotFound());
            }
            return(View(exchangeRate));
        }
Example #7
0
        /// <summary>
        /// Serves as a hash function for a Currency.
        /// GetHashCode is suitable for use in hashing algorithms and data
        /// structures like a hash table.
        /// </summary>
        /// <returns>A hash code for the current Currency.</returns>
        public override int GetHashCode()
        {
            int hash = (RegionInfo.ISOCurrencySymbol.GetHashCode() ^
                        ExchangeRate.GetHashCode() ^
                        IsDefault.GetHashCode() ^
                        IsActive.GetHashCode());

            foreach (Denomination denom in Denominations)
            {
                hash ^= denom.GetHashCode();
            }

            return(hash);
        }
Example #8
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ExchangeRateService.
            ExchangeRateService exchangeRateService =
                (ExchangeRateService)user.GetService(DfpService.v201702.ExchangeRateService);

            // Set the ID of the exchange rate.
            long exchangeRateId = long.Parse(_T("INSERT_EXCHANGE_RATE_ID_HERE"));

            // Create a statement to get the exchange rate.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :exchangeRateId and refreshRate = :refreshRate")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("exchangeRateId", exchangeRateId)
                                                .AddValue("refreshRate", ExchangeRateRefreshRate.FIXED.ToString());

            try {
                // Get exchange rates by statement.
                ExchangeRatePage page = exchangeRateService
                                        .getExchangeRatesByStatement(statementBuilder.ToStatement());

                ExchangeRate exchangeRate = page.results[0];

                // Update the exchange rate value to 1.5.
                exchangeRate.exchangeRate = 15000000000L;

                // Update the exchange rate on the server.
                ExchangeRate[] exchangeRates = exchangeRateService
                                               .updateExchangeRates(new ExchangeRate[] { exchangeRate });

                if (exchangeRates != null)
                {
                    foreach (ExchangeRate updatedExchangeRate in exchangeRates)
                    {
                        Console.WriteLine("An exchange rate with ID '{0}', currency code '{1}', " +
                                          "direction '{2}' and exchange rate '{3}' was updated.", exchangeRate.id,
                                          exchangeRate.currencyCode, exchangeRate.direction,
                                          (exchangeRate.exchangeRate / 10000000000f));
                    }
                }
                else
                {
                    Console.WriteLine("No exchange rates updated.");
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to update exchange rates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        // GET: ExchangeRates/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ExchangeRate exchangeRate = ExchangeRateRepository.Find(id.Value);

            if (exchangeRate == null)
            {
                return(HttpNotFound());
            }
            return(View(exchangeRate));
        }
Example #10
0
        public ConversionTests()
        {
            gbp = new Currency(1, "GBP", "\u00A3");
            usd = new Currency(2, "USD", "\u0024");
            aud = new Currency(3, "AUD", "A\u0024");
            eur = new Currency(4, "EUR", "\u20AC");
            ExchangeRate gbpToUsd = new ExchangeRate(usd, 1.24697m);
            ExchangeRate gbpToAud = new ExchangeRate(aud, 1.83744m);
            ExchangeRate gbpToEur = new ExchangeRate(eur, 1.12344m);

            gbp.ExchangeRates.Add(gbpToUsd);
            gbp.ExchangeRates.Add(gbpToAud);
            gbp.ExchangeRates.Add(gbpToEur);
        }
Example #11
0
        public ExchangeRate get_ExchangeRate(Session session, string ExchangeRateId, short RowStatus)
        {
            ExchangeRate exchangeRateID = session.FindObject <ExchangeRate>(
                CriteriaOperator.And(
                    new BinaryOperator("ExchangeRateId", ExchangeRateId, BinaryOperatorType.Equal),
                    new BinaryOperator("RowStatus", RowStatus, BinaryOperatorType.Equal)
                    ));

            if (exchangeRateID == null)
            {
                throw new Exception("ExchangeRate is not exist system");
            }
            return(exchangeRateID);
        }
Example #12
0
        public ActionResult DeleteConfirmed(int id)
        {
            ExchangeRate exchangeRate = ExchangeRateRepository.Find(id);
            bool         ok           = ExchangeRateRepository.Delete(id);

            if (ok)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(RedirectToAction("Delete", id));
            }
        }
Example #13
0
 private void _baseCurrencyCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     _subCurrencyCombobox.Visibility = Visibility.Visible;
     _subCurrencyCombobox.Items.Clear();
     foreach (var currency in ExchangeRate.GetCurrencies())
     {
         if (currency.ToString() != _baseCurrencyCombobox.SelectedItem.ToString())
         {
             _subCurrencyCombobox.Items.Add(currency);
         }
     }
     _subCurrencyCombobox1.Items.Clear();
     _confirmButton.Visibility = Visibility.Hidden;
 }
        public void WhenCurrencyPairInNlCulture_ThenParsingShouldSucceed()
        {
            var fx1 = ExchangeRate.Parse("EUR/USD 1,2591");

            fx1.BaseCurrency.Code.Should().Be("EUR");
            fx1.QuoteCurrency.Code.Should().Be("USD");
            fx1.Value.Should().Be(1.2591M);

            var fx2 = ExchangeRate.Parse("EUR/USD1,2591");

            fx2.BaseCurrency.Code.Should().Be("EUR");
            fx2.QuoteCurrency.Code.Should().Be("USD");
            fx2.Value.Should().Be(1.2591M);
        }
Example #15
0
        private ExchangeRate GetRegularExchangeRate(Asset baseAsset, Asset quoteAsset)
        {
            ExchangeRate baseToDollarRate = _dollarApi.GetUsdRate(baseAsset);

            ExchangeRate quoteToDollarRate = _dollarApi.GetUsdRate(quoteAsset);

            return(new ExchangeRate
            {
                AssetBase = baseToDollarRate.AssetBase,
                AssetQuote = quoteToDollarRate.AssetBase,
                Rate = baseToDollarRate.Rate / quoteToDollarRate.Rate,
                Time = DateTime.Now
            });
        }
Example #16
0
 public void AddRate(ExchangeRate exchangeRate, bool createReverse = false)
 {
     _context.ExchangeRates.Add(exchangeRate);
     if (createReverse)
     {
         _context.ExchangeRates.Add(new ExchangeRate()
         {
             ExchangeRateId = Guid.NewGuid(),
             FromCurrencyId = exchangeRate.ToCurrencyId,
             ToCurrencyId   = exchangeRate.FromCurrencyId,
             Ratio          = Math.Round(1 / exchangeRate.Ratio, 4),
         });
     }
 }
        public static void UpdatePinnedRates(ExchangeRate rate)
        {
            var list = GetPinnedRates();

            if (rate.Pinned && !list.Contains(rate.Currency))
            {
                list.Add(rate.Currency);
            }
            if (!rate.Pinned && list.Contains(rate.Currency))
            {
                list.Remove(rate.Currency);
            }
            Save("pinned", JsonConvert.SerializeObject(list));
        }
Example #18
0
        public void ExchangeRateUpdateTestUsingoAuth(ServiceContext qboContextoAuth)
        {
            QueryService <ExchangeRate> entityQuery = new QueryService <ExchangeRate>(qboContextoAuth);
            List <ExchangeRate>         foundall    = entityQuery.ExecuteIdsQuery("SELECT * FROM ExchangeRate where SourceCurrencyCode in ('INR') and AsOfDate='2015-07-07'").ToList <ExchangeRate>();



            foreach (ExchangeRate found in foundall)
            {
                ExchangeRate changed = QBOHelper.UpdateExchangeRate(qboContextoAuth, found);
                //Update the returned entity data
                ExchangeRate updated = Helper.Update <ExchangeRate>(qboContextoAuth, changed);//Verify the updated ExchangeRate
            }
        }
Example #19
0
        public static async Task <long> SaveAsync(string tenant, int officeId, string baseCurrency,
                                                  List <ExchangeRateViewModel> exchangeRates)
        {
            long exchangeRateId = 0;

            using (var db = DbProvider.Get(FrapidDbServer.GetConnectionString(tenant), tenant).GetDatabase())
            {
                db.BeginTransaction();

                try
                {
                    var sql = new Sql("UPDATE finance.exchange_rates SET status = @0 WHERE office_id=@1", false, officeId);
                    await db.ExecuteAsync(sql);

                    var exchangeRate = new ExchangeRate
                    {
                        OfficeId  = officeId,
                        Status    = true,
                        UpdatedOn = DateTimeOffset.UtcNow
                    };

                    var awaiter =
                        await db.InsertAsync("finance.exchange_rates", "exchange_rate_id", true, exchangeRate).ConfigureAwait(false);

                    exchangeRateId = awaiter.To <long>();

                    foreach (var item in exchangeRates)
                    {
                        var detail = new ExchangeRateDetail
                        {
                            ExchangeRateId      = exchangeRateId,
                            LocalCurrencyCode   = baseCurrency,
                            ForeignCurrencyCode = item.CurrencyCode,
                            ExchangeRate        = item.Rate,
                            Unit = 1
                        };

                        await db.InsertAsync("finance.exchange_rate_details", "exchange_rate_detail_id", true, detail);
                    }

                    db.CompleteTransaction();
                }
                catch (Exception)
                {
                    db.AbortTransaction();
                }

                return(exchangeRateId);
            }
        }
Example #20
0
        private void _confirmButton_Click(object sender, RoutedEventArgs e)
        {
            ExchangeRate.Currency BaseCurrency = ExchangeRate.StrToCurrency(_baseCurrencyCombobox.SelectedItem.ToString());
            var CurrencyList = new List <ExchangeRate.Currency>
            {
                ExchangeRate.StrToCurrency(_subCurrencyCombobox.SelectedItem.ToString()),
                ExchangeRate.StrToCurrency(_subCurrencyCombobox1.SelectedItem.ToString())
            };

            //Creates a new Page without distorting window resolution or creating a new window
            App.ElementHandles.ExchangeRateInputHWND = new ExchangeRateInput(BaseCurrency, CurrencyList);
            CurrencySelectMainGrid.Children.Clear();
            CurrencySelectMainGrid.Children.Add(App.ElementHandles.ExchangeRateInputHWND);
        }
        private ExchangeRate[] FillTimeSeriesGaps(ICollection <ExchangeRate> collection, DateTime startTime, DateTime endTime)
        {
            if (!collection.Any())
            {
                return(Array.Empty <ExchangeRate>());
            }

            var daysRange = Enumerable.Range(0, (endTime - startTime).Days + 1)
                            .Select(day => startTime.AddDays(day))
                            .Where(day => day.Date >= collection.Min(col => col.Date))
                            .GroupJoin(collection,
                                       day => day,
                                       coll => coll.Date,
                                       (day, coll) => (day, ExchangeRate: coll.FirstOrDefault()))
                            .ToArray();

            if (!daysRange.Any())
            {
                return(Array.Empty <ExchangeRate>());
            }

            var result = new List <ExchangeRate>();

            var lastDefinedValue = daysRange.First().ExchangeRate;

            foreach (var day in daysRange)
            {
                ExchangeRate itemToAdd;
                if (day.ExchangeRate == null)
                {
                    itemToAdd = new ExchangeRate
                    {
                        Date   = day.day,
                        Source = lastDefinedValue.Source,
                        Target = lastDefinedValue.Target,
                        Value  = lastDefinedValue.Value
                    };
                }
                else
                {
                    itemToAdd = day.ExchangeRate;
                }

                lastDefinedValue = itemToAdd;
                result.Add(itemToAdd);
            }

            return(result.ToArray());
        }
Example #22
0
        private Singleton()
        {
            ExchangeRates = new List <ExchangeRate>();
            ExchangeRate newExchangeRate = new ExchangeRate
            {
                Id   = 1,
                Date = Convert.ToDateTime("2020-08-01"),
                GTQ  = 1,
                USD  = 7.9
            };

            ExchangeRates.Add(newExchangeRate);

            newExchangeRate = new ExchangeRate
            {
                Id   = 2,
                Date = Convert.ToDateTime("2020-08-02"),
                GTQ  = 1,
                USD  = 7.88
            };
            ExchangeRates.Add(newExchangeRate);

            newExchangeRate = new ExchangeRate
            {
                Id   = 3,
                Date = Convert.ToDateTime("2020-08-03"),
                GTQ  = 1,
                USD  = 7.86
            };
            ExchangeRates.Add(newExchangeRate);

            newExchangeRate = new ExchangeRate
            {
                Id   = 4,
                Date = Convert.ToDateTime("2020-08-04"),
                GTQ  = 1,
                USD  = 7.92
            };
            ExchangeRates.Add(newExchangeRate);

            newExchangeRate = new ExchangeRate
            {
                Id   = 5,
                Date = Convert.ToDateTime("2020-08-05"),
                GTQ  = 1,
                USD  = 7.87
            };
            ExchangeRates.Add(newExchangeRate);
        }
Example #23
0
        private void SetExchangeRate()
        {
            _exchangeRate = null;
            if (ServicesProvider.GetInstance().GetCurrencyServices().FindAllCurrencies().Count == 1)
            {
                _exchangeRate = new ExchangeRate
                {
                    Currency = _FundingLine.Currency,
                    Date     = dateTimePickerEvent.Value,
                    Rate     = 1
                };
            }
            buttonSave.Enabled = false;

            DateTime _date = dateTimePickerEvent.Value;

            try
            {
                if (!ServicesProvider.GetInstance().GetExchangeRateServices().RateExistsForEachCurrency
                        (ServicesProvider.GetInstance().GetCurrencyServices().FindAllCurrencies(), _date.Date)
                    /*&& (User.CurrentUser.HasAdminRole || User.CurrentUser.HasSuperAdminRole)*/)
                {
                    buttonAddRate.Enabled = true;
                    var _xrForm =
                        new ExchangeRateForm(new DateTime(dateTimePickerEvent.Value.Year, _date.Month, _date.Day),
                                             _FundingLine.Currency);
                    _xrForm.ShowDialog();
                }
                _exchangeRate = ServicesProvider.GetInstance().GetAccountingServices().FindExchangeRate(_date.Date, _FundingLine.Currency);
            }
            catch (Exception ex)
            {
                new frmShowError(CustomExceptionHandler.ShowExceptionText(ex)).ShowDialog();
            }
            finally
            {
                if (_exchangeRate != null)
                {
                    buttonSave.Enabled    = true;
                    buttonAddRate.Visible = false;
                }
                else
                {
                    buttonSave.Enabled = false;
                    //buttonAddRate.Enabled = User.CurrentUser.isAdmin || User.CurrentUser.isSuperAdmin;
                    buttonAddRate.Enabled = true;
                }
            }
        }
Example #24
0
        public void PerformCalls(Object source, ElapsedEventArgs e)
        {
            try
            {
                _request = new HttpRequestMessage()
                {
                    RequestUri = new Uri("http://www.banguat.gob.gt/variables/ws/TipoCambio.asmx"),
                    Method     = HttpMethod.Post
                };

                _request.Headers.Add("SOAPAction", "http://www.banguat.gob.gt/variables/ws/TipoCambioDia");
                _request.Content = new StringContent(_xmlDocument, Encoding.UTF8, "text/xml");
                _request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");

                var response = _httpClient.SendAsync(_request).Result;

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var responseObject = Helpers.GetDeserializedResponse(response).Result;
                    var dataSourceItem = responseObject.TipoCambioDiaResult.CambioDolar.FirstOrDefault();

                    if (dataSourceItem != null)
                    {
                        var exchangeRate = new ExchangeRate()
                        {
                            Date         = DateTime.Parse(dataSourceItem.Fecha),
                            Rate         = dataSourceItem.Referencia,
                            WhenObtained = DateTime.UtcNow
                        };

                        var requestPayload = JsonConvert.SerializeObject(exchangeRate);

                        _apiRequest = new HttpRequestMessage()
                        {
                            RequestUri = new Uri(WebAPIUrl),
                            Method     = HttpMethod.Post
                        };
                        _apiRequest.Content = new StringContent(requestPayload);
                        _apiRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                        var apiResponse = _apiHttpClient.SendAsync(_apiRequest).Result;
                    }
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
Example #25
0
        private async Task SaveCurrenciesInDb(ExchangeRate exchangeRate)
        {
            if (exchangeRate.Success)
            {
                var currencies = AddOrUpdateCurrency(exchangeRate);

                await _applicationContext.AddAsync(new CurrentExchangeRateRequest()
                {
                    Date       = DateTime.UtcNow,
                    Currencies = currencies
                });

                await _applicationContext.SaveChangesAsync();
            }
        }
Example #26
0
        public ExchangeRatesCacheTests()
        {
            _configuration          = new Mock <IHaveConfigurations>();
            _exchangeRatesRetriever = new Mock <IRetrieveExchangeRates>();
            _cache = new ExchangeRatesCache(_configuration.Object, _exchangeRatesRetriever.Object);

            _eurExchangeRate = new ExchangeRate(
                new Dictionary <Currency, decimal>
            {
                { Currency.EUR, 1m },
                { Currency.GBP, TargetEurGbpRate },
                { Currency.USD, TargetEurUsdRate }
            },
                _updatedAt);
        }
Example #27
0
        public async Task <long> TinybarsFromGas(double agu)
        {
            // agu = Arbitrary Gas Unit - we really have no idea, some 'relative' unit of work.
            // agc = Arbitrary Gas Constant - Well, we know this is not linear with the exchange rate so we have to keep changing it.
            // Change the agc when the gas price goes up/down whatever.
            long agc = 200;

            if (_exchangeRate == null)
            {
                await using var client = NewClient();
                _exchangeRate          = (await client.GetExchangeRatesAsync()).Current;
            }
            // This is not necessarily correct, but hopefully stable.
            return(((long)(agu * agc * _exchangeRate.HBarEquivalent)) / (_exchangeRate.USDCentEquivalent));
        }
Example #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteExchangeRate(Guid id)
        {
            bool isDeleted = false;

            using (var context = new SCMSEntities())
            {
                ExchangeRate exchangeRate = context.ExchangeRates.Single(c => c.Id.Equals(id));
                context.ExchangeRates.Remove(exchangeRate);
                if (context.SaveChanges() > 0)
                {
                    isDeleted = true;
                }
            }
            return(isDeleted);
        }
        public void GetExchangedValueReturnsANumberRoundedBy8()
        {
            var er        = new ExchangeRate(5999999M, "R$/BTC", DateTime.Now, CultureInfo.InvariantCulture);
            var valueFiat = 15M;

            var result = er.ExchangeValueTo(valueFiat);

            var numberOfDecimals = result.ToString(CultureInfo.InvariantCulture).Split('.').Last().Length;

            Assert.Equal(numberOfDecimals, Constants.BitcoinDecimals);

            var roundValue = Math.Round(valueFiat / er.Rate, Constants.BitcoinDecimals, MidpointRounding.AwayFromZero);

            Assert.Equal(result, roundValue);
        }
Example #30
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            ExchangeRate = await _context.ExchangeRate.FirstOrDefaultAsync(m => m.ExchangeRateId == id);

            if (ExchangeRate == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Example #31
0
        public void Should_Get_A_List_Of_Exchange_Rates_For_Type_In_A_Date()
        {
            FixedList <ExchangeRateType> exchangeRateTypes = ExchangeRateType.GetList();

            var      EXCHANGE_RATE_TYPE = exchangeRateTypes[0];
            DateTime DATE = new DateTime(2017, 08, 31);

            FixedList <ExchangeRate> list = ExchangeRate.GetList(EXCHANGE_RATE_TYPE, DATE);

            Assert.NotEmpty(list);

            Assert.All(list, x => { Assert.Equal(DATE, x.Date); });
            Assert.All(list, x => { Assert.Equal(EXCHANGE_RATE_TYPE, x.ExchangeRateType); });
            Assert.All(list, x => { Assert.True(x.Value > 0); });
        }
        // GET: ExchangeRates/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ExchangeRate exchangeRate = ExchangeRateRepository.Find(id.Value);

            if (exchangeRate == null)
            {
                return(HttpNotFound());
            }
            //ViewBag.Currency_ID = new SelectList(db.Currency, "ID", "Name", exchangeRate.Currency_ID);
            return(View(exchangeRate));
        }
        public void AddExchangeRate()
        {
            ExchangeRate exchangeRate = new ExchangeRate()
            {
                CurrencyId       = 2,
                RateForSale      = 75,
                RateForPurchaise = 76,
                RateDate         = DateTime.Now
            };

            exchangeRateService.AddExchangeRate(exchangeRate);
            bool rateIsExist = exchangeRateService.IsExist(exchangeRate.Id);

            Assert.True(rateIsExist);
        }
Example #34
0
 public override int GetHashCode()
 {
     return
         (BaseCurrencyAmount.GetHashCode()
          ^ UnixTimeStamp.GetHashCode()
          ^ CounterCurrencyAmount.GetHashCode()
          ^ ExchangeRate.GetHashCode()
          ^ OrderId.GetHashCode()
          ^ Pair.GetHashCode()
          ^ SourceExchange.GetHashCode()
          ^ TradeFee.GetHashCode()
          ^ TradeFeeCurrency.GetHashCode()
          ^ TransactionType.GetHashCode()
          ^ TransactionId.GetHashCode());
 }
Example #35
0
        public ExchangeRate CalculateCrossRate(ExchangeRate rate1, ExchangeRate rate2, DateTime timestampUtc)
        {
            Argument.NotNull(rate1, "rate1");
            Argument.NotNull(rate2, "rate2");

            if (rate1.Base.ISOName != rate2.Base.ISOName)
            {
                throw new ArgumentException("Can't calculate cross rate for rates with different base currencies.");
            }
            if (rate1.Foreign.ISOName == rate2.Foreign.ISOName)
            {
                throw new ArgumentException("Can't calculate cross rate for rates with same foreign currencies.");
            }
            var buyRate = rate2.BuyRate / rate1.SellRate;
            var sellRate = rate2.SellRate / rate1.BuyRate;

            return ExchangeRate.Create(rate1.Foreign, rate2.Foreign, buyRate, sellRate, timestampUtc);
        }
Example #36
0
        public ActionResult Create(ExchangeRate item)
        {
            if (!ModelState.IsValid)
                return PartialView ("_Create", item);

            var qry = from x in ExchangeRate.Queryable
                  where x.Date == item.Date.Date &&
                        x.Base == item.Base &&
                        x.Target == item.Target
                  select x;

            if (qry.Count () > 0) {
                ModelState.AddModelError ("Date", Resources.ExchangeRateAlreadyExists);
                return PartialView ("_Create", item);
            }

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
Example #37
0
        public ArbAgent(ExchangeLink sell, ExchangeLink buy, System.ComponentModel.ISynchronizeInvoke s)
        {
            _sellLink = sell;
            _buyLink = buy;

            _timer = new System.Timers.Timer();
            _timer.Interval = 10000;
            _timer.SynchronizingObject = s;
            _timer.Elapsed += new ElapsedEventHandler(DoUpdate);
            _timer.Enabled = false;

            _updateInProgress = false;

            _exchangeRate = new ExchangeRate();

            _sellBalanceUpdater = new BalanceUpdater(_sellLink, Currency.XBT, UpdateSellBalance, 60000);
            _buyBalanceUpdater = new BalanceUpdater(_buyLink, Currency.USD, UpdateBuyBalance, 60000);

            _sellFeeUpdater = new FeeUpdater(_sellLink, UpdateSellFee, 1000 * 3600 * 4);
            _buyFeeUpdater = new FeeUpdater(_buyLink, UpdateBuyFee, 1000 * 3600 * 4);

            _exchangeRateUpdater = new ExchangeRateUpdater(_buyLink, UpdateExchangeRate, 1000 * 3600 * 6);
        }
    /// <summary>
    /// Run the code examples.
    /// </summary>
    /// <param name="user">The DFP user object running the code examples.</param>
    public override void Run(DfpUser user) {
      // Get the ExchangeRateService.
      ExchangeRateService exchangeRateService =
          (ExchangeRateService) user.GetService(DfpService.v201508.ExchangeRateService);

      // Create an exchange rate.
      ExchangeRate exchangeRate = new ExchangeRate();

      // Set the currency code.
      exchangeRate.currencyCode = "AUD";

      // Set the direction of the conversion (from the network currency).
      exchangeRate.direction = ExchangeRateDirection.FROM_NETWORK;

      // Set the conversion value as 1.5 (this value is multiplied by 10,000,000,000)
      exchangeRate.exchangeRate = 15000000000L;

      // Do not refresh exchange rate from Google data. Update manually only.
      exchangeRate.refreshRate = ExchangeRateRefreshRate.FIXED;

      try {
        // Create the exchange rate on the server.
        ExchangeRate[] exchangeRates = exchangeRateService.createExchangeRates(
            new ExchangeRate[] {exchangeRate});

        foreach (ExchangeRate createdExchangeRate in exchangeRates) {
          Console.WriteLine("An exchange rate with ID '{0}', currency code '{1}', " +
              "direction '{2}' and exchange rate '{3}' was created.", exchangeRate.id,
              exchangeRate.currencyCode, exchangeRate.direction,
              (exchangeRate.exchangeRate / 10000000000f));
        }

      } catch (Exception e) {
        Console.WriteLine("Failed to create exchange rates. Exception says \"{0}\"",
            e.Message);
      }
    }
Example #39
0
 internal CurrencyConverter(ExchangeRate exchangeRate)
 {
     Argument.NotNull(exchangeRate, "rate");
     _exchangeRate = exchangeRate;
 }
Example #40
0
 public void add(ExchangeRate arg0, Date startDate, Date endDate) {
   NQuantLibcPINVOKE.ExchangeRateManager_add__SWIG_0(swigCPtr, ExchangeRate.getCPtr(arg0), Date.getCPtr(startDate), Date.getCPtr(endDate));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Example #41
0
        public void testSmartLookup()
        {
            Currency EUR = new EURCurrency(), USD = new USDCurrency(), GBP = new GBPCurrency(),
                  CHF = new CHFCurrency(), SEK = new SEKCurrency(), JPY = new JPYCurrency();

             ExchangeRateManager rateManager = ExchangeRateManager.Instance;
             rateManager.clear();

             ExchangeRate eur_usd1 = new ExchangeRate(EUR, USD, 1.1983);
             ExchangeRate eur_usd2 = new ExchangeRate(USD, EUR, 1.0/1.2042);
             rateManager.Add(eur_usd1, new Date(4,Month.August,2004));
             rateManager.Add(eur_usd2, new Date(5,Month.August,2004));

             ExchangeRate eur_gbp1 = new ExchangeRate(GBP, EUR, 1.0 / 0.6596);
             ExchangeRate eur_gbp2 = new ExchangeRate(EUR, GBP, 0.6612);
             rateManager.Add(eur_gbp1, new Date(4,Month.August,2004));
             rateManager.Add(eur_gbp2, new Date(5,Month.August,2004));

             ExchangeRate usd_chf1 = new ExchangeRate(USD, CHF, 1.2847);
             ExchangeRate usd_chf2 = new ExchangeRate(CHF, USD, 1.0 / 1.2774);
             rateManager.Add(usd_chf1, new Date(4,Month.August,2004));
             rateManager.Add(usd_chf2, new Date(5,Month.August,2004));

             ExchangeRate chf_sek1 = new ExchangeRate(SEK, CHF, 0.1674);
             ExchangeRate chf_sek2 = new ExchangeRate(CHF, SEK, 1.0 / 0.1677);
             rateManager.Add(chf_sek1, new Date(4,Month.August,2004));
             rateManager.Add(chf_sek2, new Date(5,Month.August,2004));

             ExchangeRate jpy_sek1 = new ExchangeRate(SEK, JPY, 14.5450);
             ExchangeRate jpy_sek2 = new ExchangeRate(JPY, SEK, 1.0 / 14.6110);
             rateManager.Add(jpy_sek1, new Date(4,Month.August,2004));
             rateManager.Add(jpy_sek2, new Date(5,Month.August,2004));

             Money m1 = 100000.0 * USD;
             Money m2 = 100000.0 * EUR;
             Money m3 = 100000.0 * GBP;
             Money m4 = 100000.0 * CHF;
             Money m5 = 100000.0 * SEK;
             Money m6 = 100000.0 * JPY;

             Money.conversionType = Money.ConversionType.NoConversion;

             // two-rate chain

             ExchangeRate usd_sek = rateManager.lookup(USD, SEK, new Date(4,Month.August,2004));
             Money calculated = usd_sek.exchange(m1);
             Money expected = new Money(m1.value*usd_chf1.rate/chf_sek1.rate, SEK);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             usd_sek = rateManager.lookup(SEK, USD, new Date(5,Month.August,2004));
             calculated = usd_sek.exchange(m5);
             expected = new Money(m5.value*usd_chf2.rate/chf_sek2.rate, USD);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             // three-rate chain

             ExchangeRate eur_sek = rateManager.lookup(EUR, SEK,new Date(4,Month.August,2004));
             calculated = eur_sek.exchange(m2);
             expected = new Money(m2.value*eur_usd1.rate*usd_chf1.rate/chf_sek1.rate, SEK);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             eur_sek = rateManager.lookup(SEK, EUR, new Date(5,Month.August,2004));
             calculated = eur_sek.exchange(m5);
             expected = new Money(m5.value*eur_usd2.rate*usd_chf2.rate/chf_sek2.rate, EUR);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             // four-rate chain

             ExchangeRate eur_jpy = rateManager.lookup(EUR, JPY,new Date(4,Month.August,2004));
             calculated = eur_jpy.exchange(m2);
             expected = new Money(m2.value*eur_usd1.rate*usd_chf1.rate*jpy_sek1.rate/chf_sek1.rate, JPY);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             eur_jpy = rateManager.lookup(JPY, EUR, new Date(5,Month.August,2004));
             calculated = eur_jpy.exchange(m6);
             expected = new Money(m6.value*jpy_sek2.rate*eur_usd2.rate*usd_chf2.rate/chf_sek2.rate, EUR);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             // five-rate chain

             ExchangeRate gbp_jpy = rateManager.lookup(GBP, JPY,new Date(4,Month.August,2004));
             calculated = gbp_jpy.exchange(m3);
             expected = new Money(m3.value*eur_gbp1.rate*eur_usd1.rate*usd_chf1.rate*jpy_sek1.rate/chf_sek1.rate, JPY);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             gbp_jpy = rateManager.lookup(JPY, GBP, new Date(5,Month.August,2004));
             calculated = gbp_jpy.exchange(m6);
             expected = new Money(m6.value*jpy_sek2.rate*eur_usd2.rate*usd_chf2.rate*eur_gbp2.rate/chf_sek2.rate, GBP);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }
        }
 public static Dictionary<Bro, decimal> CalculateInCurrency(ExchangeRate rate, IList<Transaction> transactions, IList<Bro> bros)
 {
     return CalculateInBaseCurrency(transactions, bros).ToDictionary(p => p.Key, p => p.Value * rate.Rate);
 }
 public TotalInCurrencyRest(IList<BroTotalInCurrencyRest> totals, ExchangeRate rate)
 {
     Totals = totals;
     Rate = new ExchangeRateRest(rate);
 }
Example #44
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ExchangeRate obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Example #45
0
 public ExchangeRate lookup(Currency source, Currency target, Date date) {
   ExchangeRate ret = new ExchangeRate(NQuantLibcPINVOKE.ExchangeRateManager_lookup__SWIG_1(swigCPtr, Currency.getCPtr(source), Currency.getCPtr(target), Date.getCPtr(date)), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Example #46
0
 public void add(ExchangeRate arg0) {
   NQuantLibcPINVOKE.ExchangeRateManager_add__SWIG_2(swigCPtr, ExchangeRate.getCPtr(arg0));
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
 }
Example #47
0
            public void WhenRateIsDecimal_ThenCreatingShouldSucceed()
            {
                var fx = new ExchangeRate(_euro, _dollar, 1.2591M);

                fx.BaseCurrency.Should().Be(_euro);
                fx.QuoteCurrency.Should().Be(_dollar);
                fx.Value.Should().Be(1.2591M);
            }
Example #48
0
        public void testDirectLookup()
        {
            ExchangeRateManager rateManager = ExchangeRateManager.Instance;
             rateManager.clear();

             Currency EUR = new EURCurrency(), USD = new USDCurrency();

             ExchangeRate eur_usd1 = new ExchangeRate(EUR, USD, 1.1983);
             ExchangeRate eur_usd2 = new ExchangeRate(USD, EUR, 1.0/1.2042);
             rateManager.Add(eur_usd1, new Date(4,Month.August,2004));
             rateManager.Add(eur_usd2, new Date(5,Month.August,2004));

             Money m1 = 50000.0 * EUR;
             Money m2 = 100000.0 * USD;

             Money.conversionType = Money.ConversionType.NoConversion;

             ExchangeRate eur_usd = rateManager.lookup(EUR, USD,new Date(4,Month.August,2004),ExchangeRate.Type.Direct);
             Money calculated = eur_usd.exchange(m1);
             Money expected = new Money(m1.value*eur_usd1.rate, USD);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             eur_usd = rateManager.lookup(EUR, USD,new Date(5,Month.August,2004),ExchangeRate.Type.Direct);
             calculated = eur_usd.exchange(m1);
             expected = new Money(m1.value/eur_usd2.rate, USD);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             ExchangeRate usd_eur = rateManager.lookup(USD, EUR,new Date(4,Month.August,2004),ExchangeRate.Type.Direct);

             calculated = usd_eur.exchange(m2);
             expected = new Money(m2.value/eur_usd1.rate, EUR);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             usd_eur = rateManager.lookup(USD, EUR,new Date(5,Month.August,2004),ExchangeRate.Type.Direct);

             calculated = usd_eur.exchange(m2);
             expected = new Money(m2.value*eur_usd2.rate, EUR);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }
        }
Example #49
0
            public void WhenRateIsDouble_ThenCreatingShouldSucceed()
            {
                var fx = new ExchangeRate(_euroAsString, _dollarAsString, 1.2591);

                fx.BaseCurrency.Should().Be(_euro);
                fx.QuoteCurrency.Should().Be(_dollar);
                // TODO: Can doubles be compared for equality? See https://github.com/dennisdoomen/fluentassertions/wiki
                fx.Value.Should().Be(1.2591M);
            }
Example #50
0
        public void testTriangulatedLookup()
        {
            ExchangeRateManager rateManager = ExchangeRateManager.Instance;
             rateManager.clear();

             Currency EUR = new EURCurrency(), USD = new USDCurrency(), ITL = new ITLCurrency();

             ExchangeRate eur_usd1 = new ExchangeRate(EUR, USD, 1.1983);
             ExchangeRate eur_usd2 = new ExchangeRate(EUR, USD, 1.2042);
             rateManager.Add(eur_usd1, new Date(4,Month.August,2004));
             rateManager.Add(eur_usd2, new Date(5,Month.August,2004));

             Money m1 = 50000000.0 * ITL;
             Money m2 = 100000.0 * USD;

             Money.conversionType = Money.ConversionType.NoConversion;

             ExchangeRate itl_usd = rateManager.lookup(ITL, USD,new Date(4,Month.August,2004));
             Money calculated = itl_usd.exchange(m1);
             Money expected = new Money(m1.value*eur_usd1.rate/1936.27, USD);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             itl_usd = rateManager.lookup(ITL, USD,new Date(5,Month.August,2004));
             calculated = itl_usd.exchange(m1);
             expected = new Money(m1.value*eur_usd2.rate/1936.27, USD);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             ExchangeRate usd_itl = rateManager.lookup(USD, ITL, new Date(4, Month.August, 2004));

             calculated = usd_itl.exchange(m2);
             expected = new Money(m2.value*1936.27/eur_usd1.rate, ITL);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }

             usd_itl = rateManager.lookup(USD, ITL, new Date(5, Month.August, 2004));

             calculated = usd_itl.exchange(m2);
             expected = new Money(m2.value*1936.27/eur_usd2.rate, ITL);

             if (!Utils.close(calculated, expected))
             {
            Assert.Fail("Wrong result: expected: " + expected + " calculated: " + calculated);
             }
        }
Example #51
0
            public void WhenRateIsFloat_ThenCreatingShouldSucceed()
            {
                var fx = new ExchangeRate(_euroAsString, _dollarAsString, 1.2591F);

                fx.BaseCurrency.Should().Be(_euro);
                fx.QuoteCurrency.Should().Be(_dollar);
                fx.Value.Should().Be(1.2591M);
            }
 public ExchangeRateRest(ExchangeRate rate)
 {
     Currency = rate.Currency.Id;
     Date = JsonDate.ToString(rate.Date);
     Rate = rate.Rate;
 }
Example #53
0
 public static ExchangeRate chain(ExchangeRate r1, ExchangeRate r2) {
   ExchangeRate ret = new ExchangeRate(NQuantLibcPINVOKE.ExchangeRate_chain(ExchangeRate.getCPtr(r1), ExchangeRate.getCPtr(r2)), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }