using OemanTrader.Domain.Exceptions; using OemanTrader.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OemanTrader.Domain.Services.TransactionServices { public class BuyStockService : IBuyStockService { private readonly IStockPriceService _stockPriceService; private readonly IDataService _accountService; public BuyStockService(IStockPriceService stockPriceService, IDataService accountService) { _stockPriceService = stockPriceService; _accountService = accountService; } public async Task BuyStock(Account buyer, string symbol, int shares) { double stockPrice = await _stockPriceService.GetPrice(symbol); double transactionPrice = stockPrice * shares; if (transactionPrice > buyer.Balance) { throw new InsufficientFundsException(buyer.Balance,transactionPrice); } AssetTransaction transaction = new AssetTransaction() { Account = buyer, Asset = new Asset() { PricePerShare = stockPrice, Symbol = symbol }, DateProcessed = DateTime.Now, ShareAmount = shares, IsPurchase = true }; buyer.AssetTransactions.Add(transaction); buyer.Balance -= transactionPrice; await _accountService.Update(buyer.Id, buyer); return buyer; } } }