/// <summary> /// Resets the right sidebar with its details /// </summary> private void cleanRightSidebar() { foreach (Control groupBox in panelRight.Controls) { if (groupBox is GroupBox) { foreach (Control x in groupBox.Controls) { if (x is Label && ((Label)x).Name.Contains("Input")) { x.Text = "..."; } else if (x is Panel) { foreach (Control y in x.Controls) { if (y is Label && ((Label)y).Name.Contains("Input")) { y.Text = "..."; } } } } } } gbDetails.Text = "Wertpapier"; selectedStock = null; nupQuantity.Value = 0; }
/// <summary> /// updates the latest stock prices in listview /// </summary> private async void updateStockPricesInListView() { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Aktuellste Wertpapierdaten werden abgefragt..."); for (int i = 0; i < lvWatchlist.Items.Count; i++) { StockListitem slItem = (StockListitem)lvWatchlist.Items[i].Tag; FinanceAPI rest = new FinanceAPI(webFinanceStrategy, slItem.symbol); Task <SingleQuote> taskStockData = Task.Run(() => rest.getLatestQuote()); SingleQuote stockData = await taskStockData; if (stockData != null) { if (webFinanceStrategy == FinanceAPI.FinanceStrategies.Yahoo) { var yahooStock = (YahooSingleQuote)stockData; slItem.BookValue = yahooStock.BookValue; slItem.MarketCapitalization = yahooStock.MarketCapitalization; slItem.FiftydayMovingAverage = yahooStock.FiftydayMovingAverage; slItem.TwoHundreddayMovingAverage = yahooStock.TwoHundreddayMovingAverage; } slItem.Change = stockData.Change; slItem.PriceCurrent = Convert.ToDouble(stockData.CurrentPrice); lvWatchlist.Items[i] = new ListViewItem(slItem.toStringArray(webFinanceStrategy)); lvWatchlist.Items[i].Tag = slItem; } } mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); }
/// <summary> /// Deletes stock-watchlist mapping /// </summary> /// <param name="item">WatchlistStock entity</param> public void deleteStockFromWatchlist(StockListitem item) { if (ConnectionState == true) { if (item.StockID == 0) { var a = checkExistingStocksItem(item); item.StockID = a.StockID; } var sequenzT = (from mp in db.UserLines where mp.StocksMapID == item.StocksMapID select mp); db.UserLines.DeleteAllOnSubmit(sequenzT); db.SubmitChanges(); var sequenz = (from mp in db.StocksMap where mp.Category == 'w' where mp.StocksMapID == item.StocksMapID select mp); if (sequenz.Any() && sequenz.First() != null) { db.StocksMap.DeleteOnSubmit(sequenz.First()); db.SubmitChanges(); } } }
public StockChartView(StockListitem stock, FinanceAPI.FinanceStrategies webFinanceStrategy) { InitializeComponent(); this.stock = stock; this.webFinanceStrategy = webFinanceStrategy; setParameters(); drawChartAsync(); getAllLinesAsync(); }
/// <summary> /// Draws the chart for stock /// </summary> private void drawChart(StockListitem stockItem = null) { panelChart.Controls.Clear(); if (stockItem != null) { MoneyMakerView view = new StockChartView(stockItem, webFinanceStrategy, startDate, endDate); view.Dock = DockStyle.Fill; panelChart.Controls.Add(view); } }
public StockChartView(StockListitem stock, FinanceAPI.FinanceStrategies webFinanceStrategy, DateTime startDate, DateTime endDate) { InitializeComponent(); this.stock = stock; this.webFinanceStrategy = webFinanceStrategy; this.startDate = startDate; this.endDate = endDate; setParameters(); drawChartAsync(); getAllLinesAsync(); }
public static string toPriceFormat(this StockListitem quote, decimal?value) { if (value != null) { return(((double)value).ToString("0.00") + " " + quote.Currency.Symbol); } else { return("0.00" + quote.Currency.Symbol); } }
/// <summary> /// Check if the stock already exists /// </summary> /// <param name="stock">the stock data to check</param> /// <returns>Stocks database entity</returns> private Stocks checkExistingStocksItem(StockListitem stock) { Stocks result = null; if (ConnectionState == true) { result = (from st in db.Stocks where st.Symbol == stock.symbol select st).FirstOrDefault(); } return(result); }
/// <summary> /// Stores the stock to database if bank has money /// </summary> private async void saveStockAsync(StockListitem watchlistStock) { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Wertpapier wird gekauft..."); FinanceAPI rest = new FinanceAPI(webFinanceStrategy, watchlistStock.symbol); Task <SingleQuote> taskStockData = Task.Run(() => rest.getLatestQuote()); stockLatestPrice = await taskStockData; if (stockLatestPrice != null) { watchlistStock.PurchaseDate = DateTime.Now; watchlistStock.PricePurchase = stockLatestPrice.CurrentPrice; watchlistStock.PriceCurrent = (double)stockLatestPrice.CurrentPrice; if (webFinanceStrategy == FinanceAPI.FinanceStrategies.Yahoo) { var yahooStock = stockLatestPrice as YahooSingleQuote; watchlistStock.BookValue = yahooStock.BookValue; watchlistStock.MarketCapitalization = yahooStock.MarketCapitalization; watchlistStock.FiftydayMovingAverage = yahooStock.FiftydayMovingAverage; watchlistStock.TwoHundreddayMovingAverage = yahooStock.TwoHundreddayMovingAverage; } decimal totalSum = Convert.ToDecimal(watchlistStock.PriceCurrent * watchlistStock.Quantity); var bank = bankModel.getBank(); if (totalSum <= bank.AccountBalance) { Task <int> insertTask = Task.Run(() => depotModel.insertStockToDepot(watchlistStock)); int id = await insertTask; if (id > 0) { depotModel.saveTransaction(TransactionItem.TransactionTypeEnum.Purchase, watchlistStock); watchlistStock.StocksMapID = id; // Add to listview var lvItem = new ListViewItem(watchlistStock.toStringArray()); lvItem.Tag = watchlistStock; lvDepot.Items.Add(lvItem); // Draw Chart selectedStock = watchlistStock; loadChartDataAsync(selectedStock); } } else { MessageBox.Show("Nicht genügend Geld auf der Bank"); } } mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); }
/// <summary> /// Additional stock data (book value, market capilization, etc.) /// </summary> private void additionalStockData(StockListitem selectedStock) { if (selectedStock != null) { int height = 30; var fullHeight = (height) * 4; if (gbDetails.Controls.ContainsKey("pnDetailsAdditional")) { gbDetails.Controls.RemoveByKey("pnDetailsAdditional"); gbDetails.Size = new Size(gbDetails.Size.Width, (gbDetails.Size.Height - fullHeight)); pnDetails.Location = new Point(pnDetails.Location.X, pnDetails.Location.Y - fullHeight); gbBestand.Location = new Point(gbBestand.Location.X, gbBestand.Location.Y - fullHeight); gbPurchaseData.Location = new Point(gbPurchaseData.Location.X, gbPurchaseData.Location.Y - fullHeight); } if (webFinanceStrategy == FinanceAPI.FinanceStrategies.Yahoo) { var topControl = pnDetails.Location; // Make box bigger gbDetails.Size = new Size(gbDetails.Size.Width, (gbDetails.Size.Height + fullHeight)); pnDetails.Location = new Point(pnDetails.Location.X, pnDetails.Location.Y + fullHeight); gbBestand.Location = new Point(gbBestand.Location.X, gbBestand.Location.Y + fullHeight); gbPurchaseData.Location = new Point(gbPurchaseData.Location.X, gbPurchaseData.Location.Y + fullHeight); string[] additionalStockDataLabel = { "Buchwert", "Marktkap.", "50-Tage", "250-Tage" }; string[] additionalStockData = { selectedStock.BookValue.ToString(), selectedStock.MarketCapitalization, selectedStock.FiftydayMovingAverage.ToString(), selectedStock.TwoHundreddayMovingAverage.ToString() }; Panel pnDetailsAdditional = new Panel(); pnDetailsAdditional.Name = "pnDetailsAdditional"; pnDetailsAdditional.Location = new Point(10, topControl.Y + 7); pnDetailsAdditional.Size = new Size(216, fullHeight); gbDetails.Controls.Add(pnDetailsAdditional); for (int i = 0; i < 4; i++) { Label labelInfo = new Label(); labelInfo.Size = new Size(60, height); labelInfo.Text = additionalStockDataLabel[i]; labelInfo.Location = new Point(0, (height * i)); Label labelBox = new Label(); labelBox.Text = additionalStockData[i]; labelBox.Size = new Size(90, height); labelBox.Location = new Point(67, (height * i)); pnDetailsAdditional.Controls.Add(labelInfo); pnDetailsAdditional.Controls.Add(labelBox); } } } }
/// <summary> /// Inserts stock into database and maps with watchlist /// </summary> /// <param name="stock">the stock data</param> public int insertStockToDepot(StockListitem stock) { int insertID = 0; if (ConnectionState == true) { // Stock exists? Stocks existingItem = null; // Non existing, then insert if (db.Stocks.Any()) { existingItem = db.Stocks.Where(st => st.Symbol == stock.symbol).SingleOrDefault(); db.SubmitChanges(); } if (existingItem == null) { db.Stocks.InsertOnSubmit(new Stocks { Symbol = stock.symbol, Name = stock.name, StockExchange = stock.exch, Typ = stock.typeDisp }); db.SubmitChanges(); existingItem = db.Stocks.FirstOrDefault(st => st.Symbol == stock.symbol); } int stockID = existingItem.StockID; var stocksMap = new StocksMap { Category = 'd', CategoryID = stock.CategoryID, StockID = stockID, Quantity = stock.Quantity, PurchaseDate = DateTime.Now, PurchasePrice = Convert.ToDecimal(stock.PricePurchase), }; // Map stock with watchlist db.StocksMap.InsertOnSubmit(stocksMap); db.SubmitChanges(); insertID = stocksMap.StocksMapID; } return(insertID); }
/// <summary> /// Selects the stock which the user searched for /// </summary> private void btnGetStock_Click(object sender, EventArgs e) { ComboBox cbMultiLine = stockSearchView.SearchBox; StockListitem watchlistStock = new StockListitem(); YahooStockSearchResult selectedItem = (YahooStockSearchResult)cbMultiLine.SelectedItem; // Add Stock to List if (selectedItem != null) { watchlistStock = depotModel.buildWatchlistStockItem(selectedItem, nupStockQuantity.Value); selectedStock = watchlistStock; makeBuyProposition(); } }
/// <summary> /// Prepares data for stock chart and detail view /// </summary> private async void loadChartDataAsync(StockListitem selectedItem = null) { if (selectedItem != null) { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Wertpapierdaten für " + selectedItem.name + " werden abgefragt..."); FinanceAPI rest = new FinanceAPI(webFinanceStrategy, selectedItem.symbol); drawChart(selectedItem); Task <SingleQuote> taskStockData = Task.Run(() => rest.getLatestQuote()); stockLatestPrice = await taskStockData; fillRightSidebarWithData(); mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); } }
/// <summary> /// Adds stock to watchlist /// </summary> private void btnAddStock_Click(object sender, EventArgs e) { ComboBox cbMultiLine = stockSearchView.SearchBox; StockListitem watchlistStock = new StockListitem(); YahooStockSearchResult selectedItem = (YahooStockSearchResult)cbMultiLine.SelectedItem; // Add Stock to List if (selectedItem != null) { watchlistStock = model.buildWatchlistStockItem(watchlist.WatchListID, selectedItem, nupStockQuantity.Value); // Save to data insertStockAsync(watchlistStock); updateStockPricesInListView(); } }
/// <summary> /// Inserts stock into database and maps with watchlist /// </summary> /// <param name="stock">the stock data</param> public int insertStockToWatchlist(StockListitem stock) { int insertID = 0; if (ConnectionState == true) { // Stock exists? Stocks existingItem; // Non existing, then insert existingItem = checkExistingStocksItem(stock); if (existingItem == null) { db.Stocks.InsertOnSubmit(new Stocks { Symbol = stock.symbol, Name = stock.name, StockExchange = stock.exch, Typ = stock.typeDisp }); db.SubmitChanges(); existingItem = checkExistingStocksItem(stock); } int stockID = existingItem.StockID; var stocksMap = new StocksMap { Category = 'w', CategoryID = stock.CategoryID, StockID = stockID, Quantity = stock.Quantity, PurchaseDate = DateTime.Now, PurchasePrice = Convert.ToDecimal(stock.PricePurchase), }; // Map stock with watchlist db.StocksMap.InsertOnSubmit(stocksMap); db.SubmitChanges(); insertID = stocksMap.StocksMapID; } return(insertID); }
/// <summary> /// Changes the selected item /// </summary> private void lvDepot_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point mousePos = lvDepot.PointToClient(Control.MousePosition); ListViewHitTestInfo hitTest = lvDepot.HitTest(mousePos); var firstSelected = hitTest.Item; if (firstSelected?.Tag != null) { selectedStock = (StockListitem)firstSelected.Tag; loadChartDataAsync(selectedStock); } else { cleanRightSidebar(); } } }
/// <summary> /// prepares data for stock chart and detail view /// </summary> private async void loadChartDataAsync(StockListitem selectedItem) { if (selectedItem != null) { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Chart wird gezeichnet..."); FinanceAPI rest = new FinanceAPI(webFinanceStrategy, selectedItem.symbol); drawChart(selectedItem); Task <SingleQuote> taskStockData = Task.Run(() => rest.getLatestQuote()); stockLatestPrice = await taskStockData; if (stockLatestPrice != null) { fillRightSidebarWithData(); additionalStockData(selectedItem); mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); } } }
/// <summary> /// Inserts the stock to the watchlist /// </summary> private async void insertStockAsync(StockListitem watchlistStock) { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Aktie wird gespeichert..."); FinanceAPI rest = new FinanceAPI(webFinanceStrategy, watchlistStock.symbol); Task <SingleQuote> taskStockData = Task.Run(() => rest.getLatestQuote()); stockLatestPrice = await taskStockData; if (stockLatestPrice != null) { watchlistStock.Change = stockLatestPrice.Change; watchlistStock.PurchaseDate = DateTime.Now; watchlistStock.PricePurchase = stockLatestPrice.CurrentPrice; watchlistStock.PriceCurrent = Convert.ToDouble(stockLatestPrice.CurrentPrice); watchlistStock.StocksMapID = model.insertStockToWatchlist(watchlistStock); if (webFinanceStrategy == FinanceAPI.FinanceStrategies.Yahoo) { var yahooStock = stockLatestPrice as YahooSingleQuote; watchlistStock.BookValue = yahooStock.BookValue; watchlistStock.MarketCapitalization = yahooStock.MarketCapitalization; watchlistStock.FiftydayMovingAverage = yahooStock.FiftydayMovingAverage; watchlistStock.TwoHundreddayMovingAverage = yahooStock.TwoHundreddayMovingAverage; } selectedStock = watchlistStock; loadChartDataAsync(watchlistStock); // Add to listview var lvItem = new ListViewItem(watchlistStock.toStringArray()); lvItem.Tag = watchlistStock; lvWatchlist.Items.Add(lvItem); } else { MessageBox.Show("Es konnten keine Preisinformationen für das Wertpapier gefunden werden."); } mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); }
/// <summary> /// Removes stock from watchlist /// </summary> private async void btnDeleteStock_Click(object sender, EventArgs e) { btnDeleteStock.Visible = false; if (lvWatchlist.SelectedItems.Count > 0) { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Wertpapiere werden aus der Watchlist entfernt..."); var selected = lvWatchlist.SelectedItems; foreach (ListViewItem item in selected) { StockListitem wls = (StockListitem)item.Tag; Task task = Task.Run(() => model.deleteStockFromWatchlist(wls)); await task; } selectedStock = null; refreshWatchlistDataAsync(); cleanRightSidebar(); panelChart.Controls.Clear(); mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); } }
/// <summary> /// Saves the transaction (purchase or sale) /// </summary> /// <param name="type">The transaction type : s(ales), c(harge), t(akeoff), p(urchase)</param> /// <param name="stock">the stock data</param> public void saveTransaction(TransactionItem.TransactionTypeEnum type, StockListitem stock) { BankAccountModel bankModel = new BankAccountModel(); var bank = bankModel.getBank(); var ttype = (type == TransactionItem.TransactionTypeEnum.Purchase) ? 'p' : 's'; var totalSum = (decimal)stock.PricePurchase * (decimal)stock.Quantity; if (ConnectionState == true && bank != null) { if (totalSum <= bank.AccountBalance) { decimal change = 0; switch (type) { case TransactionItem.TransactionTypeEnum.Sales: change += totalSum; break; case TransactionItem.TransactionTypeEnum.Purchase: change -= totalSum; break; } var bankQuery = (from bk in db.BankAccount where bk.BankAccountID == bank.BankAccountID select bk).First(); bankQuery.AccountBalance += change; db.SubmitChanges(); db.Transactions.InsertOnSubmit(new Transactions { Description = stock.Quantity + " - " + stock.name, BankAccountID = bank.BankAccountID, Created = DateTime.Now, Amount = totalSum, TransactionType = ttype, }); db.SubmitChanges(); } } }
/// <summary> /// Default constructor /// </summary> public UserlineModel(StockListitem stock, Color lineColor = default(Color), int lineThickness = 1) { this.stock = stock; this.lineColor = lineColor; this.lineThickness = lineThickness; }
/// <summary> /// Sales the stock and saves the transaction /// </summary> public void removeStock(StockListitem stock, decimal quantity) { if (ConnectionState == true) { var query = (from ds in db.StocksMap where ds.StocksMapID == stock.StocksMapID select ds).FirstOrDefault(); if (query != null) { if (quantity < stock.Quantity) { query.Quantity -= (int)quantity; } else if (quantity == stock.Quantity) { db.UserLines.DeleteAllOnSubmit(query.UserLines); db.StocksMap.DeleteOnSubmit(query); } db.SubmitChanges(); BankAccountModel bankModel = new BankAccountModel(); var bank = bankModel.getBank(); var valueBought = quantity * query.PurchasePrice; var valueSold = quantity * Convert.ToDecimal(stock.PriceCurrent); db.Transactions.InsertOnSubmit(new Transactions { Description = quantity + " - " + stock.name, BankAccountID = bank.BankAccountID, Created = DateTime.Now, Amount = valueSold, TransactionType = 's', }); var capitalGainTax = SettingsModel.getInstance().getCapitalGainTax(); if (capitalGainTax > 0) { decimal valueTax = 0; var taxType = ""; char taxTransType = 'x'; if (valueSold > valueBought) // Profit { valueTax = Convert.ToDecimal(valueSold - valueBought) * (capitalGainTax / 100); taxType = "Kapitalerstragssteuer nach Verkauf - " + stock.name; } else if (valueSold < valueBought) // Loss { valueTax = Convert.ToDecimal(valueBought - valueSold) * (capitalGainTax / 100); taxType = "Steuergutschrift durch Verkauf - " + stock.name; taxTransType = 'y'; } db.Transactions.InsertOnSubmit(new Transactions { Description = taxType, BankAccountID = bank.BankAccountID, Created = DateTime.Now, Amount = valueTax, TransactionType = taxTransType, }); } db.SubmitChanges(); } } }
/// <summary> /// updates the latest stock prices in listview /// </summary> private async void updateStockPricesInListViewAsync() { mainForm.notifyUser(FrmMain.NotifyType.PrepareMessage, "Wertpapierdaten werden aktualisiert..."); double depotCurrent = 0.00; double depotStart = 0.00; for (int i = 0; i < lvDepot.Items.Count && lvDepot.Items.Count > 0; i++) { StockListitem slItem = (StockListitem)lvDepot.Items[i].Tag; FinanceAPI rest = new FinanceAPI(webFinanceStrategy, slItem.symbol); Task <SingleQuote> taskStockData = Task.Run(() => rest.getLatestQuote()); SingleQuote stockData = await taskStockData; if (stockData != null && null != lvDepot.Items[i]) { if (webFinanceStrategy == FinanceAPI.FinanceStrategies.Yahoo) { var yahooStock = (YahooSingleQuote)stockData; slItem.BookValue = yahooStock.BookValue; slItem.MarketCapitalization = yahooStock.MarketCapitalization; slItem.FiftydayMovingAverage = yahooStock.FiftydayMovingAverage; slItem.TwoHundreddayMovingAverage = yahooStock.TwoHundreddayMovingAverage; } slItem.Change = stockData.Change; slItem.PriceCurrent = Convert.ToDouble(stockData.CurrentPrice); lvDepot.Items[i] = new ListViewItem(slItem.toStringArray(webFinanceStrategy)); lvDepot.Items[i].Tag = slItem; if (slItem.Currency.ShortCode == defaultCurrency) { depotCurrent += (double)slItem.PriceCurrent * (double)slItem.Quantity; depotStart += (double)slItem.PricePurchase * (double)slItem.Quantity; } else { string currencyPair = "" + slItem.Currency.ShortCode + defaultCurrency; if (!currencyRates.ContainsKey(currencyPair)) { Task <CurrencyRate> taskCurrencyData = Task.Run(() => new FinanceAPI(webFinanceStrategy, currencyPair).getCurrencyRate()); CurrencyRate currencyRate = await taskCurrencyData; if (currencyRate != null) { depotCurrent += (double)slItem.PriceCurrent * (double)slItem.Quantity * currencyRate.Rate; depotStart += (double)slItem.PricePurchase * (double)slItem.Quantity * currencyRate.Rate; currencyRates.Add(currencyPair, currencyRate.Rate); } } else { depotCurrent += (double)slItem.PriceCurrent * (double)slItem.Quantity * currencyRates[currencyPair]; depotStart += (double)slItem.PricePurchase * (double)slItem.Quantity * currencyRates[currencyPair]; } } } } lblDepotCurrent.Text = depotCurrent.ToString("0.00"); lblDepotStart.Text = depotStart.ToString("0.00"); calculateDepotChanges(); mainForm.notifyUser(FrmMain.NotifyType.StatusMessage); }
public static string toPriceFormat(this StockListitem quote, double value) { return(value.ToString("0.00") + " " + quote.Currency.Symbol); }