public async Task <decimal?> GetQuoteAsync(QuoteRequest quoteRequest) { var candle = await _externalFinancialService.GetCandleAsync(quoteRequest.Symbol, quoteRequest.Date); if (candle == null) { throw new ApiException(HttpStatusCode.NotFound, $"Quote data not found [{quoteRequest.Symbol}/{quoteRequest.Date:yyyy-MM-dd}]."); } const string marketCurrencySymbol = "USD"; string regionCurrencySymbol = _globalizationService.GetCurrencySymbol(quoteRequest.Region); if (regionCurrencySymbol.Equals(marketCurrencySymbol, StringComparison.InvariantCultureIgnoreCase)) { return(await Task.FromResult(candle.Close)); } decimal marketExchangeRate = await _exchangeRateService.GetExchangeRateAsync(marketCurrencySymbol, quoteRequest.Date); decimal regionExchangeRate = await _exchangeRateService.GetExchangeRateAsync(regionCurrencySymbol, quoteRequest.Date); decimal?quote = candle.Close * marketExchangeRate / regionExchangeRate; return(await Task.FromResult(quote)); }
/// <summary> /// Обменять валюту /// </summary> /// <param name="sourceCurrencyId">Идентификатор исходящей валюты</param> /// <param name="destinationCurrencyId">Идентификатор входящей валюты</param> /// <param name="sumInSourceCurrency">Сумма в исходящей валюте</param> public async Task ExchangeAsync(long userId, int sourceCurrencyId, int destinationCurrencyId, decimal sumInSourceCurrency) { var wallet = walletRepository.GetWalletByUserId(userId); if (wallet == null) { throw new ArgumentException($"В системе не заведен кошелек для пользователя с ИД = {userId}"); } var sourceCurrency = currencyRepository.GetCurrencyById(sourceCurrencyId); var destinationCurrency = currencyRepository.GetCurrencyById(destinationCurrencyId); if (sourceCurrency == null) { throw new ArgumentException($"В БД не найдена валюта с ИД = {sourceCurrencyId}"); } if (destinationCurrency == null) { throw new ArgumentException($"В БД не найдена валюта с ИД = {destinationCurrencyId}"); } var exchangeRate = await exchangeRateService.GetExchangeRateAsync(sourceCurrency.Code, destinationCurrency.Code); wallet.Withdraw(sourceCurrencyId, sumInSourceCurrency); var sumInDestinationCurrency = sumInSourceCurrency * exchangeRate; wallet.Deposit(destinationCurrencyId, sumInDestinationCurrency); walletRepository.Update(wallet); }
private async Task <ExchangeResponse> CalculateTaxAsync(DateTime invoiceDate, double preTaxAmount, string currency) { var fixerResponse = await _exchangeRateService.GetExchangeRateAsync(invoiceDate, new string[] { currency }); if (!fixerResponse.Success) { return(new ExchangeResponse { Errors = new[] { "Could not get conversion rate" } }); } double exchRate; fixerResponse.Rates.TryGetValue(currency, out exchRate); var calcPreTaxAmount = preTaxAmount * exchRate; double taxRate; _taxRateOptions.TryGetValue(currency, out taxRate); var calcTaxAmount = calcPreTaxAmount * (taxRate / 100); return(new ExchangeResponse { Exchange = new Exchange { PreTaxAmount = CurrencyHelper.DisplayAs(calcPreTaxAmount, currency), TaxAmount = CurrencyHelper.DisplayAs(calcTaxAmount, currency), GrandTotal = CurrencyHelper.DisplayAs(calcPreTaxAmount + calcTaxAmount, currency), ExchangeRate = exchRate, }, Success = true }); }
public async Task <IActionResult> GetExhangeRate([FromBody] string currencyCode) { try { var exchangeRate = await _exchangeRateService.GetExchangeRateAsync(currencyCode); return(Ok(exchangeRate)); } catch (Exception ex) { _logger.LogCritical(ex.Message); return(BadRequest(new ErrorViewModel { Error = ErrorCode.ServerError, ErrorDescription = ex.Message })); } }
private void InitTasks() { _exchangeRateTask = _exchangeRateService.GetExchangeRateAsync(); _accountSummaryTask = _accountManager.RequestAccountSummaryAsync(); }
public async Task <IActionResult> SendAction([FromBody] SendPaymentModel model) { if (ModelState.IsValid) { var user = await GetCurrentUserAsync(); var primaryWallet = await _applicationDbContext.UserPrimaryWallets .Include(e => e.Wallet) .FirstOrDefaultAsync(e => e.UserId == user.Id); if (primaryWallet == null) { _logger.LogInformation(@"User '{user.Id}' does not have an associated primary wallet."); return(BadRequest()); } var currency = await _applicationDbContext.Currencies.FirstOrDefaultAsync(e => e.Code == model.CurrencyCode); if (currency == null) { return(BadRequest()); } var exchangeRate = await _exchangeRateService.GetExchangeRateAsync(currency.Code); var tokens = model.Amount * exchangeRate.Value; var wallet = primaryWallet.Wallet; if (wallet.Balance < tokens) { return(BadRequest()); } using (var dbTransaction = _applicationDbContext.Database.BeginTransaction()) { try { var payment = new Payment() { SenderId = user.Id, ReceiverId = model.ReceiverId, CurrencyCode = model.CurrencyCode, Amount = model.Amount, ExchangeRate = exchangeRate.Value, Fee = 0, Tokens = tokens, Status = PaymentStatus.Pending, CreatedAt = DateTime.UtcNow }; payment.SuspenseWallet = new PaymentSuspenseWallet() { Label = Guid.NewGuid().ToString(), Balance = tokens }; _applicationDbContext.Payments.Add(payment); await _applicationDbContext.SaveChangesAsync(); dbTransaction.Commit(); return(Ok()); } catch (Exception ex) { dbTransaction.Rollback(); _logger.LogCritical(ex.Message); ModelState.AddModelError(string.Empty, ex.Message); } } } return(BadRequest(ModelState.GetErrorResponse())); }