Example #1
0
        public async Task Convert_WithReciprocalConversion_ReturnsExpectedResult()
        {
            var converter = new CurrencyConverterService(this._apiRepository, this._logger);
            var Moneys    = new List <Money> {
                new Money(100, "CNY")
            };
            var targetCurrency = new Currency("GBP");
            var targetDate     = new DateTime(2018, 01, 01);
            var cnyRate        = new ExchangeRateDto
            {
                DateTime         = targetDate,
                FixedCurrency    = "GBP",
                VariableCurrency = "CNY",
                Name             = "Pound Sterling",
                Rate             = 10
            };

            var rates = new Dictionary <DateTime, IReadOnlyCollection <ExchangeRateDto> >
            {
                { targetDate, new[] { cnyRate } }
            };

            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate)).Returns(rates);

            var conversion = await converter.Convert(Moneys, targetCurrency, targetDate, this._ruleCtx);

            Assert.IsNotNull(conversion);
            Assert.AreEqual(conversion.Value.Value, 10);
            Assert.AreEqual(conversion.Value.Currency.Code, "GBP");
            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate)).MustHaveHappenedOnceExactly();
        }
        public void Test_Sould_be_able_to_get_Exchange_Rate()
        {
            //Arrange
            ICountry fromCountry = new Country()
            {
                CurrencyId = "USD"
            };
            ICountry toCountry = new Country()
            {
                CurrencyId = "INR"
            };
            string conversionRate     = "{\"USD_INR\":{\"val\":29}}";
            var    mockUnityContainer = new Mock <IUnityContainer>();
            var    mockRestClient     = new Mock <IRestClient>();
            var    mockIRestResponse  = new Mock <IRestResponse>();

            mockIRestResponse.SetupProperty(x => x.Content, conversionRate);
            mockRestClient.Setup(x => x.Execute(It.IsAny <IRestRequest>())).Returns(() => mockIRestResponse.Object);

            var currencyConverterService = new CurrencyConverterService(mockUnityContainer.Object, mockRestClient.Object);

            //Act
            decimal exchangeRate = currencyConverterService.GetEXchangeRate(fromCountry, toCountry);

            //Assert
            Assert.AreEqual(exchangeRate, 29);
        }
        public void ConvertFromTo_ProductList_SameCurrency()
        {
            // ARRANGE
            ICurrencyConverterService service = new CurrencyConverterService();
            var p1 = new Product()
            {
                Id          = 1,
                Name        = "hmm",
                Description = "Desc",
                Price       = new ProductPrice {
                    Value = 1, Currency = Currency.USD
                },
                Category = ProductCategory.Pants
            };
            var productList = new List <Product>()
            {
                p1
            };

            // ACT
            var newProductList = service.ConvertTo(productList, Currency.EUR);

            // ASSESS
            Assert.Single(newProductList);
            var newProduct = newProductList.Single();

            Assert.NotEqual(p1, newProduct);
            Assert.NotEqual(p1.Price, newProduct.Price);
            Assert.Equal(Currency.EUR, newProduct.Price.Currency);
        }
Example #4
0
        public async Task Convert_NullMoneys_ReturnsNotNull()
        {
            var converter = new CurrencyConverterService(this._apiRepository, this._logger);

            var result = await converter.Convert(null, this._currency, this._conversionTime, this._ruleCtx);

            Assert.IsNotNull(result);
        }
Example #5
0
        public async Task Conversion_should_returns_success_when_a_current_currency_equals_a_target_currency()
        {
            var getCurrencyFunc = new Func <object, Currencies?>(o => CurrencyConverterService.TargetCurrency);
            var service         = new CurrencyConverterService(null, null);

            var result = await service.ConvertPricesInData(new AgentContext(), new object(), null, getCurrencyFunc);

            Assert.True(result.IsSuccess);
        }
