private void btnCalculate_Click(object sender, EventArgs e) { ShareSellInfo = new ShareSellInfo(); try { if (!Helper.Helper.Required(txtSharesSold) || !Helper.Helper.Required(txtPricePerShare) || !Helper.Helper.Required(txtSellDate)) { return; } if (!Helper.Helper.NonNegativeInteger(txtSharesSold) || !Helper.Helper.NonNegativeDecimal(txtPricePerShare) || !Helper.Helper.ValidDate(txtSellDate)) { return; } int soldShares = int.Parse(txtSharesSold.Text); int remainingShares = lblRemainingShares.Text == String.Empty ? Calc.GetTotalShares() : int.Parse(lblRemainingShares.Text); if (soldShares > remainingShares) { MessageBox.Show("Available shares: " + remainingShares.ToString() + "."); return; } DateTime lastSharePurcahaseDate = Calc.GetLastSharePurchaseDate(); if (DateTime.Parse(txtSellDate.Text) < lastSharePurcahaseDate) { MessageBox.Show("Sell Date can not be less than " + lastSharePurcahaseDate.ToString("dd/MM/yyyy") + "."); return; } ShareSellInfo.Quantity = soldShares; ShareSellInfo.Price = decimal.Parse(txtPricePerShare.Text); ShareSellInfo.SellingDate = DateTime.Parse(txtSellDate.Text); ShareRemainingDisplayInfo shareRemainingDisplayInfo = Calc.Calculate(ShareSellInfo); lblRemainingShares.Text = shareRemainingDisplayInfo.RemainingShares.ToString(); lblCostPriceSoldShares.Text = shareRemainingDisplayInfo.CostPriceSoldShares.ToString(); lblCostPriceRemainingShares.Text = shareRemainingDisplayInfo.CostPriceRemainingSharesPerQuantity.ToString(); lblGainLoss.Text = shareRemainingDisplayInfo.ProfitLoss.ToString(); } catch (Exception) { MessageBox.Show("Something went wrong. Please restart your application."); } }
// Calculate data of remaining share, cost price of sold share, cost price of remaining share per quantity and actual Profit or loss. public ShareRemainingDisplayInfo Calculate(ShareSellInfo shareSellInfo) { ShareSellInfomation.Add(shareSellInfo); int totalSharesPurchase = ShareCostInfomation.Sum(x => x.Quantity); int totalSharesSold = ShareSellInfomation.Sum(y => y.Quantity); int remainingShares = totalSharesPurchase - totalSharesSold; decimal costPriceSoldShares = GetCostPriceSoldShares(ShareCostInfomation, totalSharesSold); decimal sellPriceSoldShares = GetSellPriceSoldShares(ShareSellInfomation); decimal CostPriceRemainingShares = GetCostPriceRemainingShares(ShareCostInfomation, costPriceSoldShares); ShareRemainingDisplayInfo shareRemainingDisplayInfo = new ShareRemainingDisplayInfo(); shareRemainingDisplayInfo.RemainingShares = remainingShares; shareRemainingDisplayInfo.CostPriceSoldShares = Math.Round(costPriceSoldShares / totalSharesSold, 3); shareRemainingDisplayInfo.CostPriceRemainingSharesPerQuantity = remainingShares != 0? Math.Round(CostPriceRemainingShares / remainingShares, 8):0; shareRemainingDisplayInfo.ProfitLoss = Math.Round(sellPriceSoldShares - costPriceSoldShares, 0); return(shareRemainingDisplayInfo); }