// Determines if the portfolio is balance public static void CheckBalanced(AppDbContext db, AppUser Customer) { // get the users stock account // Get the customer Savings account var SAQ = from sa in db.StockAccount where sa.Customer.Id == Customer.Id select sa; StockAccount CustomerStockAccount = SAQ.FirstOrDefault(); // Holding variables to counts the number of each type of stock Int32 ordinary = 0; Int32 index = 0; Int32 mutual = 0; // loop through the stocks and check the types foreach (Trade t in CustomerStockAccount.Trades) { if (t.TradeType == TradeType.Buy) { if (t.StockMarket.StockType == StockType.Ordinary) { ordinary += 1; } else if (t.StockMarket.StockType == StockType.Index_Fund) { index += 1; } else if (t.StockMarket.StockType == StockType.Mutual_Fund) { mutual += 1; } } } // check to see if balanced if (ordinary >= 2 && index >= 1 && mutual >= 1) { CustomerStockAccount.Balanced = true; } else { CustomerStockAccount.Balanced = false; } // update the stock account db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); }
public void PostCompany([FromBody] StockAccountDto stockAccountDto) { StockAccount com = new StockAccount(); com.Id = stockAccountDto.Id; com.Status = stockAccountDto.Status; com.SharesType = stockAccountDto.SharesType; com.CurrentAmount = stockAccountDto.CurrentAmount; com.Beneficiary = stockAccountDto.Beneficiary; com.ExpiredDate = stockAccountDto.ExpiredDate; com.ShareholderId = stockAccountDto.ShareholderId; com.ShareTypeId = stockAccountDto.ShareTypeId; stocky.StockAccount.Add(com); stocky.SaveChanges(); }
public override void UpdateStockAccountInfo(StockAccount account) { //first time to initialized if (account.StockPositionMap.Count <= 0) { if (null == MarketMakerMgr.GetInstance().GetFairValueMgr().MyMarketData) { return; } String symbol = MarketMakerMgr.GetInstance().GetFairValueMgr().MyMarketData.Symbol; StockPosition position = new StockPosition(); position.BaseVolume = position.TotalVolume = position.AvailVolume = 100; account.StockPositionMap[symbol] = position; } }
public void PutStockAccount(String id, [FromBody] StockAccountDto stockAccountDto) { // stocky.Company.Update(id, com); StockAccount com = stocky.StockAccount.Where(e => e.Id == stockAccountDto.Id).Single <StockAccount>(); com.Id = stockAccountDto.Id; com.Status = stockAccountDto.Status; com.SharesType = stockAccountDto.SharesType; com.CurrentAmount = stockAccountDto.CurrentAmount; com.Beneficiary = stockAccountDto.Beneficiary; com.ExpiredDate = stockAccountDto.ExpiredDate; com.ShareholderId = stockAccountDto.ShareholderId; com.ShareTypeId = stockAccountDto.ShareTypeId; stocky.Entry(com).State = Microsoft.EntityFrameworkCore.EntityState.Modified; stocky.SaveChanges(); }
// GET: StockAccounts/Details // Shows all of the Trades for the stock account // Takes the Users to the index page of the StockTradeViewModel public ActionResult Details() { // Get the customer var CustomerQuery = from u in db.Users where u.UserName == User.Identity.Name select u; AppUser Customer = CustomerQuery.FirstOrDefault(); // Get the Stock Account var StockAccountQuery = from s in db.StockAccount where s.Customer.Id == Customer.Id select s; StockAccount CustomerStockAccount = StockAccountQuery.FirstOrDefault(); // Check to see if the stock account is active if (CustomerStockAccount.ApprovalStatus == ApprovedorNeedsApproval.NeedsApproval) { RedirectToAction("Portal", "Home"); } // Get all of the trades for the customer var TradesQuery = from t in db.Trades where t.StockAccount.StockAccountID == CustomerStockAccount.StockAccountID select t; List <Trade> Trades = TradesQuery.ToList(); // Get all of the transactions var TransQuery = from t in db.BankingTransaction where t.StockAccount.StockAccountID == CustomerStockAccount.StockAccountID select t; List <BankingTransaction> Trans = TransQuery.ToList(); // Add to view bag ViewBag.Trades = Trades; ViewBag.Transactions = Trans; ViewBag.Ranges = SearchTransactions.AmountRange(); ViewBag.Dates = SearchTransactions.DateRanges(); ViewBag.Customer = Customer; ViewBag.ResultsCount = Trans.Count; return(View(CustomerStockAccount)); }
public ActionResult DeleteConfirmed() { // Query the Database for the logged in user var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); StockAccount stockAccount = db.StockAccount.Find(customer.StockAccount.FirstOrDefault().StockAccountID); // Remove all dependencies stockAccount.Trades.RemoveAll(i => i.StockAccount.StockAccountID == stockAccount.StockAccountID); stockAccount.BankingTransaction.RemoveAll(i => i.StockAccount.StockAccountID == stockAccount.StockAccountID); db.StockAccount.Remove(stockAccount); db.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult GetTradeHistory(long UserId) { StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); if (stockAccount == null) { return(Json(new { code = 400, message = "没有数据" })); } else { List <TradeHistory> tradeHistories = db.TradeHistories.Where(s => s.StockAccountId == stockAccount.Id).ToList(); if (tradeHistories.Count == 0) { return(Json(new { code = 400, message = "没有数据" })); } else { return(Json(new { code = 200, data = tradeHistories.OrderByDescending(s => s.TradeTime).Select(s => new { s.Id, s.StockCode, s.StockName, TransactionType = s.TransactionType.ToString(), s.TransactionValue, s.TransactionPrice, s.TransactionAmount, TradeTime = ParamHelper.TalkTimeConvert(s.TradeTime) }) })); } } }
// GET: StockAccounts/Delete // Pull up the page to delete the Stock Account public ActionResult Delete() { // Query the Database for the logged in user var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); if (customer == null) { return(HttpNotFound()); } // Find the stock account associated with the customer // Return the Stock Account Associated with the customer StockAccount CustomerStockAccount = customer.StockAccount.FirstOrDefault(); return(View(CustomerStockAccount)); }
public static Double SumStockValueCalculation(long UserId) { StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); List <SimulationStock> simulationStocks = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList(); if (simulationStocks.Count == 0) { return(0); } else { Double SumStockValue = 0; foreach (SimulationStock item in simulationStocks) { SumStockValue += item.NowPrice * item.StockNumber; } return(SumStockValue); } }
public HttpResponseMessage Login(string Phonenumber, string Password) { User loginUser = db.Users.Where(s => s.Phonenumber == Phonenumber).FirstOrDefault(); IDatabase redisDatabase = RedisHelper.Value.Database; if (loginUser == null) { return(ApiResponse.Invalid("Phonenumber", "帐号不存在")); } if (SecurityHelper.MD5Hash(Password) != loginUser.Password) { return(ApiResponse.Invalid("Password", "密码错误")); } else { StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == loginUser.Id); string TalkNumber_Key = "UserId=" + loginUser.Id.ToString() + "&TalkNumber"; return(ApiResponse.Ok(new { loginUser.Id, loginUser.Username, loginUser.Phonenumber, loginUser.CreateTime, loginUser.ImageUrl, Gender = loginUser.Gender.ToString(), StockAge = loginUser.StockAge, loginUser.FansNumber, loginUser.FollowNumber, TalkNumber = redisDatabase.StringGet(TalkNumber_Key), loginUser.Remark, loginUser.CoinNumber, SumMoney = stockAccount == null? "0":ParamHelper.ConvertNumber(stockAccount.SumMoney) })); } }
// GET: /StockTrades/StocksHome // Returns all of the trades associated with the account public ActionResult StocksHome() { // Get the users account // Query the Database for the logged in user var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); // Get the customers stock account // Query the Database for the logged in user var StockAccountQuery = from sa in db.StockAccount where sa.Customer.Id == customer.Id select sa; // Select the account StockAccount CustomerStockAccount = StockAccountQuery.FirstOrDefault(); // Get all of the Trades for the account var TradesQuery = from t in db.Trades where t.StockAccount.StockAccountID == CustomerStockAccount.StockAccountID select t; // Put all of the trades into a list List <Trade> CustomerTrades = TradesQuery.ToList(); // Associate everything with the model // Create a new instance of the StockTrades ViewModel StockTradeViewModel StockTrade = new StockTradeViewModel { StockCustomerProfile = customer, AccountStock = CustomerStockAccount, Trades = CustomerTrades }; return(View(StockTrade)); }
public static void Account(AppDbContext db) { var ca2query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca2 = ca2query.FirstOrDefault(); StockAccount ca2 = new StockAccount { AccountNumber = "1000000000", Customer = Customerca2, Name = "Shan's Stock", CashBalance = 0m }; db.StockAccount.AddOrUpdate(x => x.AccountNumber, ca2); var ca3query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca3 = ca3query.FirstOrDefault(); Saving ca3 = new Saving { AccountNumber = "1000000001", Customer = Customerca3, Name = "William's Savings", Balance = 40035.5m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca3); var ca4query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca4 = ca4query.FirstOrDefault(); Checking ca4 = new Checking { AccountNumber = "1000000002", Customer = Customerca4, Name = "Gregory's Checking", Balance = 39779.49m }; db.CheckingAccount.AddOrUpdate(x => x.AccountNumber, ca4); var ca5query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca5 = ca5query.FirstOrDefault(); Checking ca5 = new Checking { AccountNumber = "1000000003", Customer = Customerca5, Name = "Allen's Checking", Balance = 47277.33m }; db.CheckingAccount.AddOrUpdate(x => x.AccountNumber, ca5); var ca6query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca6 = ca6query.FirstOrDefault(); Checking ca6 = new Checking { AccountNumber = "1000000004", Customer = Customerca6, Name = "Reagan's Checking", Balance = 70812.15m }; db.CheckingAccount.AddOrUpdate(x => x.AccountNumber, ca6); var ca7query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca7 = ca7query.FirstOrDefault(); Saving ca7 = new Saving { AccountNumber = "1000000005", Customer = Customerca7, Name = "Kelly's Savings", Balance = 21901.97m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca7); var ca8query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca8 = ca8query.FirstOrDefault(); Checking ca8 = new Checking { AccountNumber = "1000000006", Customer = Customerca8, Name = "Eryn's Checking", Balance = 70480.99m }; db.CheckingAccount.AddOrUpdate(x => x.AccountNumber, ca8); var ca9query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca9 = ca9query.FirstOrDefault(); Saving ca9 = new Saving { AccountNumber = "1000000007", Customer = Customerca9, Name = "Jake's Savings", Balance = 7916.4m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca9); var ca10query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca10 = ca10query.FirstOrDefault(); StockAccount ca10 = new StockAccount { AccountNumber = "1000000008", Customer = Customerca10, Name = "Michelle's Stock", CashBalance = 0m }; db.StockAccount.AddOrUpdate(x => x.AccountNumber, ca10); var ca11query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca11 = ca11query.FirstOrDefault(); Saving ca11 = new Saving { AccountNumber = "1000000009", Customer = Customerca11, Name = "Jeffrey's Savings", Balance = 69576.83m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca11); var ca12query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca12 = ca12query.FirstOrDefault(); StockAccount ca12 = new StockAccount { AccountNumber = "1000000010", Customer = Customerca12, Name = "Kelly's Stock", CashBalance = 0m }; db.StockAccount.AddOrUpdate(x => x.AccountNumber, ca12); var ca13query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca13 = ca13query.FirstOrDefault(); Checking ca13 = new Checking { AccountNumber = "1000000011", Customer = Customerca13, Name = "Eryn's Checking 2", Balance = 30279.33m }; db.CheckingAccount.AddOrUpdate(x => x.AccountNumber, ca13); //var ca14query = from c in db.Users where c.Email == "*****@*****.**" select c; //AppUser Customerca14 = ca14query.FirstOrDefault(); //IRA ca14 = new IRA { AccountNumber = "1000000012", Customer = Customerca14, Name = "Jennifer's IRA", Balance = 53177.21m }; //addb.IRAAccount.AddOrUpdate(x => x.AccountNumber, ca14); var ca15query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca15 = ca15query.FirstOrDefault(); Saving ca15 = new Saving { AccountNumber = "1000000013", Customer = Customerca15, Name = "Sarah's Savings", Balance = 11958.08m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca15); var ca16query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca16 = ca16query.FirstOrDefault(); Saving ca16 = new Saving { AccountNumber = "1000000014", Customer = Customerca16, Name = "Jeremy's Savings", Balance = 72990.47m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca16); var ca17query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca17 = ca17query.FirstOrDefault(); Saving ca17 = new Saving { AccountNumber = "1000000015", Customer = Customerca17, Name = "Elizabeth's Savings", Balance = 7417.2m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca17); //var ca18query = from c in db.Users where c.Email == "*****@*****.**" select c; //AppUser Customerca18 = ca18query.FirstOrDefault(); //IRA ca18 = new IRA { AccountNumber = "1000000016", Customer = Customerca18, Name = "Allen's IRA", Balance = 75866.69m }; //db.IRAAccount.AddOrUpdate(x => x.AccountNumber, ca18); var ca19query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca19 = ca19query.FirstOrDefault(); StockAccount ca19 = new StockAccount { AccountNumber = "1000000017", Customer = Customerca19, Name = "John's Stock", CashBalance = 0m }; db.StockAccount.AddOrUpdate(x => x.AccountNumber, ca19); var ca20query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca20 = ca20query.FirstOrDefault(); Saving ca20 = new Saving { AccountNumber = "1000000018", Customer = Customerca20, Name = "Clarence's Savings", Balance = 1642.82m }; db.SavingsAccount.AddOrUpdate(x => x.AccountNumber, ca20); var ca21query = from c in db.Users where c.Email == "*****@*****.**" select c; AppUser Customerca21 = ca21query.FirstOrDefault(); Checking ca21 = new Checking { AccountNumber = "1000000019", Customer = Customerca21, Name = "Sarah's Checking", Balance = 84421.45m }; db.CheckingAccount.AddOrUpdate(x => x.AccountNumber, ca21); db.SaveChanges(); }
public ActionResult Create([Bind(Include = "StockAccountID,Name")] StockAccount stockAccount) { if (ModelState.IsValid) { // Query the Database for the logged in user var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); //Change field to needs approval stockAccount.ApprovalStatus = ApprovedorNeedsApproval.NeedsApproval; if (customer == null) { return(HttpNotFound()); } // Add relate the stock account to the customer stockAccount.Customer = customer; // Get the account number stockAccount.AccountNumber = AccountNumber.AutoNumber(db); if (stockAccount.Name == null) { stockAccount.Name = "Longhorn Stock Portfolio"; } // set the stock account to needs approval stockAccount.ApprovalStatus = ApprovedorNeedsApproval.NeedsApproval; stockAccount.CashBalance = 0m; stockAccount.PendingBalance = 0m; stockAccount.Balanced = false; db.StockAccount.Add(stockAccount); db.SaveChanges(); /* Add the inital deposit to the account * * // Get the StockAccount * var StockAccountQuery = from sa in db.StockAccount * where sa.Customer.Id == customer.Id * select sa; * * StockAccount CustomerStockAccount = StockAccountQuery.FirstOrDefault(); * * // check to see if the deposit amount is over $5000 * ApprovedorNeedsApproval FirstDeposit; * if (stockAccount.CashBalance > 5000m) * { * FirstDeposit = ApprovedorNeedsApproval.NeedsApproval; * } * else * { * FirstDeposit = ApprovedorNeedsApproval.Approved; * } * * // Create a new transaction * BankingTransaction InitialDeposit = new BankingTransaction * { * Amount = stockAccount.CashBalance, * ApprovalStatus = FirstDeposit, * BankingTransactionType = BankingTranactionType.Deposit, * Description = "Initial Deposit to Cash Balance", * TransactionDate = DateTime.Today, * TransactionDispute = DisputeStatus.NotDisputed, * StockAccount = CustomerStockAccount * }; * * * // Add the transaction to the database * db.BankingTransaction.Add(InitialDeposit); * db.SaveChanges(); * */ return(View("AccountConfirmation")); } return(View(stockAccount)); }
public static String AutoNumber(AppDbContext db) { // Create a list to hold all of the account number List <Decimal> AccountNumList = new List <Decimal>(); // Find the account with the largest account number var SPQ = from sp in db.StockAccount where sp.AccountNumber != null select sp; SPQ = SPQ.OrderByDescending(s => s.StockAccountID); StockAccount SP = SPQ.FirstOrDefault(); if (SP != null) { Decimal SPAN = Convert.ToDecimal(SP.AccountNumber); AccountNumList.Add(SPAN); } var CAQ = from ca in db.CheckingAccount select ca; CAQ = CAQ.OrderByDescending(c => c.CheckingID); Checking CA = CAQ.FirstOrDefault(); if (CA != null) { Decimal CAN = Convert.ToDecimal(CA.AccountNumber); AccountNumList.Add(CAN); } var SAQ = from sa in db.SavingsAccount select sa; SAQ = SAQ.OrderByDescending(s => s.SavingID); Saving SA = SAQ.FirstOrDefault(); if (SA != null) { Decimal SAN = Convert.ToDecimal(SA.AccountNumber); AccountNumList.Add(SAN); } var IQ = from ira in db.IRAAccount select ira; IQ = IQ.OrderByDescending(s => s.IRAID); IRA I = IQ.FirstOrDefault(); if (I != null) { Decimal IN = Convert.ToDecimal(I.AccountNumber); AccountNumList.Add(IN); } // Variable to hold the max Decimal MaxAccNum = 0; // Loop through each Account Number and find the biggest one foreach (Decimal AccNum in AccountNumList) { if (AccNum > MaxAccNum) { MaxAccNum = AccNum; } } MaxAccNum += 1; return(MaxAccNum.ToString()); }
public HttpResponseMessage BuyStocks(long UserId, string NameorCode, int Number) { User user = db.Users.FirstOrDefault(s => s.Id == UserId); StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); SimulationStock simulationStock = null; JObject jObject = null; ParamHelper paramHelper = new ParamHelper(); string StockCode = NameorCode; if (paramHelper.HaveEnglish(StockCode) || paramHelper.HaveHanZi(StockCode)) { Stock tempStock = db.Stocks.FirstOrDefault(s => s.StockName == StockCode || s.StockName.Equals(StockCode)); if (tempStock == null) { return(ApiResponse.BadRequest("未找到数据")); } StockCode = tempStock.StockCode; } try { string res = new ShowApiRequest("http://route.showapi.com/131-46", "138438", "dd520f20268747d4bbda22ac31c9cbdf") .addTextPara("stocks", StockCode) .addTextPara("needIndex", "0") .post(); jObject = JsonConvert.DeserializeObject <JObject>(res); if (jObject["showapi_res_body"]["ret_code"].ToString() != "0" || jObject["showapi_res_body"]["list"].Count() == 0) { return(ApiResponse.BadRequest("未找到数据")); } double nowPrice = Double.Parse(jObject["showapi_res_body"]["list"].First["nowPrice"].ToString()); string stockName = jObject["showapi_res_body"]["list"].First["name"].ToString(); if (Number * nowPrice > stockAccount.ValidMoney) { return(ApiResponse.BadRequest("老铁,您的钱好像有点不够")); } else { simulationStock = new SimulationStock() { StockAccount = stockAccount, StockAccountId = stockAccount.Id, StockCode = StockCode, BuyPrice = nowPrice, NowPrice = nowPrice, StockNumber = Number, StockName = stockName, BuyTime = DateTime.Now, Valid = true }; stockAccount.ValidMoney -= Number * nowPrice; stockAccount.SumStockValue = nowPrice * Number; db.SimulationStocks.Add(simulationStock); db.Entry(stockAccount).State = EntityState.Modified; TradeHistory tradeHistory = new TradeHistory() { StockName = stockName, StockCode = StockCode, StockAccountId = stockAccount.Id, TransactionValue = nowPrice * Number, TransactionPrice = nowPrice, TransactionAmount = Number, TransactionType = Enums.TransactionType.买入, TradeTime = DateTime.Now }; db.TradeHistories.Add(tradeHistory); db.SaveChanges(); Thread.Sleep(1); } Thread.Sleep(1); } #pragma warning disable CS0168 // 声明了变量“ex”,但从未使用过 catch (Exception ex) #pragma warning restore CS0168 // 声明了变量“ex”,但从未使用过 { db.Entry(stockAccount).State = EntityState.Unchanged; return(ApiResponse.BadRequest("未找到数据")); } return(ApiResponse.Ok(new { simulationStock.BuyPrice, simulationStock.StockName, simulationStock.StockCode, simulationStock.StockNumber, StockSum = simulationStock.BuyPrice * simulationStock.StockNumber, stockAccount.ValidMoney, message = "您买入 " + simulationStock.StockName + "(" + simulationStock.StockCode + ") " + Number + "股" })); }
public IActionResult GetPositionList(long UserId) { StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); if (stockAccount == null) { return(Json(new { code = 400, message = "您还未激活账户,请先激活" })); } List <SimulationStock> simulationStocks = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList(); double Today_Profit_or_Loss = 0; if (simulationStocks.Count == 0) { return(Json(new { code = 200, stockAccount.SumMoney, stockAccount.ValidMoney, stockAccount.SumStockValue, Today_Profit_or_Loss = Math.Round(Today_Profit_or_Loss, 2), data = new string[] { } })); } else { string[] stockCodes = simulationStocks.Select(s => s.StockCode).ToArray(); StringBuilder request_string = new StringBuilder(); for (int i = 0; i < stockCodes.Length; i++) { if (i == stockCodes.Length - 1) { request_string.Append(stockCodes[i]); } else { request_string.Append(stockCodes[i] + ","); } } string res = new ShowApiRequest("http://route.showapi.com/131-46", "138438", "dd520f20268747d4bbda22ac31c9cbdf") .addTextPara("stocks", request_string.ToString()) .addTextPara("needIndex", "0") .post(); JObject jObject = JsonConvert.DeserializeObject <JObject>(res); JArray stockList = JArray.Parse(jObject["showapi_res_body"]["list"].ToString()); Double StockValue = 0; for (int i = 0; i < simulationStocks.Count; i++) { for (int j = 0; j < stockList.Count; j++) { if (simulationStocks[i].StockCode == stockList[j]["code"].ToString()) { simulationStocks[i].NowPrice = Double.Parse(stockList[j]["nowPrice"].ToString()); StockValue += Double.Parse(stockList[j]["nowPrice"].ToString()) * simulationStocks[i].StockNumber; Today_Profit_or_Loss += (simulationStocks[i].NowPrice - simulationStocks[i].BuyPrice) * simulationStocks[i].StockNumber; db.Entry(simulationStocks[i]).State = EntityState.Modified; db.SaveChanges(); } } } Thread.Sleep(1); try { stockAccount.SumMoney = StockValue + stockAccount.ValidMoney; stockAccount.SumStockValue = StockValue; stockAccount.Profit_or_Loss = Today_Profit_or_Loss; stockAccount.Rank = RankCalculation(UserId: UserId); db.Entry(stockAccount).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); } catch (Exception ex) { Console.WriteLine(ex.Message); db.Entry(stockAccount).State = EntityState.Unchanged; return(Json(new { code = 400, data = "糟糕,网络好像出问题了" })); } } return(Json(new { code = 200, SumMoney = Math.Round(stockAccount.SumMoney, 2), ValidMoney = Math.Round(stockAccount.ValidMoney, 2), SumStockValue = Math.Round(stockAccount.SumStockValue, 2), Today_Profit_or_Loss = Math.Round(Today_Profit_or_Loss, 2), data = simulationStocks.Select(s => new { s.Id, s.StockName, s.StockCode, Profit_or_Loss_Value = Math.Round(s.NowPrice - s.BuyPrice, 2).ToString(), Profit_or_Loss_Ratio = Math.Round((s.NowPrice - s.BuyPrice) / s.BuyPrice, 2).ToString() + "%", s.StockNumber, s.NowPrice }) })); }
public IActionResult GetHomePage(long UserId, long MyId) { User user = db.Users.FirstOrDefault(s => s.Id == UserId); IDatabase redisDatabase = RedisHelper.Value.Database; string TalkNumber_Key = "UserId=" + UserId.ToString() + "&TalkNumber"; ParamHelper paramHelper = new ParamHelper(); StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == user.Id); if (MyId == UserId) { return(Json(new { user.Id, user.Username, user.Remark, Gender = user.Gender.ToString(), StockAge = user.StockAge, user.ImageUrl, user.FansNumber, user.FollowNumber, user.CoinNumber, TalkNumber = redisDatabase.StringGet(TalkNumber_Key), SumMoney = stockAccount == null ? "0" : ParamHelper.ConvertNumber(stockAccount.SumMoney) })); } else { FollowRecord followRecord = db.FollowRecords.FirstOrDefault(s => s.FollowingId == MyId && s.FollowedId == UserId); if (followRecord == null) { return(Json(new { user.Id, user.Username, user.Remark, Gender = user.Gender.ToString(), StockAge = user.StockAge, user.ImageUrl, user.FansNumber, user.FollowNumber, user.CoinNumber, TalkNumber = redisDatabase.StringGet(TalkNumber_Key), SumMoney = stockAccount == null ? "0" : ParamHelper.ConvertNumber(stockAccount.SumMoney), If_Follow = "false" })); } else { return(Json(new { user.Id, user.Username, user.Remark, Gender = user.Gender.ToString(), StockAge = user.StockAge, user.ImageUrl, user.FansNumber, user.FollowNumber, user.CoinNumber, TalkNumber = redisDatabase.StringGet(TalkNumber_Key), SumMoney = stockAccount == null ? "0" : ParamHelper.ConvertNumber(stockAccount.SumMoney), If_Follow = "true" })); } } }
public PersonalAccount() { InitializeComponent(); SynchronizeAccount = Factory.LinkAccount(); }
// GET: /StockTrades/PurchaseStocks // Returns page to purchase stocks public ActionResult PurchaseStocks(int?StockID, int?Choice, int?AccountID) { // Check to see if any IDs are null if (StockID == null || Choice == null || AccountID == null) { return(HttpNotFound()); } // Get the users account // Query the Database for the logged in user var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); //Return frozen view if no go if (customer.ActiveStatus == false) { return(View("Frozen")); } // Get the Selected Stock StockMarket SelectedStock = db.StockMarket.Find(StockID); // Create a new model instance PurchaseStockTrade StockTrade = new PurchaseStockTrade { CustomerProfile = customer, SelectedStock = SelectedStock }; switch (Choice) { case 1: // Find the Checking Account Checking SelectedChecking = db.CheckingAccount.Find(AccountID); // Add to model StockTrade.CheckingAccounts = SelectedChecking; break; case 2: // Find the savings account Saving SelectedSavings = db.SavingsAccount.Find(AccountID); StockTrade.SavingsAccount = SelectedSavings; break; case 3: // Find the portfolio StockAccount SelectedStockAccount = db.StockAccount.Find(AccountID); StockTrade.AccountStock = SelectedStockAccount; break; default: return(HttpNotFound()); } return(View(StockTrade)); }
public dynamic GetStockAccount(String id) { StockAccount com = stocky.StockAccount.Where(e => e.Id == id).FirstOrDefault(); return(new StockAccountDto(com.Id, com.Status, com.SharesType, com.CurrentAmount, com.Beneficiary, com.ExpiredDate, com.ShareholderId, com.ShareTypeId)); }
public ActionResult PurchaseStocks(PurchaseStockTrade PurchcaseTrade) { try { // get the customer AppUser Customer = db.Users.Find(PurchcaseTrade.CustomerProfile.Id); if (Customer == null) { return(RedirectToAction("Portal", "Home")); } if (PurchcaseTrade.TradeDate < DateTime.Today || PurchcaseTrade.TradeDate == null) { ViewBag.Error = "Date cannot be before today"; return(View("PurchaseError")); } if (PurchcaseTrade.Quantity == 0) { ViewBag.Error = "Quantity cannot be 0"; return(View("PurchaseError")); } // Get the stock StockMarket SelectedStock = db.StockMarket.Find(PurchcaseTrade.SelectedStock.StockMarketID); // Get the total amount Decimal decTotal = (PurchcaseTrade.Quantity * SelectedStock.StockPrice); // create a new transaction list for the trade List <BankingTransaction> TradeTrans = new List <BankingTransaction>(); // Create a new fee transaction and add it to the list BankingTransaction FeeTrans = new BankingTransaction { Amount = SelectedStock.Fee, BankingTransactionType = BankingTranactionType.Fee, Description = ("Fee for purchase of " + SelectedStock.CompanyName), TransactionDate = (PurchcaseTrade.TradeDate), StockAccount = Customer.StockAccount.FirstOrDefault(), TransactionDispute = DisputeStatus.NotDisputed }; TradeTrans.Add(FeeTrans); // Make the trade happen Trade Trade = new Trade() { Amount = decTotal, Quantity = PurchcaseTrade.Quantity, Ticker = SelectedStock.Ticker, TransactionDate = PurchcaseTrade.TradeDate, PricePerShare = SelectedStock.StockPrice, TradeType = TradeType.Buy, StockAccount = Customer.StockAccount.FirstOrDefault(), StockMarket = SelectedStock, BankingTransactions = TradeTrans, DisputeMessage = "None", TransactionDispute = DisputeStatus.NotDisputed, Description = "None", CorrectedAmount = 0 }; // Get the customer Savings account var SAQ = from sa in db.StockAccount where sa.Customer.Id == Customer.Id select sa; StockAccount CustomerStockAccount = SAQ.FirstOrDefault(); // check the account nulls if (PurchcaseTrade.CheckingAccounts != null) { // find the account Checking CustomerChecking = db.CheckingAccount.Find(PurchcaseTrade.CheckingAccounts.CheckingID); if (CustomerChecking == null) { return(RedirectToAction("Portal", "Home")); } // take the money from the account if (CustomerChecking.Balance - decTotal >= 0) { // Check to see if the cash balance is enough for the fee if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee) { ViewBag.Error = "Fee was greater than Stock Cash Balance"; return(View("PurchaseError")); } // create a list to hold the checking account List <Checking> CheckingList = new List <Checking>(); CheckingList.Add(CustomerChecking); //Create a new transaction BankingTransaction CheckingTrans = new BankingTransaction { Amount = decTotal, BankingTransactionType = BankingTranactionType.Withdrawl, CheckingAccount = CheckingList, Description = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()), TransactionDate = PurchcaseTrade.TradeDate, Trade = Trade, TransactionDispute = DisputeStatus.NotDisputed }; // add the stuff to the database db.BankingTransaction.Add(FeeTrans); db.SaveChanges(); db.Trades.Add(Trade); db.SaveChanges(); // Take the money out db.CheckingAccount.Find(CustomerChecking.CheckingID).Balance -= decTotal; // take out the fee CustomerStockAccount.CashBalance -= SelectedStock.Fee; // take out the fee CustomerStockAccount.TradingFee += SelectedStock.Fee; db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified; db.BankingTransaction.Add(CheckingTrans); db.SaveChanges(); } // HACK else { ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks"; return(View("PurchaseError")); } // Any further changes } else if (PurchcaseTrade.SavingsAccount != null) { // Get the customer Savings account Saving CustomerSavings = db.SavingsAccount.Find(PurchcaseTrade.SavingsAccount.SavingID); // take the money from the account if (CustomerSavings.Balance - decTotal >= 0) { // Check to see if the cash balance is enough for the fee if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee) { ViewBag.Error = "Fee was greater than Stock Cash Balance"; return(View("PurchaseError")); } // create a list to hold the checking account List <Saving> SavingsList = new List <Saving>(); SavingsList.Add(CustomerSavings); //Create a new transaction BankingTransaction SavingsTrans = new BankingTransaction { Amount = decTotal, BankingTransactionType = BankingTranactionType.Withdrawl, SavingsAccount = SavingsList, Description = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()), TransactionDate = PurchcaseTrade.TradeDate, Trade = Trade, TransactionDispute = DisputeStatus.NotDisputed }; // add the stuff to the database db.BankingTransaction.Add(FeeTrans); db.SaveChanges(); db.Trades.Add(Trade); db.SaveChanges(); // Take the money out db.SavingsAccount.Find(CustomerSavings.SavingID).Balance -= decTotal; // take out the fee CustomerStockAccount.CashBalance -= SelectedStock.Fee; // take out the fee CustomerStockAccount.TradingFee += SelectedStock.Fee; db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified; db.BankingTransaction.Add(SavingsTrans); db.SaveChanges(); } // HACK else { ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks"; return(View("PurchaseError")); } } else if (PurchcaseTrade.AccountStock != null) { // take the money from the account if (CustomerStockAccount.CashBalance - decTotal >= 0) { // Check to see if the cash balance is enough for the fee if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee) { ViewBag.Error = "Fee was greater than Stock Cash Balance"; return(View("PurchaseError")); } // create a list to hold the checking account List <StockAccount> StockAccountList = new List <StockAccount>(); StockAccountList.Add(CustomerStockAccount); //Create a new transaction BankingTransaction StocksTrans = new BankingTransaction() { Amount = decTotal, BankingTransactionType = BankingTranactionType.Withdrawl, StockAccount = CustomerStockAccount, Description = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()), TransactionDate = PurchcaseTrade.TradeDate, Trade = Trade, TransactionDispute = DisputeStatus.NotDisputed }; // add the stuff to the database db.BankingTransaction.Add(FeeTrans); db.SaveChanges(); db.Trades.Add(Trade); db.SaveChanges(); // Take the money out CustomerStockAccount.CashBalance -= decTotal; // take out the fee CustomerStockAccount.CashBalance -= SelectedStock.Fee; // take out the fee CustomerStockAccount.TradingFee += SelectedStock.Fee; db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified; db.BankingTransaction.Add(StocksTrans); db.SaveChanges(); } // HACK else { ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks"; return(View("PurchaseError")); } } else { return(HttpNotFound()); } // Add the stuff to the database // check to see if the porfolio is balanced BalancedPortfolio.CheckBalanced(db, Customer); return(View("PurchaseConfirmation")); } catch (Exception e) { ViewBag.Error = "An unknown error occured"; return(View("PurchaseError")); } }
public ActionResult SellStocks(SellStocksTrade Sale) { // Get the Customer // Query the Database for the logged in user var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); //Return frozen view if no go if (customer.ActiveStatus == false) { return(View("Frozen")); } // Get the original trade Trade OriginalTrade = db.Trades.Find(Sale.TradeID); // Get the Stock that is being sold StockMarket StockSale = db.StockMarket.Find(Sale.StockMarketID); // Get the Stock Account StockAccount CustomerStockAccount = db.StockAccount.Find(Sale.StockAccountID); // create a new transaction list for the trade List <BankingTransaction> TradeTrans = new List <BankingTransaction>(); // Check the dates if (Sale.SaleDate < OriginalTrade.TransactionDate) { ViewBag.Error = "Cannot sell before purchase"; return(View("SaleError")); } if (Sale.QuantitySold == 0) { ViewBag.Error = "Cannot sell with zero quantity"; return(View("SaleError")); } // String for the description String Description = ($"Sale of {StockSale.CompanyName}, for {Sale.QuantitySold} shares, with initial price of {OriginalTrade.PricePerShare}, current price of {StockSale.StockPrice}, and a gain/loss of {Sale.Profit}"); // Sale Amount Decimal SaleAmount = (Sale.QuantitySold * StockSale.StockPrice); // Create a new fee transaction and add it to the list BankingTransaction FeeTrans = new BankingTransaction { Amount = StockSale.Fee, BankingTransactionType = BankingTranactionType.Fee, Description = ("Fee for sale of " + StockSale.CompanyName), StockAccount = CustomerStockAccount, TransactionDate = Sale.SaleDate, TransactionDispute = DisputeStatus.NotDisputed }; // Add the transaction to the list TradeTrans.Add(FeeTrans); // Make the trade happen Trade SaleTrade = new Trade() { TradeType = TradeType.Sell, Amount = (Sale.QuantitySold * StockSale.StockPrice), PricePerShare = StockSale.StockPrice, Ticker = StockSale.Ticker, Quantity = Sale.QuantitySold, TransactionDate = Sale.SaleDate, Description = Description, StockMarket = StockSale, StockAccount = CustomerStockAccount, BankingTransactions = TradeTrans, TransactionDispute = DisputeStatus.NotDisputed }; // Create a new transaction for the actual sale BankingTransaction SaleTrans = new BankingTransaction { Amount = SaleAmount, BankingTransactionType = BankingTranactionType.Deposit, Description = Description, StockAccount = CustomerStockAccount, Trade = SaleTrade, TransactionDate = Sale.SaleDate, TransactionDispute = DisputeStatus.NotDisputed }; // Add the transactions and the trades the the db db.BankingTransaction.Add(FeeTrans); db.SaveChanges(); db.Trades.Add(SaleTrade); db.SaveChanges(); db.BankingTransaction.Add(SaleTrans); db.SaveChanges(); // Update the stock account // Take out the fee CustomerStockAccount.CashBalance -= Sale.Fee; // Add the fee to the account CustomerStockAccount.TradingFee += Sale.Fee; // Add/Subtract the profit CustomerStockAccount.CashBalance += Sale.Profit; // Update the Database db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); // Remove the shares from the account // Check to see if there is any stock left // If there is no stock left then we need to remove the original buy trade if (OriginalTrade.Quantity - Sale.QuantitySold == 0) { // Clear the associated foriegn keys OriginalTrade.BankingTransactions.Clear(); // Remove the original trade db.Trades.Remove(OriginalTrade); } // If the original trade quantity is not zero else { // update the quantity OriginalTrade.Quantity -= Sale.QuantitySold; // update the database db.Entry(OriginalTrade).State = System.Data.Entity.EntityState.Modified; } // Save the changes db.SaveChanges(); // Check to see if the account is balanced BalancedPortfolio.CheckBalanced(db, customer); // Return users to the stock account details page return(RedirectToAction("Details", "StockAccounts")); }
public virtual void UpdateStockAccountInfo(StockAccount account) { throw new Exception("Not implement method"); }
public HttpResponseMessage SellStocks(long UserId, long SimulationStockId, int SellNumber) { User user = db.Users.FirstOrDefault(s => s.Id == UserId); StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); Double Initial_ValidMoney = stockAccount.ValidMoney; SimulationStock simulationStock = db.SimulationStocks.FirstOrDefault(s => s.Id == SimulationStockId); if (SellNumber > simulationStock.StockNumber) { return(ApiResponse.BadRequest("超过你的持股数量了")); } else { SellStock sellStock = new SellStock(); try { List <SimulationStock> simulationStocks = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList(); if (simulationStocks.Count > 0) { string[] stockCodes = simulationStocks.Select(s => s.StockCode).ToArray(); StringBuilder request_string = new StringBuilder(); for (int i = 0; i < stockCodes.Length; i++) { if (i == stockCodes.Length - 1) { request_string.Append(stockCodes[i]); } else { request_string.Append(stockCodes[i] + ","); } } string res = new ShowApiRequest("http://route.showapi.com/131-46", "138438", "dd520f20268747d4bbda22ac31c9cbdf") .addTextPara("stocks", request_string.ToString()) .addTextPara("needIndex", "0") .post(); JObject jObject = JsonConvert.DeserializeObject <JObject>(res); JArray jArray = JArray.Parse(jObject["showapi_res_body"]["list"].ToString()); for (int i = 0; i < simulationStocks.Count; i++) { for (int j = 0; j < jArray.Count; j++) { if (simulationStocks[i].StockCode == jArray[j]["code"].ToString()) { simulationStocks[i].NowPrice = Double.Parse(jArray[j]["nowPrice"].ToString()); db.Entry(simulationStocks[i]).State = EntityState.Modified; db.SaveChanges(); } } Thread.Sleep(1); } sellStock.SellPrice = simulationStock.NowPrice; sellStock.SellStockNumber = SellNumber; sellStock.BuyPrice = simulationStock.BuyPrice; sellStock.StockName = simulationStock.StockName; sellStock.StockCode = simulationStock.StockCode; sellStock.SellTime = DateTime.Now; sellStock.StockAccountId = stockAccount.Id; db.SellStocks.Add(sellStock); if (SellNumber == simulationStock.StockNumber) { simulationStock.StockNumber = 0; simulationStock.Valid = false; db.Entry(simulationStock).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); } else { simulationStock.StockNumber -= SellNumber; db.Entry(simulationStock).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); } try { double StockValue = 0; List <SimulationStock> last = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList(); foreach (var item in last) { StockValue += item.NowPrice * item.StockNumber; } StockAccount stockAccount2 = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); stockAccount2.SumStockValue = StockValue; db.Entry(stockAccount2).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); StockAccount stockAccount3 = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); stockAccount3.Profit_or_Loss += (sellStock.SellPrice - sellStock.BuyPrice) * SellNumber; stockAccount3.ValidMoney += sellStock.SellPrice * SellNumber; stockAccount3.SumMoney = Initial_ValidMoney + sellStock.SellPrice * SellNumber; db.Entry(stockAccount3).State = EntityState.Modified; Thread.Sleep(1); TradeHistory tradeHistory = new TradeHistory() { StockName = simulationStock.StockName, StockCode = simulationStock.StockCode, StockAccountId = stockAccount.Id, TransactionValue = sellStock.SellPrice * SellNumber, TransactionPrice = sellStock.SellPrice, TransactionAmount = SellNumber, TransactionType = Enums.TransactionType.卖出, TradeTime = DateTime.Now }; db.TradeHistories.Add(tradeHistory); db.SaveChanges(); } catch (Exception ex) { db.Entry(simulationStock).State = EntityState.Unchanged; db.Entry(stockAccount).State = EntityState.Unchanged; } } } catch (Exception ex) { return(ApiResponse.BadRequest("糟糕,网络好像出问题了")); } return(ApiResponse.Ok(new { sellStock.SellPrice, sellStock.SellStockNumber, sellStock.SellTime, sellStock.StockCode, sellStock.StockName, sellStock.BuyPrice, message = "您卖出 " + sellStock.StockName + "(" + sellStock.StockCode + ") " + sellStock.SellStockNumber + "股, " + "收益为¥" + (sellStock.SellPrice - sellStock.BuyPrice) * sellStock.SellStockNumber, })); } }
public HttpResponseMessage GetStockMainPage(long UserId) { User user = db.Users.FirstOrDefault(s => s.Id == UserId); StockAccount stockAccount = db.StockAccounts.FirstOrDefault(s => s.UserId == UserId); JArray stockList = null; if (stockAccount == null) { return(ApiResponse.BadRequest("建议您先开个户")); } else { List <SimulationStock> simulationStocks = db.SimulationStocks.Where(s => s.StockAccountId == stockAccount.Id && s.Valid == true).ToList(); if (simulationStocks.Count > 0) { string[] stockCodes = simulationStocks.Select(s => s.StockCode).ToArray(); StringBuilder request_string = new StringBuilder(); for (int i = 0; i < stockCodes.Length; i++) { if (i == stockCodes.Length - 1) { request_string.Append(stockCodes[i]); } else { request_string.Append(stockCodes[i] + ","); } } string res = new ShowApiRequest("http://route.showapi.com/131-46", "138438", "dd520f20268747d4bbda22ac31c9cbdf") .addTextPara("stocks", request_string.ToString()) .addTextPara("needIndex", "0") .post(); JObject jObject = JsonConvert.DeserializeObject <JObject>(res); stockList = JArray.Parse(jObject["showapi_res_body"]["list"].ToString()); Double SumStockValue = 0; for (int i = 0; i < simulationStocks.Count; i++) { for (int j = 0; j < stockList.Count; j++) { if (simulationStocks[i].StockCode == stockList[j]["code"].ToString()) { simulationStocks[i].NowPrice = Double.Parse(stockList[j]["nowPrice"].ToString()); SumStockValue += Double.Parse(stockList[j]["nowPrice"].ToString()) * simulationStocks[i].StockNumber; db.Entry(simulationStocks[i]).State = EntityState.Modified; db.SaveChanges(); } } Thread.Sleep(1); } stockAccount.SumStockValue = SumStockValue; stockAccount.SumMoney = SumStockValue + stockAccount.ValidMoney; db.Entry(stockAccount).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); try { stockAccount.Rank = RankCalculation(UserId: UserId); db.Entry(stockAccount).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); } catch (Exception ex) { Console.WriteLine(ex.Message); db.Entry(stockAccount).State = EntityState.Unchanged; return(ApiResponse.BadRequest("糟糕,网络好像出问题了")); } } else { try { stockAccount.Rank = RankCalculation(UserId: UserId); db.Entry(stockAccount).State = EntityState.Modified; db.SaveChanges(); Thread.Sleep(1); } catch (Exception ex) { Console.WriteLine(ex.Message); db.Entry(stockAccount).State = EntityState.Unchanged; return(ApiResponse.BadRequest("糟糕,网络好像出问题了")); } } Thread.Sleep(1); } return(ApiResponse.Ok(new { stockAccount.UserId, stockAccount.SumMoney, SumStockValue = ParamHelper.ConvertNumber(stockAccount.SumStockValue), stockAccount.ValidMoney, Profit_or_Loss = Math.Round(stockAccount.Profit_or_Loss, 2), stockAccount.Rank })); }
public ActionResult Portal() { var CustomerQuery = from c in db.Users where c.UserName == User.Identity.Name select c; // Get the Customer AppUser customer = CustomerQuery.FirstOrDefault(); if (customer == null) { return(HttpNotFound()); } // Find the Checking Accounts Associated var CheckingQuery = from ca in db.CheckingAccount where ca.Customer.Id == customer.Id select ca; // Convert to a list and execute List <Checking> CustomerCheckings = CheckingQuery.ToList(); // Loop through each checking account and change the account numbers // Only include the last 4 digits foreach (Checking account in CustomerCheckings) { account.AccountNumber = account.AccountNumber.Substring(6); } foreach (Checking account in CustomerCheckings) { if (account.Balance < 0) { account.Overdrawn = true; } } // Send to the Viewbag ViewBag.CheckingAccounts = CustomerCheckings; // Find the Savings Accounts Associated var SavingsQuery = from sa in db.SavingsAccount where sa.Customer.Id == customer.Id select sa; // Convert to a list and execute List <Saving> CustomerSavings = SavingsQuery.ToList(); // Loop through and extract only the last 4 digits of account number foreach (Saving account in CustomerSavings) { account.AccountNumber = account.AccountNumber.Substring(6); } ViewBag.SavingsAccounts = CustomerSavings; foreach (Saving account in CustomerSavings) { if (account.Balance < 0) { account.Overdrawn = true; } } // Find the IRA Accounts Associated var IRAQuery = from IR in db.IRAAccount where IR.Customer.Id == customer.Id select IR; List <IRA> CustomerIRA = IRAQuery.ToList(); // Loop through and set the account number to last 4 digits foreach (IRA account in CustomerIRA) { account.AccountNumber = account.AccountNumber.Substring(6); } foreach (IRA account in CustomerIRA) { if (account.Balance < 0) { account.Overdrawn = true; } } ViewBag.IRAAccounts = CustomerIRA; // Get the total value of the stock porfolio // Get the stock account var StockQuery = from sa in db.StockAccount where sa.Customer.Id == customer.Id select sa; StockAccount CustomerSA = StockQuery.FirstOrDefault(); if (CustomerSA != null) { /* Variable to hold the total amount * Decimal StockAccountValue = 0; * * foreach (Trade t in CustomerSA.Trades.Where(i => i.TradeType == TradeType.Buy)) * { * StockAccountValue += (t.Quantity * t.PricePerShare); * } * * StockAccountValue += CustomerSA.CashBalance; * */ if (CustomerSA.CashBalance < 0) { CustomerSA.Overdrawn = true; } CustomerSA.AccountNumber = CustomerSA.AccountNumber.Substring(6); // Add to the view bag ViewBag.StockAccountValue = (CustomerSA.CashBalance + CustomerSA.StockBalance); } else { // Add to the view bag ViewBag.StockAccountValue = 0; } // check to make the customer has created an account if (CustomerCheckings.Count == 0 && CustomerIRA.Count == 0 && CustomerSavings.Count == 00 && CustomerSA == null) { // redirect the user to the create an account page return(RedirectToAction("Create", "Home")); } return(View(customer)); }