Example #6
0
        public async Task Conversion_should_returns_failure_when_a_current_currency_is_not_specified()
        {
            var getCurrencyFunc = new Func <object, Currencies?>(o => Currencies.NotSpecified);
            var service         = new CurrencyConverterService(null, null);

            var result = await service.ConvertPricesInData(new AgentContext(), new object(), null, getCurrencyFunc);

            Assert.True(result.IsFailure);
        }
 public RateForm()
 {
     InitializeComponent();
     currencyComboBox.Items.AddRange(CurrencyConverterService.GetCurrencyTags());
     currencyComboBox.Text            = currencyComboBox.Items[0].ToString();
     currencyDataGriedView.DataSource = euroService.EuroCurrencyRates;
     amountTextBox.GotFocus          += (a, eve) => panelService.RemoveText(amountTextBox);
     amountTextBox.LostFocus         += (a, eve) => panelService.AddText(amountTextBox, "1");
 }
Example #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                try
                {
                    Data data            = FileReaderService.ExtractData(args[0]);
                    uint amountConverted = CurrencyConverterService.Convert(data);
                    Console.Write(amountConverted);
                }
                catch (IOException e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("An error has occured during the file reading !");
                }
                catch (DataFormatException e)
                {
                    Console.WriteLine(e.Message);
                    List <string> log = new List <string>
                    {
                        "Invalid data format !",
                        "",
                        "Reminder of the correct format :",
                        "",
                        "XXX;M;YYY",
                        "N",
                        "AAA;BBB;T.TTTT",
                        "CCC;DDD;U.UUUU",
                        "EEE;FFF;V.VVVV",
                        "... N times"
                    };

                    Console.WriteLine(string.Join("\n", log.ToArray()));
                }
                catch (AlgorithmException e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("An error has occured during the dijkstra algorithm !");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Uncaught error !");
                }
            }
            else if (args.Length > 1)
            {
                Console.WriteLine("Multiple files names !");
            }
            else
            {
                Console.WriteLine("File name missed !");
            }

            Console.ReadLine();
        }
Example #9
0
        static async Task <int> Main(string[] args)
        {
            var tw = new TextWriterTraceListener(Console.Out);

            tw.TraceOutputOptions |= TraceOptions.None;
            Trace.Listeners.Add(tw);
            Trace.AutoFlush = true;
            Trace.Indent();

            var app = new CommandLineApplication
            {
                Name        = "TW ING Coding Challenge",
                Description = "The TeamWildenberg console app for the different assignments in the ING Coding Challenge"
            };

            app.HelpOption("-?|-h|--help");
            var versionOption = app.Option("-v|--version", "Check which version we are running", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                return(0);
            });
            app.Execute(args);

            if (versionOption.HasValue())
            {
                var assemblyVersion = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;
                TraceExtensions.DoMessage($"Version: {assemblyVersion}");
                return(0);
            }
            else
            {
                // instantiate services
                ICurrencyConverterService converterService = new CurrencyConverterService();
                ICsvService csvService = new CsvService(new HttpClient());

                // execute command
                try
                {
                    ICommandAsync cmd = new ChallengeCommand(csvService, converterService);
                    await cmd.Execute().ConfigureAwait(false);

                    return(0);
                }
                catch (CsvServiceException x)
                {
                    TraceExtensions.DoError(x.Message);
                    return(-1);
                }
                catch (Exception)
                {
                    TraceExtensions.DoError($"Something fishy happened, exiting.");
                    throw;
                }
            }
        }
