public static void insertTrade(Trade trade)
 {
     int nextLine = System.IO.File.ReadLines(filePath).Count() + 1;
     System.IO.StreamWriter file = new System.IO.StreamWriter(filePath,true);
     
     file.WriteLine(nextLine + "\t" + 
         DateTime.Now + "\t" + 
         trade.quantityShares  + "\t" +  
         trade.type  + "\t" + 
         trade.price);
     file.Close();
 }
 public bool RecordTrade(Trade trade)
 {
     try
     {
         Trades.Add(trade);
     }
     catch (Exception ex)
     {
         Log.ErrorFormat(Properties.Resources.SUPERSIMPLESTOCKS_ERR_004, trade, ex.Message);
         return false;
     }
     return true;
 }
        /// <summary>
        /// Perform trade on stock exchange.
        /// </summary>
        /// <returns>List of performed trades.</returns>
        public List<Trade> Trade()
        {
            var rand = new Random();
            var tradesCount = rand.Next((int)(EndTime - StartTime).TotalSeconds);
            var tradePeriod = (EndTime - StartTime).TotalSeconds / tradesCount;

            var trades = new List<Trade>();
            for (int i = 0; i < tradesCount; i++)
            {
                var stock = Stocks.ElementAt(rand.Next(Stocks.Count));

                var tradeAction = (rand.NextDouble() >= 0.5) ? TradeAction.Buy : TradeAction.Sell;
                var price = stock.ParValue*(decimal) 0.5 +
                            (decimal) (rand.NextDouble()*(double) (stock.ParValue*2 - stock.ParValue*(decimal) 0.5));
                var quantity = rand.Next(1, 1000);
                var tradeTime = StartTime.AddSeconds(i*tradePeriod);
                var trade = new Trade(stock, tradeTime, quantity, tradeAction, price);
                
                trades.Add(trade); 
            }
            return trades;
        }
        static void Main(string[] args)
        {
            try
            {
                // Read Stock Sample Data
                string filePath = "./resources/data/stocks_sample_data.csv";
                CsvReader csvR = new CsvReader(new StreamReader(filePath));
                csvR.Configuration.RegisterClassMap<StockCsvMap>();
                TradeOperations.Stocks = csvR.GetRecords<Stock>().ToList();
                csvR.Dispose();

                // Print sample data
                Console.WriteLine("** Stock Sample Data **");
                foreach (var stock in TradeOperations.Stocks)
                    Console.WriteLine(stock);
                Console.WriteLine();

                // Create a pseudo-rand generator to generate trades
                Random rand = new Random(117);

                // Create a DateTime
                DateTime date = new DateTime(2016, 01, 01, 13, 00, 00, 00);

                // Get Indicators
                Array indicators = Enum.GetValues(typeof(Trade.Indicators));

                // Initialize TradeOperations
                ITradeOperations tradeOperations = new TradeOperations();
                // Create 1000 trade operations with randoms
                Console.WriteLine("** Trade Operations **");
                for (int i = 0; i < 1000; i++)
                {
                    // Add random seconds to a date
                    date = date.AddSeconds(rand.Next(1, 120));
                    // Create a trade with randoms
                    Trade trade = new Trade
                    {
                        Indicator = indicators.GetValue(rand.Next(0, indicators.Length)).ToString(),
                        Price = rand.Next(1, 10000) / 100.0,
                        Quantity = rand.Next(1, 1000),
                        Stock = TradeOperations.Stocks.ElementAt(rand.Next(0, TradeOperations.Stocks.Count)),
                        Timestamp = date
                    };

                    // Print the trade with calculated Dividend Yeld and P/E Ratio
                    Console.WriteLine(string.Format("Trade [{0}]: {1}; Dividend Yeld [{2:0.##}], P/E Ratio [{3:0.##}]",
                        i + 1, trade, trade.DividendYeld(), trade.PERatio()));

                    // Record the trade in the list of trades
                    tradeOperations.RecordTrade(trade);

                    // Print Stock Prices
                    StringBuilder sb = new StringBuilder("\tStock Prices: ");
                    foreach (Stock stock in TradeOperations.Stocks)
                        sb.Append(string.Format("[{0} = {1:0.##}]\t", stock.StockSymbol, tradeOperations.StockPrice(stock.StockSymbol)));
                    Console.WriteLine(sb);

                    // Print GBCE All Share Index
                    Console.WriteLine(string.Format("\tGBCE All Share Index = [{0:0.##}]", tradeOperations.StocksGeometricMean()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            ConsoleKeyInfo op;
            
            do
            {
                Console.Clear(); 
                Console.WriteLine("\nSuperSimpleStocks Application - by Ion Ruiz Iragui\n");
                ShowAll();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("\t[A] Calculate the dividend yield\n");
                Console.Write("\t[B] Calculate the P/E Ratio\n");
                Console.Write("\t[C] Record a trade\n");
                Console.Write("\t[D]. Calculate Stock Price based on trades recorded in the last X\n");
                Console.Write("\t[E]. Calculate the GBCE All Share Index\n");
                Console.Write("\t[Esc] Exit\t\n\n");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Select an option...");
                op = Console.ReadKey(true);
                
                switch (op.Key)
                {
                    case ConsoleKey.A:
                        Console.Clear(); 
                        Console.WriteLine("\nSuperSimpleStocks Application - by Ion Ruiz Iragui\n\n");
                        ShowAll();
                        Console.WriteLine("[A]. Calculate the dividend yield: Type the SymbolCode:");
                        String choice1 = Console.ReadLine();                 
                        Console.WriteLine("\nThe dividend yield of " +
                            choice1 + ": " + BLL.calculateDividendYield(choice1));
                        Console.Write("Press any key to continue...");
                        Console.ReadKey();
                        break;

                    case ConsoleKey.B:
                        Console.Clear(); 
                        Console.WriteLine("\nSuperSimpleStocks Application - by Ion Ruiz Iragui\n\n");
                        ShowAll();
                        Console.WriteLine("[B]. Calculate the P/E Ratio");
                        String choice2 = Console.ReadLine();                 
                        Console.WriteLine("\nThe dividend yield of " +
                            choice2 + ": " + BLL.PERatio(choice2));
                        Console.Write("Press any key to continue...");
                        Console.ReadKey();
                        break;

                    case ConsoleKey.C:
                        Console.Clear(); 
                        Console.WriteLine("\nSuperSimpleStocks Application - by Ion Ruiz Iragui\n\n");
                        ShowAll();
                        Console.WriteLine("[C]. Record a trade");
                        Console.Write("Insert the Quantity: ");
                        String quantity = Console.ReadLine();
                        Console.Write("Insert the Type (B)uy/(S)ell): ");
                        String type = Console.ReadLine();
                        Console.Write("Insert the Price (decimals with comma): ");
                        String price = Console.ReadLine();
                        Trade trade = new Trade(quantity,type,price);
                        BLL.insertTrade(trade);
                        Console.WriteLine("\n\nInsertion completed!!");
                        Console.Write("Press any key to continue...");
                        Console.ReadKey();
                        break;

                    case ConsoleKey.D:
                        Console.WriteLine("[D]. Calculate Stock Price based on trades recorded in the last X");
                        Console.Write("Mins Lapse: ");
                        String timeInMins = Console.ReadLine();
                        Double stockPrice = BLL.LastMinsTrades(int.Parse(timeInMins));
                        Console.WriteLine("\nStock Price of the last " + timeInMins + " minutes: " + stockPrice);
                        Console.Write("Press any key to continue...");
                        Console.ReadKey();
                        break;

                    case ConsoleKey.E:
                        Console.WriteLine("[E]. Calculate the GBCE All Share Index");
                        Double GBCE = BLL.CalculateGBCE();
                        Console.WriteLine("\nGBCE All Share Index: " + GBCE);
                        Console.Write("Press any key to continue...");
                        Console.ReadKey();
                        break;

                    case ConsoleKey.Escape:
                        Console.WriteLine("Chao");

                        break;
                }
            } while (op.Key != ConsoleKey.Escape);
        }