private static void RemoveTradeAsset(InvestmentAccount account, Asset asset) { int SoldQuantity; int totalOwnedQuantity = 0; if (asset.GetType() == typeof(Stock)) { SoldQuantity = ((Stock)asset).quantity; foreach (Stock ListStock in account.AssetList.OfType <Stock>()) { if (ListStock.Symbol == ((Stock)asset).Symbol) { totalOwnedQuantity += ListStock.quantity; } } if (totalOwnedQuantity < SoldQuantity) { throw new InvalidTradeException("Not enough shares to trade with."); } else { foreach (Stock ListStock in account.AssetList.OfType <Stock>()) { if (ListStock.Symbol == ((Stock)asset).Symbol) { if (SoldQuantity < ListStock.quantity) { //reduce share, no removal ListStock.changeQuantity(SoldQuantity); SoldQuantity = 0; } else { //remove asset SoldQuantity -= ListStock.quantity; ListStock.QuantityToZero(); } } } } } else { SoldQuantity = ((Forex)asset).quantity; foreach (Forex ListForex in account.AssetList.OfType <Forex>()) { if (ListForex.currencyPair == ((Forex)asset).currencyPair) { totalOwnedQuantity += ListForex.quantity; } } if (totalOwnedQuantity < SoldQuantity) { throw new InvalidTradeException("Not enough quantities to trade with."); } else { foreach (Forex ListForex in account.AssetList.OfType <Forex>()) { if (ListForex.currencyPair == ((Forex)asset).currencyPair) { if (SoldQuantity < ListForex.quantity) { //reduce share, no removal ListForex.changeQuantity(SoldQuantity); SoldQuantity = 0; } else { //remove asset SoldQuantity -= ListForex.quantity; ListForex.QuantityToZero(); } } } } } int i = 0; while (i < account.AssetList.Count) { if ((account.AssetList[i].GetType() == typeof(Stock) && ((Stock)account.AssetList[i]).quantity == 0) || (account.AssetList[i].GetType() == typeof(Forex) && ((Forex)account.AssetList[i]).quantity == 0)) { account.RemoveInvestmentAssets(account.AssetList[i]); } else { i++; } } }