Example #10
0
        static void Main(string[] args)
        {
            localhost.CurrencyConverterService service = new CurrencyConverterService();
            var result = service.rateOfExchange("EUR", "USD");

            Console.WriteLine(result);

            var result2 = service.convert("EUR", "USD", 22);

            Console.WriteLine(result2);
        }
        public void Get_currency_converterlayer_success(string from, string to)
        {
            var mock = new Mock <IHttpClient>();

            mock.Setup(x => x.GetBaseHttpTask <decimal>(Singleton.AppSettings.BaseUrl, "currency", $"currencyFrom={from}", $"currencyTo={to}"));

            var service = new CurrencyConverterService(mock.Object);

            service.GetCurrency(from, to);
            mock.Verify(x => x.GetBaseHttpTask <decimal>(Singleton.AppSettings.BaseUrl, "currency", $"currencyFrom={from}", $"currencyTo={to}"), Times.Once);
        }
        public async Task InitDatabase()
        {
            if (database.CurrencyRepository.GetAll().Any())
            {
                return;
            }
            var currencies = CurrencyConverterService.GetCurrencyTags().Select(c => Currency.Create(c));

            database.CurrencyRepository.AddRange(currencies);
            await database.Complete();
        }
        public void Get_currencies_converterlayer_success()
        {
            var mock = new Mock <IHttpClient>();

            mock.Setup(x => x.GetBaseHttpTask <Dictionary <string, string> >(Singleton.AppSettings.BaseUrl, "currency/currencies"));

            var service = new CurrencyConverterService(mock.Object);

            service.GetCurrencies();
            mock.Verify(x => x.GetBaseHttpTask <Dictionary <string, string> >(Singleton.AppSettings.BaseUrl, "currency/currencies"), Times.Once);
        }
Example #14
0
        public async Task Conversion_should_returns_failure_when_a_rate_currency_service_returns_failure()
        {
            var rateServiceMock = new Mock <ICurrencyRateService>();

            rateServiceMock.Setup(s => s.Get(It.IsAny <Currencies>(), It.IsAny <Currencies>()))
            .Returns(new ValueTask <Result <decimal> >(Result.Failure <decimal>("error")));
            var service = new CurrencyConverterService(rateServiceMock.Object, null);

            var result = await service.ConvertPricesInData(new AgentContext(), new object(), null, GetCurrencyFunc);

            Assert.True(result.IsFailure);
        }
Example #15
0
        public void TestInputNumber()
        {
            var currencyConverterService = new CurrencyConverterService();

            var oddSymbol1 = currencyConverterService.GetNumberPresentation("11t");
            var oddSymbol2 = currencyConverterService.GetNumberPresentation("11.0");
            var bigNumber  = currencyConverterService.GetNumberPresentation("999 999 999 999");

            Assert.AreEqual(Language.NotNumber, oddSymbol1.ErrorMessage);
            Assert.AreEqual(null, oddSymbol2.ErrorMessage);
            Assert.AreEqual(Language.RangeOfNumber, bigNumber.ErrorMessage);
        }
Example #16
0
        public BaseTest()
        {
            var currency = new Mock <ICurrencySource>();

            currency.Setup(q => q.GetCurrencies(It.IsAny <string>()))
            .Returns(new Dictionary <string, decimal> {
                { "BRL", 3.86371m },
                { "USD", 1 },
                { "EUR", 0.85042m }
            });

            CurrencyService = new CurrencyConverterService(currency.Object);
        }
Example #17
0
        public async Task Convert_NullRatesResult_ReturnsNull()
        {
            var converter = new CurrencyConverterService(this._apiRepository, this._logger);
            var Moneys    = new List <Money> {
                new Money(100, "CNY")
            };
            var targetCurrency = new Currency("GBP");
            var targetDate     = new DateTime(2018, 01, 01);

            var conversion = await converter.Convert(Moneys, targetCurrency, targetDate, this._ruleCtx);

            Assert.IsNull(conversion);
            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate)).MustHaveHappened();
        }
Example #18
0
        public async Task Convert_InSameCurrencyAsTarget_DoesNotCallExchangeRateApi()
        {
            var converter = new CurrencyConverterService(this._apiRepository, this._logger);
            var Moneys    = new List <Money> {
                new Money(10, "CNY")
            };
            var targetCurrency = new Currency("CNY");

            var conversion = await converter.Convert(Moneys, targetCurrency, DateTime.UtcNow, this._ruleCtx);

            Assert.AreEqual(conversion.Value.Value, 10);
            Assert.AreEqual(conversion.Value.Currency.Code, "CNY");

            A.CallTo(() => this._apiRepository.GetAsync(A <DateTime> .Ignored, A <DateTime> .Ignored)).MustNotHaveHappened();
        }
        public void ConvertFromTo_Price_SameCurrency()
        {
            // ARRANGE
            ICurrencyConverterService service = new CurrencyConverterService();
            var price = new ProductPrice()
            {
                Value = 1, Currency = Currency.USD
            };

            // ACT
            var newPrice = service.ConvertTo(price, Currency.USD);

            // ASSESS
            Assert.Equal(Currency.USD, newPrice.Currency);
            Assert.Equal(1, newPrice.Value);
        }
Example #20
0
        public WalletController(CurrencyConverterService currencyConverterService)
        {
            Users.Add(new User
            {
                Id     = 1,
                Name   = "Ivan",
                Wallet = new Dictionary <string, decimal>
                {
                    { "RUB", 10000 },
                    { "USD", 500 },
                    { "CAD", 10 },
                    { "AUD", 150 },
                    { "JPY", 0 },
                    { "PLN", 0 }
                }
            });
            Users.Add(new User
            {
                Id     = 2,
                Name   = "Alex",
                Wallet = new Dictionary <string, decimal>
                {
                    { "RUB", 5000 },
                    { "USD", 1700 },
                    { "CAD", 100 },
                    { "AUD", 100 },
                    { "JPY", 0 },
                    { "PLN", 1000 }
                }
            });
            Users.Add(new User
            {
                Id     = 3,
                Name   = "John",
                Wallet = new Dictionary <string, decimal>
                {
                    { "RUB", 0 },
                    { "USD", 2000 },
                    { "CAD", 800 },
                    { "AUD", 700 },
                    { "JPY", 30000 },
                    { "PLN", 0 }
                }
            });

            _currencyConverterService = currencyConverterService;
        }
Example #21
0
        public async Task Convert_EmptyRatesResult_ReturnsNull()
        {
            var converter = new CurrencyConverterService(this._apiRepository, this._logger);
            var Moneys    = new List <Money> {
                new Money(100, "CNY")
            };
            var targetCurrency = new Currency("GBP");
            var targetDate     = new DateTime(2018, 01, 01);

            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate))
            .Returns(new Dictionary <DateTime, IReadOnlyCollection <ExchangeRateDto> >());

            var conversion = await converter.Convert(Moneys, targetCurrency, targetDate, this._ruleCtx);

            Assert.IsNull(conversion);
            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate)).MustHaveHappenedOnceExactly();
        }
Example #22
0
        public async Task <ProductPrice> Get([FromRoute] string product, [FromQuery] string targetCurrency)
        {
            string exchangeRatesPath = "ExchangeRates.csv";
            IEnumerable <ExchangeRate> exchangeRates = (await(await client.GetAsync(exchangeRatesPath))
                                                        .EnsureSuccessStatusCode().Content.ReadAsStringAsync()).
                                                       Replace("\r", string.Empty).Split("\n").Select((s, id) =>
            {
                Console.WriteLine(id);
                if (id != 0)
                {
                    string[] args = s.Split(",");
                    if (args.Count() == 2)
                    {
                        ExchangeRate exchangeRate = new ExchangeRate();
                        exchangeRate.Currency     = args[0];
                        exchangeRate.Value        = Decimal.Parse(args[1], CultureInfo.InvariantCulture);
                        return(exchangeRate);
                    }
                }
                return(null);
            }).Where(e => e != null);
            string pricesPath = "Prices.csv";
            IEnumerable <Product> products = (await(await client.GetAsync(pricesPath))
                                              .EnsureSuccessStatusCode().Content.ReadAsStringAsync()).
                                             Replace("\r", string.Empty).Split("\n").Select((s, id) =>
            {
                Console.WriteLine(id);
                if (id != 0)
                {
                    string[] args = s.Split(",");
                    if (args.Count() == 3)
                    {
                        Product exchangeRate     = new Product();
                        exchangeRate.Description = args[0];
                        exchangeRate.Currency    = args[1];
                        exchangeRate.Price       = Decimal.Parse(args[2], CultureInfo.InvariantCulture);
                        return(exchangeRate);
                    }
                }
                return(null);
            }).Where(e => e != null);
            CurrencyConverterService currencyConverter = new CurrencyConverterService(exchangeRates, products);

            return(currencyConverter.ConvertCurrency(product, targetCurrency));
        }
Example #23
0
        public async Task Conversion_should_use_rate_to_convert_prices()
        {
            var rateService       = CreateAedToUsdRateService(aedToUsdRate: (decimal)0.274);
            var converterFactory  = CreateConverterFactoryWithZeroBuffers();
            var currencyConverter = new CurrencyConverterService(rateService, converterFactory);
            var originalPrice     = new MoneyAmount
            {
                Amount   = (decimal)3761.62,
                Currency = Currencies.AED
            };

            var(_, _, resultingPrice, _) = await currencyConverter.ConvertPricesInData(originalPrice,
                                                                                       (amount, function) => function(amount),
                                                                                       d => d.Currency);


            Assert.Equal((decimal)1030.68, resultingPrice.Amount);
            Assert.Equal(Currencies.USD, resultingPrice.Currency);
        public void Test_Sould_be_able_to_get_CountryList()
        {
            //Arrange
            const string countries          = "{\"results\":{\"AF\":{\"alpha3\":\"AFG\",\"currencyId\":\"AFN\",\"currencyName\":\"Afghan afghani\",\"currencySymbol\":\"؋\",\"id\":\"AF\",\"name\":\"Afghanistan\"},\"AI\":{\"alpha3\":\"AIA\",\"currencyId\":\"XCD\",\"currencyName\":\"East Caribbean dollar\",\"currencySymbol\":\"$\",\"id\":\"AI\",\"name\":\"Anguilla\"}}}";
            var          mockUnityContainer = new Mock <IUnityContainer>();
            var          mockRestClient     = new Mock <IRestClient>();
            var          mockIRestResponse  = new Mock <IRestResponse>();

            mockIRestResponse.SetupProperty(x => x.Content, countries);
            mockRestClient.Setup(x => x.Execute(It.IsAny <IRestRequest>())).Returns(() => mockIRestResponse.Object);

            var currencyConverterService = new CurrencyConverterService(mockUnityContainer.Object, mockRestClient.Object);

            //Act
            ObservableCollection <ICountry> countriesList = currencyConverterService.GetCountries();

            //Assert
            Assert.AreEqual(countriesList.Count, 2);
        }
Example #25
0
        public async Task Convert_WithIndirectConversionRateSetOneRates_ReturnsExpectedResult(
            decimal rate1,
            decimal rate2,
            decimal expected)
        {
            var converter = new CurrencyConverterService(this._apiRepository, this._logger);
            var Moneys    = new List <Money> {
                new Money(100, "CNY")
            };
            var targetCurrency = new Currency("EUR");
            var targetDate     = new DateTime(2018, 01, 01);
            var cnyRate        = new ExchangeRateDto
            {
                DateTime         = targetDate,
                FixedCurrency    = "CNY",
                VariableCurrency = "USD",
                Name             = "Thaler",
                Rate             = (double)rate1
            };
            var eurRate = new ExchangeRateDto
            {
                DateTime         = targetDate,
                FixedCurrency    = "EUR",
                VariableCurrency = "USD",
                Name             = "Thaler",
                Rate             = (double)rate2
            };

            var rates = new Dictionary <DateTime, IReadOnlyCollection <ExchangeRateDto> >
            {
                { targetDate, new[] { cnyRate, eurRate } }
            };

            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate)).Returns(rates);

            var conversion = await converter.Convert(Moneys, targetCurrency, targetDate, this._ruleCtx);

            Assert.IsNotNull(conversion);
            Assert.AreEqual(conversion.Value.Value, expected);
            Assert.AreEqual(conversion.Value.Currency.Code, "EUR");
            A.CallTo(() => this._apiRepository.GetAsync(targetDate, targetDate)).MustHaveHappenedOnceExactly();
        }
Example #26
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            quotes                    = new SourceCache <Quote, string>(quote => quote.Pair);
            myTrades                  = new SourceCache <Trade, long>(trade => trade.Id);
            myTradesQuoteUpdate       = new SourceCache <Trade, long>(trade => trade.Id);
            clientBalances            = new SourceCache <BalancePerClient, long>(Balance => Balance.ClientID);
            curPairPositionPerClient  = new SourceCache <CurPairPositionPerClient, string>(CurPairPositionPerClient => CurPairPositionPerClient.ClientPair);
            curPositionPerClient      = new SourceCache <CurPositionPerClient, string>(CurPositionPerClient => CurPositionPerClient.ClientIdCur);
            curPositionPerClientCache = curPositionPerClient.AsObservableCache();

            curPositionPerClientQuoteUpdate = new SourceCache <CurPositionPerClient, string>(CurPositionPerClient => CurPositionPerClient.ClientIdCur);



            myTradesLocker             = new object();
            CurPositionPerClientLocker = new object();

            // services Initialization
            ITradesModifierService    tradesModifierService    = new TradesModifierService(myTrades);
            ICurrencyConverterService currencyConverterService = new CurrencyConverterService(quotes);

            IQuoteExtractorService quoteExtractor = new QuoteExtractorService(myTrades, quotes, clientBalances, tradesModifierService);

            new Thread(quoteExtractor.ExtractData).Start();

            ILogPrinterService logPrinterService = new LogPrinterService(myTrades, clientBalances, curPairPositionPerClient, curPositionPerClient, curPositionPerClientCache, curPositionPerClientQuoteUpdate, myTradesQuoteUpdate);

            logPrinterService.PrintClientBalances();
            logPrinterService.PrintcurPairPositionPerClient();
            logPrinterService.PrintmyTrades();
            logPrinterService.PrintcurPositionPerClientCache();
            logPrinterService.PrintmyTradesQuoteUpdate();
            logPrinterService.PrintcurPositionPerClientQuoteUpdate();

            IStopOutExecutorService stopOutExecutorService = new StopOutExecutorService(quotes, clientBalances, curPairPositionPerClient, tradesModifierService, currencyConverterService);

            stopOutExecutorService.ManageStopOuts();

            IPositionPerCurrencyPairCalculatorService positionPerCurrencyPairCalculatorService = new PositionPerCurrencyPairCalculatorService(myTrades, curPairPositionPerClient);

            positionPerCurrencyPairCalculatorService.CalculatePosistionPerCurrencyPairPerCustomer();

            IPositionPerCurrencyCalculatorService positionPerCurrencyCalculatorService = new PositionPerCurrencyCalculatorService(myTrades, curPositionPerClient, currencyConverterService);

            positionPerCurrencyCalculatorService.CalculatePosistionPerCurrencyPerCustomer();

            IMarginCalculatorService marginCalculatorService = new MarginCalculatorService(clientBalances, curPositionPerClient);

            marginCalculatorService.CalculateRequiredMargin();

            IPAndLUpdaterService pAndLUpdaterService = new PAndLUpdaterService(myTrades, clientBalances);

            pAndLUpdaterService.UpdatePandLPerClient();

            ICurrencyPositionPerClientUpdaterService currencyPositionPerClientUpdaterService = new CurrencyPositionPerClientUpdaterService(quotes, curPositionPerClient, curPositionPerClientQuoteUpdate, curPositionPerClientCache);

            currencyPositionPerClientUpdaterService.UpdateAllCurrenciesPositions();

            IUpdateTradesService updateTradesService = new UpdateTradesService(myTrades, quotes, currencyConverterService, myTradesQuoteUpdate);

            updateTradesService.UpdateAllTradesAndQuotes();
        }
Example #27
0
 public CurrenciesController(ICurrencySource currencyService, CurrencyConverterService currencyConverterService)
 {
     _currencyService          = currencyService;
     _currencyConverterService = currencyConverterService;
 }
 public void Setup()
 {
     _target = new CurrencyConverterService();
 }