<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;
using System.Diagnostics;
/****** Available functions to call ***********
string getAnnualizedGain(string symbol)
string getExchange(string symbol)
double getChange(string symbol)
string getChangeInPercent(string symbol)
double getStockYearHigh(string symbol)
double getStockYearLow(string symbol)
string getCompanyName(string symbol)
double getLatestValue(string symbol)
*/
namespace stockme
{
    class Program
    {
        static void Main(string[] args)
        {
            const int NUM_THREADS = 8; //reccomended 36 symbols per thread
            ArrayList arList = new ArrayList();
            ArrayList qrResults;
            Stopwatch sw = new Stopwatch();
            // (284 * 2) symbols is suggested for stress test.
            arList.Add("goog"); arList.Add("A"); arList.Add("AA"); arList.Add("AA-B"); arList.Add("HBI"); arList.Add("HCN"); arList.Add("HE"); arList.Add("HF");
            //ThreadStockerWrapper(threads,function_name,stocknames_arraylist);
            ThreadStockWrapper Stocker = new ThreadStockWrapper(NUM_THREADS, "getLatestValue", arList); //see available functions above to call.
            sw.Start();
            qrResults = Stocker.threadStockCall(); // returns back a QuerryResults ArrayList();
            sw.Stop();
            foreach (QueryResults qr in qrResults)
            {
                if (qr.isString)
                {
                    Console.WriteLine(qr.sSymbol + " " + qr.sResult + " " + qr.sQuery);
                }
                else
                { //results have a double instead.
                    Console.WriteLine(qr.sSymbol + " " + qr.dResult + " " + qr.sQuery);
                }
            }
            Console.WriteLine("Elapsed Miliseconds " + sw.ElapsedMilliseconds);
        }
    }
    /*begin Class QueryResults ***** brandon ****/
    class QueryResults
    {
        private string symbol, str_result, query;
        private double dbl_result;
        private bool bIsStr; // is the result a string.. if false it is a double.
        public QueryResults(string s, double d, string r, string q, bool isStr)
        {
            sSymbol = s;
            dResult = d;
            sResult = r;
            sQuery = q;
            bIsStr = isStr;
        }
        public bool isString // if false the result is a double;
        {
            get { return bIsStr; }
            set { }
        }
        public string sSymbol
        {
            get { return symbol; }
            set { symbol = value; }
        }
        public double dResult
        {
            get { return dbl_result; }
            set { dbl_result = value; }
        }
        public string sResult
        {
            get { return str_result; }
            set { str_result = value; }
        }
        public string sQuery
        {
            get { return query; }
            set { query = value; }
        }
    }
    /*begin Class ThreadStockWrapper ***** brandon ****/
    class ThreadStockWrapper
    {
        private int iThreads;
        private string sFunction;
        private ArrayList arStockSymbols;
        private ArrayList[] arThreadStorage, arResults;
        private StockDrone[] sdDrones;
        private Thread[] tThreads;
        public ThreadStockWrapper(int threads, string function, ArrayList stockSymbols)
        {
            iThreads = threads;
            sFunction = function;
            arStockSymbols = stockSymbols;
            arThreadStorage = new ArrayList[threads];
            arResults = new ArrayList[threads];
            sdDrones = new StockDrone[threads];
            tThreads = new Thread[threads];
            for (int i = 0; i < threads; i++)
            {
                arResults[i] = new ArrayList();
                arThreadStorage[i] = new ArrayList();
            }
            for (int i = 0; i < stockSymbols.Count; i++)
            {
                arThreadStorage[i % threads].Add(stockSymbols[i]); // distributing the load equally.
            }
            for (int i = 0; i < threads; i++)
            {
                sdDrones[i] = new StockDrone(arThreadStorage[i], arResults[i]); //prep each drone, storage of symbols, and results storage.
                tThreads[i] = new Thread(sdDrones[i].dispatchFunction); // assign each drone as a thread.
            }
        }
        public ArrayList threadStockCall()
        {
            ArrayList arTemp = new ArrayList();
            for (int i = 0; i < iThreads; i++) // puts our drones to work.
            {
                tThreads[i].Start(sFunction);
            }
           
            int storageCount = iThreads;
            while (storageCount > 0)
            {
                
                for (int i = 0; i < iThreads; i++)
                {
                    storageCount--;
                    if(arResults[i].Count > 0)
                    {
                        arTemp.Add(arResults[i][0]); //allows results to be returned in the order in which they were recieved.
                        arResults[i].RemoveAt(0);
                        storageCount++;
                    }
                }
            }
            return arTemp;
        }
    }
    /****Begin Class StockDrone *** Brandon ***/
    public class StockDrone // drone class. this will be our worker bees
    {
        private static int iThreadCount = 0;
        private static object locker = new Object();
        private ArrayList stockSymbols, results;
        public StockDrone(ArrayList s, ArrayList r)
        {
            stockSymbols = s;
            results = r;
            lock (locker)
            {
                iThreadCount++;
            }
        }
        public void dispatchFunction(object oFunction)//paramatized threads can only have objects as parameters
        {
            string sFunction = (string)oFunction;
            Stock stock = new Stock();
            if (sFunction.Length >= 4)
            {
                char temp = sFunction.ToUpper().ElementAt(3);
                char temp2 = sFunction.ToUpper().ElementAt(sFunction.Length - 1);
                // public QueryResults(string s, double d, string r, string q, bool isString)
                switch (temp) //switch statments are faster than if and elses
                {
                    case 'A':
                        foreach (string s in stockSymbols)
                        {
                            results.Add(new QueryResults(s, 0.0, stock.getAnnualizedGain(s), "getAnnualizedGain", true));
                        }
                        break;
                    case 'C':
                        if (temp2 == 'E')
                        {
                            temp2 = sFunction.ToUpper().ElementAt(sFunction.Length - 2);
                            //getChange
                            if (temp2 == 'G')
                            {
                                foreach (string s in stockSymbols)
                                {
                                    results.Add(new QueryResults(s, stock.getChange(s), "", "getChange", false));
                                }
                            }
                            else
                            {
                                foreach (string s in stockSymbols)
                                {
                                    results.Add(new QueryResults(s, 0.0, stock.getCompanyName(s), "getCompanyName", true));
                                }
                            }
                        }
                        else if (temp2 == 'T')
                        {
                            // getChangeInPercent
                            foreach (string s in stockSymbols)
                            {
                                results.Add(new QueryResults(s, 0.0, stock.getChangeInPercent(s), "getChangeInPercent", true));
                            }
                        }
                        break;
                    case 'E':
                        // getExchange
                        foreach (string s in stockSymbols)
                        {
                            results.Add(new QueryResults(s, 0.0, stock.getExchange(s), "getExchange", true));
                        }
                        break;
                    case 'L':
                        //getLatestValue
                        foreach (string s in stockSymbols)
                        { //false means the result is a double.
                            results.Add(new QueryResults(s, stock.getLatestValue(s), "", "getLatestValue", false));
                        }
                        break;
                    case 'S':
                        if (temp2 == 'H')
                        { //getStockYearHigh
                            foreach (string s in stockSymbols)
                            { //false means the result is a double.
                                results.Add(new QueryResults(s, stock.getStockYearHigh(s), "", "getStockYearHigh", false));
                            }
                        }
                        else if (temp2 == 'W')
                        { //getStockYearLow
                            foreach (string s in stockSymbols)
                            { //false means the result is a double.
                                results.Add(new QueryResults(s, stock.getStockYearLow(s), "", "getStockYearLow", false));
                            }
                        }
                        break;
                }
            }
            lock (locker)
            {
                iThreadCount--;
            }
        }
        public static int getThreadCount()
        {
            return iThreadCount;
        }
    }
    /*begin Class Stock ******** blake */
    class Stock
    {
        // This doesn't work properly
        public string getAnnualizedGain(string symbol)
        {
            return getFromAPIquoute(symbol, "g3")[0];
        }
        public string getExchange(string symbol)
        {
            return getFromAPIquoute(symbol, "x0")[0];
        }
        public double getChange(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "c1")[0]);
        }
        public string getChangeInPercent(string symbol)
        {
            return getFromAPIquoute(symbol, "p2")[0];
        }
        public double getStockYearHigh(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "k0")[0]);
        }
        public double getStockYearLow(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "j0")[0]);
        }
        // This method will return a string with the company name based on the symbol.
        public string getCompanyName(string symbol)
        {
            return getFromAPIquoute(symbol, "n")[0].Substring(1, getFromAPIquoute(symbol, "n")[0].Length - 4);
        }
        public double getLatestValue(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "l1")[0]);
        }
        // Stock Symbol
        // args listed here https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty
        // returns an array of strings. Each arg is it's own element in the array.
        private string[] getFromAPIquoute(string symbol, string args)
        {
            string[] results = null;
            try
            {
                string temp = null;
                string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" +
                symbol + "&f=" + args;
                // Initialize a new WebRequest.
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
                // Get the response from the Internet resource.
                HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                // Read the body of the response from the server.
                StreamReader strm =
                new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
                temp = strm.ReadToEnd();
                results = temp.Split(new Char[] { ',' });
                strm.Close();
            }
            catch
            {
                //some exception
            }
            return results;
        }
        public string getHistory(string symbol, DateTime from, DateTime to, char interval)
        {
            //string[] results = null;
            string temp = null;
            try
            {
                string yahooURL = @"http://ichart.yahoo.com/table.csv?s=" +
                symbol + "&a=" + (from.Month - 1).ToString() + "&b=" +
                (from.Day).ToString() + "&c=" + (from.Year).ToString() + "&d=" +
                (to.Month - 1).ToString() + "&e=" + (to.Day).ToString() + "&f=" +
                (to.Year).ToString() + "&g=" + interval.ToString() + "&ignore=.csv";
                // Initialize a new WebRequest.
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
                // Get the response from the Internet resource.
                HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                // Read the body of the response from the server.
                StreamReader strm =
                new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
                temp = strm.ReadToEnd();
                //results = temp.Split(new Char[] { ',' });
                //results[0] = temp;
                strm.Close();
            }
            catch
            {
                //some exception
            }
            return temp;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using FreeTradeWindowsForms;

namespace FreeTradeWindowsForms.Models
{
    
    public class User
    {
        Stock stock = new Stock();
        public string Username { get; set; }
        public string Password { get; set; }

        /// <summary>
        /// Buying power available
        /// </summary>
        public double Cash { get; set; }
        /// <summary>
        /// Overall worth of cash and all investments
        /// </summary>
        public double Worth { get; set; }
        /// <summary>
        /// Total amount of cash used for investing - this only changes if more cash is borrowed, this will be the basis of all performance calculations
        /// </summary>
        public double borrowedCash { get; set; }
        /// <summary>
        /// // All companies that are currently being invested in.
        /// </summary>
        public List<Holding> Holdings { get; set; } 

        public List<Transaction> Transactions { get; set; }

        public List<Company> WatchList { get; set; }

        /// <summary>
        /// This flag determines whether the user can trade when the market is closed
        /// </summary>
        public bool EnforceMarketClosure { get; set; }

        /// <summary>
        /// This value determines the fee that is charged for each transaction.
        /// </summary>
        public double transactionFee { get; set; }

        // Create a new user by setting the username, password, and how much cash they initially borrowed
        public User(string username, string password, double borrowedCash)
        {
            this.Username = username;
            this.Password = <PASSWORD>;
            this.borrowedCash = borrowedCash;
            this.Worth = borrowedCash;
            this.Cash = borrowedCash;
            this.EnforceMarketClosure = true;
            this.transactionFee = 0;
            Holdings = new List<Holding>();
            Transactions = new List<Transaction>();
            WatchList = new List<Company>();
        }

        public User()
        {

        }


        /// <summary>
        /// Add more cash to use for investing. 
        /// </summary>
        /// <param name="amount"></param>
        public bool AddCash(double amount)
        {
            if (amount > 0)
            {
                Cash += amount;
                borrowedCash += amount;
                return true;
            }
            return false;

        }

        /// <summary>
        /// Buy stocks
        /// </summary>
        /// <param name="companyName"></param>
        /// <param name="companySymbol"></param>
        /// <param name="currentSharePrice"></param>
        /// <param name="numOfShares"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool BuyStock(string companyName, string companySymbol, double currentSharePrice, int numOfShares, DateTime time)
        {
            if (!stock.IsOpenStockMarket() && EnforceMarketClosure)
            {
                MessageBox.Show("The market is closed.");
                return false;
            }

            if (numOfShares * currentSharePrice > Cash)
            {
                MessageBox.Show("You don't have enough money for that purchase. Dummy.");
                return false;
            }

            double transactionAmount = (numOfShares * currentSharePrice);
            // create a new holding if one doesn't already exist
            Holding holding = GetHolding(companySymbol);
            if (holding == null)
            {
                holding = new Holding(companySymbol);
                Holdings.Add(holding);
                holding.companyName = companyName;
                holding.currentSharePrice = currentSharePrice;
            }
            holding.numOfShares += numOfShares;
            holding.totalInvested += (transactionAmount);
            holding.worth += (transactionAmount);

            // Add to list of transactions
            Transactions.Add(new Transaction(companyName, companySymbol, currentSharePrice, numOfShares, time));

            MessageBox.Show("You just purchased " + numOfShares + " shares of " + companyName + " stock at" + currentSharePrice.ToString("C2") + " per share.");
            Cash = Cash - transactionAmount;
            Cash = Cash - transactionFee;
            refresh();
            return true;
        }

        /// <summary>
        /// Get a holding information
        /// </summary>
        /// <param name="companySymbol"></param>
        /// <returns></returns>
        public Holding GetHolding(string companySymbol)
        {
            for (int i = 0; i < Holdings.Count; i++)
            {
                if (Holdings[i].stockSymbol == companySymbol)
                {
                    return Holdings[i];
                }
            }
            return null;
        }
        
        /// <summary>
        /// Sell stocks
        /// </summary>
        /// <param name="companyName"></param>
        /// <param name="companySymbol"></param>
        /// <param name="currentSharePrice"></param>
        /// <param name="numOfShares"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool SellStock(string companyName, string companySymbol, double currentSharePrice, int numOfShares, DateTime time)
        {
            Holding holding = GetHolding(companySymbol);

            if (!stock.IsOpenStockMarket() && EnforceMarketClosure)
            {
                MessageBox.Show("The market is closed.");
                return false;
            }
            if (holding == null)
                return false;

            if (numOfShares > holding.numOfShares)
            {
                MessageBox.Show("You cannot sell more shares than you own, dummy...");
                return false;
            }

            // Sale amount is subtracted from worth because worth is represents the overall worth of the stocks.
            double saleAmount = (numOfShares * currentSharePrice);
            holding.worth = holding.worth - saleAmount;
            Cash = Cash + saleAmount;
            Cash = Cash - transactionFee;

            // The effective price per share is the total amount of money invested divided by the number of shares being held.
            double effectivePricePerShare = (holding.totalInvested / holding.numOfShares);
            holding.totalInvested = holding.totalInvested - (effectivePricePerShare * numOfShares);

            holding.numOfShares = holding.numOfShares - numOfShares;
            refresh();
            MessageBox.Show("You sold " + numOfShares.ToString() + " share(s) of " + companyName + " at " + currentSharePrice.ToString("C2") + " a share. Total sale amount: " + saleAmount.ToString("C2"));
            return true;
        }

        /// <summary>
        /// Add a company to the user's watchlist.
        /// </summary>
        /// <param name="company"></param>
        public void AddToWatchList(Company company)
        {
            if (!CompanyInWatchList(company))
            {
                WatchList.Add(company);
                MessageBox.Show("Company added to watchlist.");

            }
            else
            {
                MessageBox.Show("Company already in watchlist.");
            }
        }

        public bool CompanyInWatchList(Company company)
        {
            foreach (Company watchListCompany in WatchList)
            {
                if (company.Symbol == watchListCompany.Symbol)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Refresh user profile
        /// </summary>
        public void refresh()
        {
            // refresh everything in the user profile
            // refresh everything in each holding
            double tempWorth = 0;
            for (int i = 0; i < Holdings.Count; i++)
            {
                Holdings[i].Refresh(stock.getLatestValue(Holdings[i].stockSymbol));
                tempWorth += Holdings[i].worth;
            }
            Worth = Cash + tempWorth;
        }

        /// <summary>
        /// Get a list of the top gainers
        /// </summary>
        /// <param name="count">How many holdings do you want in the list?</param>
        /// <param name="Gains">If true, returns top gainers, if false, top losers.</param>
        /// <returns></returns>
        public List<Holding> GetTopGainers(int count, bool gains)
        {
            refresh();
            List<Holding> topGainers; 
            if (gains)
                topGainers = Holdings.OrderByDescending(o => o.GetPerformance()).ToList();
            else
                topGainers = Holdings.OrderBy(o => o.GetPerformance()).ToList();

            if (count < Holdings.Count)
            {
                List<Holding> topGainersConstrained = new List<Holding>();
                for (int i = 0; i < count; i++)
                    topGainersConstrained.Add(topGainers[i]);
                return topGainersConstrained;
            }
            return topGainers;
        }

        private void AddTestDataToHoldings()
        {
            Holding holding = new Holding("AAPL");
            holding.numOfShares = 5;
            holding.totalInvested = 80.00;
            Holdings.Add(holding);

            holding = new Holding("TSLA");
            holding.numOfShares = 10;
            holding.totalInvested = 10000.00;
            Holdings.Add(holding);

        }

        public void GenerateReport(string filepath)
        {
            // Clear file
            if (File.Exists(filepath))
            {
                File.WriteAllText(filepath, string.Empty);
            }

            StreamWriter file = new StreamWriter(filepath);

            refresh();

            List<String> report = new List<string>();
            report.Add("Auto Generated report for: " + Username);
            report.Add(DateTime.Now.ToShortDateString());
            report.Add("------------------------------------------------");

            report.Add("");
            report.Add("Net Worth:\t" + Worth.ToString("C2"));
            report.Add("Cash on Hand:\t" + Cash.ToString("C2"));
            report.Add("Cash Borrowed:\t" + borrowedCash.ToString("C2"));
            report.Add("Num of Transactions: \t" + Transactions.Count.ToString());

            report.Add("");
            report.Add("Holdings");
            report.Add("--------");
            for (int i = 0; i < Holdings.Count; i++)
            {
                report.Add("\t" + (i + 1).ToString() + ". " + Holdings[i].companyName + " - " + Holdings[i].stockSymbol);
                report.Add("\t\tPerformance: " + Holdings[i].GetPerformance().ToString("P"));
                report.Add("\t\tNumber of Shares: " + Holdings[i].numOfShares);
                report.Add("\t\tWorth: " + Holdings[i].worth.ToString("C2"));
                report.Add("\t\tTotal Invested: " + Holdings[i].totalInvested.ToString("C2"));
            }

            for (int i = 0; i < report.Count; i ++)
            {
                file.WriteLine(report[i]);
            }
            file.Close();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace FreeTradeWindowsForms
{
    class Stock
    {
        // This doesn't work properly
        public string getAnnualizedGain(string symbol)
        {
            return getFromAPIquoute(symbol, "g3")[0];
        }


        public string getExchange(string symbol)
        {
            return getFromAPIquoute(symbol, "x0")[0];
        }

        public double getChange(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "c1")[0]);
        }

        public string getChangeInPercent(string symbol)
        {
            return getFromAPIquoute(symbol, "p2")[0];
        }

        public double getStockYearHigh(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "k0")[0]);
        }

        public double getStockYearLow(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "j0")[0]);
        }
        // This method will return a string with the company name based on the symbol.
        public string getCompanyName(string symbol)
        {
            return getFromAPIquoute(symbol, "n")[0].Substring(1, getFromAPIquoute(symbol, "n")[0].Length - 4);
        }

        public double getLatestValue(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "l1")[0]);
        }

        // Stock Symbol
        // args listed here https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty 
        // returns an array of strings.  Each arg is it's own element in the array.
        private string[] getFromAPIquoute(string symbol, string args)
        {
            string[] results = null;
            int count = 0;
            while (results == null && count < 3)
            {
                try
                {
                    string temp = null;
                    string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" +
                                          symbol + "&f=" + args;
                    // Initialize a new WebRequest.
                    HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
                    // Get the response from the Internet resource.
                    HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                    // Read the body of the response from the server.
                    StreamReader strm =
                      new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
                    temp = strm.ReadToEnd();
                    results = temp.Split(new Char[] { ',' });
                    strm.Close();
                }
                catch
                {
                    //some exception
                }
                count++;
            }
            if (count == 3)
            {
                MessageBox.Show("Can't seem to get ahold of Yahoo at the moment, maybe try again later?\nThe system will now exit.");
                results = new string[1] { "0" };
                Environment.Exit(0);
            }
            return results;
        }

        public string getHistory(string symbol, DateTime from, DateTime to, char interval)
        {
            //string[] results = null;
            string temp = null;
            try
            {
                string yahooURL = @"http://ichart.yahoo.com/table.csv?s=" +
                                      symbol + "&a=" + (from.Month - 1).ToString() + "&b=" +
                                      (from.Day).ToString() + "&c=" + (from.Year).ToString() + "&d=" +
                                      (to.Month - 1).ToString() + "&e=" + (to.Day).ToString() + "&f=" +
                                      (to.Year).ToString() + "&g=" + interval.ToString() + "&ignore=.csv";
                // Initialize a new WebRequest.
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
                // Get the response from the Internet resource.
                HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                // Read the body of the response from the server.
                StreamReader strm =
                  new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
                temp = strm.ReadToEnd();
                //results = temp.Split(new Char[] { ',' });
                //results[0] = temp;
                strm.Close();
            }
            catch
            {
                //some exception
            }
            return temp;
        }

        public bool IsOpenStockMarket()
        {
            TimeSpan _marketUpdateDelay = new TimeSpan(0, 15, 00);  // market update delay
            TimeSpan _marketOpenTime = new TimeSpan(9, 30, 00);     // market open time
            TimeSpan _marketCloseTime = new TimeSpan(16, 00, 00);   // market close time
            DateTime dt = DateTime.Now;
            string nameOfTheDay = DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("en-GB")).ToLower();

            if (nameOfTheDay == "sunday" || nameOfTheDay == "saturday")
            {
                return false;
            }

            // check if current time is between stock marker open and close hours
            if (dt.Hour > _marketOpenTime.Hours &&
                dt.Hour < _marketCloseTime.Hours)
                return true;

            if (dt.Hour == _marketOpenTime.Hours
                && dt.Minute >= _marketOpenTime.Minutes + _marketUpdateDelay.Minutes)
                return true;

            if (dt.Hour == _marketCloseTime.Hours
                && dt.Minute <= _marketCloseTime.Minutes + _marketUpdateDelay.Minutes)
                return true;

            return false;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FreeTrade
{
    public class Company
    {
        public string Symbol { get; set; }
        public string Name { get; set; }
        public string Sector { get; set; }
        public string Industry { get; set; }
        public string IPOyear { get; set; }
        public double StockPrice;
        public Company(String symbol, String name, String sector, String industry, String ipoYear, double stockPrice)
        {
            Symbol = symbol;
            Name = name;
            Sector = sector;
            Industry = industry;
            IPOyear = ipoYear;
            StockPrice = stockPrice;
        }

        public double getStockPrice()
        {
            Stock stock = new Stock();
            return stock.getLatestValue(Symbol);
        }

        public override string ToString()
        {
            return Name + " - " + Symbol;
        }

        public bool Contains(string query)
        {
            query = query.ToLower();
            return (Symbol.ToLower().Contains(query) ||
                Name.ToLower().Contains(query) ||
                Sector.ToLower().Contains(query) ||
                Industry.ToLower().Contains(query) ||
                IPOyear.ToLower().Contains(query));
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FreeTradeWindowsForms.Controllers;
using FreeTradeWindowsForms.Models;

namespace FreeTradeWindowsForms
{
    public partial class Settings : Form
    {
        User user;
        public Settings(User user)
        {
            InitializeComponent();
            this.user = user;
            if (!user.EnforceMarketClosure) 
            {
                marketCloseBox.Text = "No";
            }
            settingsFeesBox.Text = user.transactionFee.ToString();
        }

        public User getUser()
        {
            return user;
        }

        public string getCash()
        {
            return settingsCashBox.Text;
        }

        public string getFees()
        {
            return settingsFeesBox.Text;
        }
                
        public string getEnforcement()
        {
            return marketCloseBox.Text;
        }

        private void settingsSaveButton_Click(object sender, EventArgs e)
        {
            string message = "";
            double temp = 0; //used in parsing and then assigned to revelent fields.

            if (settingsCashBox.Text.Length > 0 && double.TryParse(settingsCashBox.Text, out temp))
            {
                if (user.AddCash(temp)) { }

                else
                    message += "No money has been added since cash is zero.";

            }
            else
            {
                if(settingsCashBox.Text.Length > 0)
                   message += "Invalid Entry in cash";
            }
                //add fees here.
            if (settingsFeesBox.Text.Length >= 0 && double.TryParse(settingsFeesBox.Text, out temp) && temp >= 0)
                user.transactionFee= temp;
            else
            {
                if(message.Length > 0)
                   message+=Environment.NewLine;
                if(settingsFeesBox.Text.Length > 0)
                   message += "Invalid entry in fees";
                else
                   settingsFeesBox.Text = user.transactionFee.ToString();
            }
            //set market enforcement
            if (getEnforcement().Equals("Yes"))
            {
                user.EnforceMarketClosure = true;
            }
            else
            {
                user.EnforceMarketClosure = false;
            }

            //close the settings window.
            this.Close();
            if (message.Length > 0)
                MessageBox.Show(message);
            else
               MessageBox.Show("Settings changed.");
        }

        private void settingsFeesBox_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace FreeTrade
{
    class Stock
    {
        // This doesn't work properly
        public string getAnnualizedGain(string symbol)
        {
            return getFromAPIquoute(symbol, "g3")[0];
        }


        public string getExchange(string symbol)
        {
            return getFromAPIquoute(symbol, "x0")[0];
        }

        public double getChange(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "c1")[0]);
        }

        public string getChangeInPercent(string symbol)
        {
            return getFromAPIquoute(symbol, "p2")[0];
        }

        public double getStockYearHigh(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "k0")[0]);
        }

        public double getStockYearLow(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "j0")[0]);
        }
        // This method will return a string with the company name based on the symbol.
        public string getCompanyName(string symbol)
        {
            return getFromAPIquoute(symbol, "n")[0].Substring(1, getFromAPIquoute(symbol, "n")[0].Length - 4);
        }

        public double getLatestValue(string symbol)
        {
            return Convert.ToDouble(getFromAPIquoute(symbol, "l1")[0]);
        }

        // Stock Symbol
        // args listed here https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty 
        // returns an array of strings.  Each arg is it's own element in the array.
        private string[] getFromAPIquoute(string symbol, string args)
        {
            string[] results = null;
            try
            {
                string temp = null;
                string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" +
                                      symbol + "&f=" + args;
                // Initialize a new WebRequest.
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
                // Get the response from the Internet resource.
                HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                // Read the body of the response from the server.
                StreamReader strm =
                  new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
                temp = strm.ReadToEnd();
                results = temp.Split(new Char[] { ',' });
                strm.Close();
            }
            catch
            {
                //some exception
            }
            return results;
        }

        public string getHistory(string symbol, DateTime from, DateTime to, char interval)
        {
            //string[] results = null;
            string temp = null;
            try
            {
                string yahooURL = @"http://ichart.yahoo.com/table.csv?s=" +
                                      symbol + "&a=" + (from.Month - 1).ToString() + "&b=" + 
                                      (from.Day).ToString() + "&c=" + (from.Year).ToString() + "&d=" + 
                                      (to.Month - 1).ToString() + "&e=" + (to.Day).ToString() + "&f=" +
                                      (to.Year).ToString() + "&g=" + interval.ToString() + "&ignore=.csv";
                // Initialize a new WebRequest.
                HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
                // Get the response from the Internet resource.
                HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
                // Read the body of the response from the server.
                StreamReader strm =
                  new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
                temp = strm.ReadToEnd();
                //results = temp.Split(new Char[] { ',' });
                //results[0] = temp;
                strm.Close();
            }
            catch
            {
                //some exception
            }
            return temp;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FreeTradeWindowsForms
{
    public partial class WhatIf : Form
    {
        public WhatIf()
        {
            InitializeComponent();
        }

        private void whatButton_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime from = fromPicker.Value;
                DateTime to = toPicker.Value;
                Stock stock = new Stock();
                string[] splitResults = stock.getHistory(companySymbolBox.Text, from, from, 'm').Split(new Char[] { ',' });
                double fromPrice = Convert.ToDouble(splitResults[7]);
                splitResults = stock.getHistory(companySymbolBox.Text, to, to, 'm').Split(new Char[] { ',' });
                double toPrice = Convert.ToDouble(splitResults[7]);
                int numShares = Convert.ToInt32(purchasedSharesBox.Text);
                double profit = (toPrice - fromPrice) * numShares;
                if (profit >= 0)
                    MessageBox.Show("You would have made " + profit.ToString("C2") + " had you bought " + numShares + " share(s) of " + companySymbolBox.Text + " in " + from.Year + " and then sold in " + to.Year + "\nFrom: " + fromPrice.ToString("C2") + "\nTo: " + toPrice.ToString("C2"));
                else
                    MessageBox.Show("You would have lost " + profit.ToString("C2") + " had you bought " + numShares + " share(s) of " + companySymbolBox.Text + " in " + from.Year + " and then sold in " + to.Year + "\nFrom: " + fromPrice.ToString("C2") + "\nTo: " + toPrice.ToString("C2"));
            }
            catch
            {
                MessageBox.Show("Something is wrong with this.");
            }
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FreeTradeWindowsForms
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void loginButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public string getUsername()
        {
            return usernameBox.Text;
        }

        public string getPassword()
        {
            return passBox.Text;
        }

        private void newUserButton_Click(object sender, EventArgs e)
        {
            NewUser newUser = new NewUser();
            newUser.Show();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FreeTrade.ViewModels;

namespace FreeTrade.Views
{
    /// <summary>
    /// Interaction logic for Trade.xaml
    /// </summary>
    public partial class Trade : UserControl
    {
        TradeViewModel viewModel = new TradeViewModel();
        public Trade()
        {
            InitializeComponent();

            this.DataContext = viewModel;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FreeTradeWindowsForms.Controllers;

namespace FreeTradeWindowsForms
{
    public partial class NewUser : Form
    {
        public NewUser()
        {
            InitializeComponent(); 
        }

        public string getUsername()
        {
            return newUserNameBox.Text;
        }

        public string getPassword()
        {
            return pass1Box.Text;
        }

        public string getPasswordVerification()
        {
            return pass2Box.Text;
        }

        public string getStartingCash()
        {
            return startCashBox.Text;
        }

        //protected override void OnFormClosing(FormClosingEventArgs e)
        //{
        //    base.OnFormClosing(e);

        //    if (e.CloseReason == CloseReason.WindowsShutDown) return;

        //    if (pass1Box.Text != pass2Box.Text)
        //    {
        //        // Confirm user wants to close
        //        switch (MessageBox.Show(this, "Your passwords do not match.", "Incorrect Input", MessageBoxButtons.OK))
        //        {
        //            case DialogResult.OK:
        //                e.Cancel = true;
        //                break;
        //            default:
        //                break;
        //        }
        //    }
        //}

        private void addUserButton_Click(object sender, EventArgs e)
        {
            double startingCash;
            bool test = double.TryParse(getStartingCash(), out startingCash);
            if (string.IsNullOrEmpty(getUsername()) || 
                string.IsNullOrEmpty(getPassword()) || 
                string.IsNullOrEmpty(getPasswordVerification()) || 
                string.IsNullOrEmpty(getStartingCash()) ||
                !double.TryParse(getStartingCash(), out startingCash) ||
                pass1Box.Text != pass2Box.Text || startingCash < 0)
            {
                MessageBox.Show("Invalid information. Please try again.");
                return;
            }

            if (LoginController.isUser(getUsername()))
                MessageBox.Show("Username already exists.");
            else
            {
                LoginController.CreateNewUser(getUsername(), getPassword(), double.Parse(getStartingCash()));
                this.Close();
            }
        }

        private void startCashBox_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;

namespace FreeTradeWindowsForms
{

    public class Search
    {
        List<Company> stocks = new List<Company>();

        public Search()
        {
            initialize();
        }

        public List<string> getStocksList(string filename)
        {
            List<string> allStocks = new List<string>();
            using (StreamReader r = new StreamReader(filename))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    allStocks.Add(line);
                }
            }
            return allStocks;
        }

        public void initialize()
        {
            List<string> allStocks = new List<string>();
            allStocks.AddRange(getStocksList(@"../../Stocks/nyse.csv"));
            allStocks.AddRange(getStocksList(@"../../Stocks/nasdaq.csv"));
            allStocks.AddRange(getStocksList(@"../../Stocks/amex.csv"));
            string[] lines = allStocks.ToArray();
            String[] columns = null;
            Company theCompany = new Company(null, null, null, null, null, 0);
            foreach (String line in lines)
            {

                columns = line.Replace("\"", "").Split(',');

                theCompany.Name = columns[1];
                theCompany.Symbol = columns[0];
                theCompany.Sector = columns[6];
                theCompany.Industry = columns[7];
                theCompany.IPOyear = columns[5];

                stocks.Add(theCompany);
                theCompany = new Company(null, null, null, null, null, 0);
            }
        }

        public List<Company> search(string query)
        {
            if (!String.IsNullOrEmpty(query))
            {
                query = query.ToLower();
                List<Company> results = new List<Company>();
                results.AddRange(stocks.FindAll(x => x.Contains(query)));
                List<Company> result = new List<Company>(results);
                return result;
            }
            return null;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeTradeWindowsForms.Models
{
    public class Holding
    {
        // TODO: add companyName and currentPrice
        /*
         * This class represents a company that a user is invested in.
         *  
         * Properties:
         *      numOfShares - the total number of shares invested in the company.
         *      stockSymbol - the stock symbol of the company that is being held.
         *      totalValue  - value of all assets in company
         *      worth       - the amount of money the holding is worth at the current stock price.
         * 
         */
        public Holding(string stockSymbol)
        {
            this.stockSymbol = stockSymbol;
            this.companyName = "";
            this.currentSharePrice = 0.0;
            this.numOfShares = 0;
            this.totalInvested = 0.0;
            this.worth = 0.0;
            this.performance = 0.0;
        }

        public Holding()
        {

        }

        public int numOfShares;
        public string stockSymbol;
        public string companyName;
        public double totalInvested;
        public double currentSharePrice;
        public double worth;
        public double performance;


        /// <summary>
        /// Get the percentage increase or decrease, don't forget to update the current share price manually before using this.
        /// </summary>
        public double GetPerformance()
        {
            return ((worth / totalInvested) - 1);
        } 

        public void Refresh(double currentPrice)
        {
            this.currentSharePrice = currentPrice;
            worth = numOfShares * currentPrice;
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using FreeTradeWindowsForms.Models;

namespace FreeTradeWindowsForms.Controllers
{
    static class LoginController
    {
        public static User Login(string username, string password)
        {
            //Construct the filepath
            string filepath = Directory.GetCurrentDirectory() + "\\" + username + ".txt";
            // User already exists
            if (File.Exists(filepath))
            {
                System.Xml.Serialization.XmlSerializer reader =
                    new System.Xml.Serialization.XmlSerializer(typeof(User));
                System.IO.StreamReader file = new System.IO.StreamReader(filepath);
                User user = new User();
                user = (User)reader.Deserialize(file);
                file.Close();
                if (user.Password == password)
                    return user;
                else
                    return null;
            }
            else
            {
                // User not found
                return null;
            }
        }

        public static bool isUser(string username)
        {
            string filepath = Directory.GetCurrentDirectory() + "\\" + username + ".txt";
            if (File.Exists(filepath))
                return true;
            else return false;
        }

        public static User CreateNewUser(string username, string password, double startingCash)
        {
            //Construct the filepath
            string filepath = Directory.GetCurrentDirectory() + "\\" + username + ".txt";
            // User already exists
            if (File.Exists(filepath))
                return null;

            User user = new User(username, password, startingCash);
            Logout(user);
            return user;
        }

        public static void Logout(User user)
        {

            // The following is just test code

            //User user = new User("Ted", "<PASSWORD>", <PASSWORD>);
            //user.Holdings.Add(new Holding("GOOG"));
            //DateTime newDate = new DateTime();
            //user.WatchList.Add(new Company("test", "GOOG", "Something", "Something", "Something", 50.00));
            //user.Transactions.Add(new Transaction("Test", "Test", 50.00, 50, DateTime.Now));

            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(User));

            //Construct the filepath
            string filepath = Directory.GetCurrentDirectory() + "\\" + user.Username + ".txt";

            // Clear the file
            if (File.Exists(filepath) )
            {
                File.WriteAllText(filepath, string.Empty);
            }
            System.IO.StreamWriter file = new System.IO.StreamWriter(
               filepath);
            writer.Serialize(file, user);
            file.Close();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FreeTrade
{
    class Test
    {
        public void theTest(string[] args)
        {
            Stock stock = new Stock();
            Console.WriteLine(stock.getLatestValue("sdfgsdfg").ToString());

            Console.WriteLine(stock.getChangeInPercent("GOOG").ToString());
            Console.WriteLine(stock.getChange("GOOG").ToString());
            Console.WriteLine(stock.getExchange("GOOG").ToString());
            Console.WriteLine(stock.getAnnualizedGain("GOOG").ToString());
            DateTime from = new DateTime(2010, 1, 1);
            DateTime to = DateTime.Now;
            Console.WriteLine(stock.getHistory("GOOG", from, to, 'w').ToString());

        }

    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace transaction
{ 
    class UserProfile
    {
        private List<CompanyStock> lCompanyStock;
        private List<StockTransaction> lStockTransaction;

        private string sName;

        private double dMoney;
        private double dPurchases;
        private double dSales;
        private double dChargedFees;
        private double dTransFee;

        List<CompanyStockInfo> GetCompnayList()
        { 
            List<CompanyStockInfo> Temp = new List<CompanyStockInfo>();
            foreach (CompanyStock cs in lCompanyStock)
            {
                Temp.Add(cs.GetDescriptor());
            }
            return Temp;
        }

        List<StockTransactionInfo> GetTransactionList()
        { 
            List<StockTransactionInfo> Temp = new List<StockTransactionInfo>();

            foreach (StockTransaction st in lStockTransaction)
            {
                Temp.Add(st.GetDescriptor());
            }
            return Temp;

        }

        public  UserProfile()
        {
            sName = "default";
            dMoney = 5000.0;
            dPurchases = 0.0;
            dSales = 0.0;
            dChargedFees = 0.0;
            dTransFee = 7.00;

            lCompanyStock = new List<CompanyStock>();
            lStockTransaction = new List<StockTransaction>();
        }

        public UserProfile(string name, double money, double transFee)
        {
            //setting up a new user
            if (!SetName(name))
            {
                sName = "error";
            }
            if (!SetMoney(money))
            {
                dMoney = 0.0;
            }
            dPurchases = 0.0;
            dSales = 0.0;
            dChargedFees = 0.0;

            if (!SetTransActionFee(transFee))
            {
                dTransFee = 2.00;
            }
            lCompanyStock = new List<CompanyStock>();
            lStockTransaction = new List<StockTransaction>();
        }


        public  UserProfile(string name)
        {
            sName = name;
            lCompanyStock = new List<CompanyStock>();
            lStockTransaction = new List<StockTransaction>();
            ReadFromFile();
        }

       

        public void WriteToFiles()
        { 
            //5 fields/
           string nl = Environment.NewLine;
           string temp = dMoney.ToString() + nl + dPurchases.ToString() + nl + dSales.ToString() + nl + dChargedFees.ToString() + nl + dTransFee.ToString();
           System.IO.File.WriteAllText(sName + "UserProfile.txt", temp);
          
           System.IO.StreamWriter file = new System.IO.StreamWriter(sName + "CompanyStock.txt", true);
           
           foreach(CompanyStock cs in lCompanyStock)
           {  //5 fields
               file.WriteLine(cs.GetName());
               file.WriteLine(cs.GetSymbol());
               file.WriteLine(cs.GetSpent().ToString());
               file.WriteLine(cs.GetEarned().ToString());
               file.WriteLine(cs.GetShares().ToString());
           }
           file.Close();

           file = new System.IO.StreamWriter(sName + "StockTransaction.txt", true);

           foreach(StockTransaction st in lStockTransaction)
           {   //6 lines
               file.WriteLine(st.GetName());
               file.WriteLine(st.GetSymbol());
               file.WriteLine(st.GetPrice());
               file.WriteLine(st.GetShares());
               file.WriteLine(st.GetDate().ToString("MM dd yyyy HH mm ss fff"));
               file.WriteLine(st.GetSold().ToString());
           }
           file.Close();
        }

        private void ReadFromFile() // this is private for a really good reason.  this function should only be used by constructor.
        {
            //Read Basic User Data In
            string[] lines = System.IO.File.ReadAllLines(sName + "UserProfile.txt");
            dMoney = double.Parse(lines[0]);
            dPurchases = double.Parse(lines[1]);
            dSales = double.Parse(lines[2]);
            dChargedFees = double.Parse(lines[3]);
            dTransFee = double.Parse(lines[4]);

            lines = System.IO.File.ReadAllLines(sName + "CompanyStock.txt");

            string tempName;
            string tempSymbol;
            double tempSpent;
            double tempEarned;
            double tempShares;


            for (int i = 0; i < lines.Length; i += 5)
            {
                tempName= lines[i];
                tempSymbol = lines[i+1 ];
                tempSpent = double.Parse(lines[i + 2]);
                tempEarned = double.Parse(lines[i + 3]);
                tempShares = double.Parse(lines[i + 4]);
                lCompanyStock.Add(new CompanyStock(tempName,tempSymbol,tempSpent,tempEarned,tempShares));
            }

            lines = System.IO.File.ReadAllLines(sName + "StockTransaction.txt");

            DateTime dt;
            bool tempSold;
            double tempPrice;

            string [] dtSpl; // Date Splitter;

            int month;
            int day;
            int year;
            int hour;
            int minute;
            int second;
            int millisecond;

            for (int i = 0; i < lines.Length; i += 6)
            {
                tempName = lines[i];
                tempSymbol = lines[i + 1];
                tempPrice = double.Parse(lines[i + 2]);
                tempShares = double.Parse(lines[i + 3]);
                dtSpl = lines[i + 4].Split(' ');
                tempSold = bool.Parse(lines[i + 5]);

               
                
                month = int.Parse(dtSpl[0]);
                day = int.Parse(dtSpl[1]);
                year = int.Parse(dtSpl[2]);
                hour = int.Parse(dtSpl[3]);
                minute = int.Parse(dtSpl[4]);
                second = int.Parse(dtSpl[5]);
                millisecond = int.Parse(dtSpl[6]);
                dt = new DateTime(year, month, day, hour, minute, second, millisecond);
                
                lStockTransaction.Add(new StockTransaction(tempName,tempSymbol,tempPrice,tempShares,dt,tempSold));

            }
        }

        public string GetName()
        {
            return sName;
        }

        public bool SetName(string name)
        {
            if (name != null && name.Length > 0)
            {
                sName = name;
                return true;
            }
            return false;
        }

        public bool BuyStock(String name, string symbol, double price, double shares, DateTime dt)
        {
            if (shares * price > dMoney)
                return false;

            if (name == null || symbol == null)
                return false;

            dMoney -= ((shares * price) + dChargedFees);
            dChargedFees += dTransFee;
            dPurchases += (shares * price);
            bool found = false;

            lStockTransaction.Add(new StockTransaction(name, symbol, price, shares, dt, false));

            for (int i = 0; i < lCompanyStock.Count && !found; i++)
            {
                if (lCompanyStock[i].GetName() == name && lCompanyStock[i].GetSymbol() == symbol)
                {
                    double spentTemp = lCompanyStock[i].GetSpent();
                    double sharesTemp = lCompanyStock[i].GetShares();
                    found = true;
                    lCompanyStock[i].SetShares(sharesTemp + shares);
                    lCompanyStock[i].SetSpent(spentTemp + (price * shares));
                }
            }
            if (!found)
            {
                lCompanyStock.Add(new CompanyStock(name, symbol, price * shares, 0, shares));
            }

            return true;
        }

        public bool SellStock(String name, string symbol, double price, double shares, DateTime dt)
        {
            if (name == null || symbol == null)
                return false;

            bool found = false;

            for (int i = 0; i < lCompanyStock.Count && !found; i++)
            {
                if (lCompanyStock[i].GetName() == name && lCompanyStock[i].GetSymbol() == symbol)
                {
                    double  earnedTemp = lCompanyStock[i].GetEarned();
                    double  sharesTemp = lCompanyStock[i].GetShares();
                    found = true;
                    if (shares > sharesTemp)
                        return false;
                    dSales += (shares * price);
                    lCompanyStock[i].SetEarned(earnedTemp+(shares*price));
                    lCompanyStock[i].SetShares(sharesTemp - shares);

                }
            }
            lStockTransaction.Add(new StockTransaction(name, symbol, price, shares, dt, true));
            dMoney += ((shares * price) - dChargedFees);
            return true;
        }




        public double GetMoney()
        {
            return dMoney;
        }

        bool SetMoney(double money)
        {
            if (money >= 0.0)
            {
                dMoney = money;
                return true;
            }
            return false;
        }

        public double GetPurchases()
        {
            return dPurchases;
        }

        public bool SetPurchases(double pur)
        {
            if (pur >= 0)
            {
                dPurchases = 0.0;
                return true;
            }
            return false;
        }

        public double GetSales()
        {
            return dSales;
        }

        public bool SetSales(double sales)
        {
            if (sales >= 0)
            {
                dSales = sales;
                return true;
            }
            return false;
        }

        public double GetChargedFee()
        {
            return dTransFee;
        }

        public bool SetChargedFee(double charged)
        {
            if (charged >= 0.0)
            {
                dChargedFees = charged;
                return true;
            }
            return false;
        }

        public double GetTransActionFee()
        {
            return dTransFee;
        }

        public bool SetTransActionFee(double transFee)
        {
            if (transFee >= 0)
            {
                dTransFee = transFee;
                return true;
            }
            return false;
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace transaction
{

    struct StockTransactionInfo
    {
        public string Name;
        public string Symbol;
        public string Price;
        public string Shares;
        public string date;
        public string Sold;
    }
    public class StockTransaction
    {
        private string sName;
        private string sStockSymbol;
        private double dPrice;
        private double dShares;
        private DateTime dtDate;
        private bool bSold;

        public StockTransactionInfo GetDescriptor()
        {
            StockTransactionInfo Temp = new StockTransactionInfo();

            Temp.Name = sName;
            Temp.Symbol = sStockSymbol;
            Temp.Price = dPrice.ToString();
            Temp.Shares = dShares.ToString();
            Temp.date = dtDate.ToString("MM/dd/yyyy hh:mm:ss.fff");
            Temp.Sold = bSold.ToString();
            return Temp;
        }


        public StockTransaction()
        {
            sName = "default";
            sStockSymbol = "dt";
            dPrice = 0.0;
            dShares = 0.0;
            dtDate = DateTime.Now;
            bSold = false;
        }

        public StockTransaction(string name, string symbol, double price, double shares, DateTime dt, bool sold)
        {
            if (!SetName(name))//if Error.
            {
                sName = "Invalid Name";
            }
            if (!SetSymbol(symbol))
            {
                sStockSymbol = "Invalid Symbol";
            }

            if(!SetPrice(price))
            {
               price = 0.0;
            }
            
            if(!SetShares(shares))
            {
               dShares = 0.0;
            }
            if (!SetDate(dtDate))
            {
                dtDate = DateTime.Now;
            }

            bSold = sold;
        }

        public string GetName()
        {
            return sName;
        }

        public bool SetName(string name)
        {
            if (name != null && name.Length > 0)
            {
                sName = name;
                return true;
            }
            return false;
        }

        public string GetSymbol()
        {
            return sStockSymbol;
        }

        public bool SetSymbol(string symbol)
        {
            if (symbol !=null && symbol.Length > 0)
            {
                sStockSymbol = symbol;
                return true;
            }
            return false;
        }

        public double GetPrice()
        {
            return dPrice;
        }

        public bool SetPrice(double price)
        {
            if (price >= 0.0)
            {
                dPrice = price;
                return true;
            }
            return false;
        }

        public double GetShares()
        {
            return dShares;
        }


        bool SetShares(double shares)
        {
            if (shares >= 0.0)
            {
                dShares = shares;
                return true;
            }
            return false;
        }


        public bool SetDate(DateTime dt)
        {
            if (dt == null)
                return false;
            //creating a deep copy
            int Month = dt.Month;
            int Day = dt.Day;
            int Year = dt.Year;
            int Hour = dt.Hour;
            int Minute = dt.Minute;
            int Second = dt.Second;
            int Millisecond = dt.Millisecond;
            //deep copy  dont touch our guts.
            dtDate = new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
            return true;
        
        }

        public DateTime GetDate()
        {
            //deep copy so we don't play with the guts.
            int Month = dtDate.Month;
            int Day = dtDate.Day;
            int Year = dtDate.Year;
            int Hour = dtDate.Hour;
            int Minute = dtDate.Minute;
            int Second = dtDate.Second;
            int Millisecond = dtDate.Millisecond;
            return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);
        
        }

        public bool GetSold()
        {
            return bSold;
        }

        public void SetSold(bool s)
        {
            bSold = s;
        }

    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreeTradeWindowsForms.Models
{
    public class Transaction
    {
        public string CompanyName { get; set; }
        public string StockSymbol { get; set; }
        public double SharePrice { get; set; }
        public int NumOfShares { get; set; }
        public DateTime date { get; set; }
        
        public Transaction()
        {

        }

        public Transaction(string companyName, string companySymbol, double sharePrice, int numOhShares, DateTime date)
        {
            this.CompanyName = companyName;
            this.StockSymbol = companySymbol;
            this.SharePrice = sharePrice;
            this.NumOfShares = numOhShares;
            this.date = date;
        }
    }
}
<file_sep>FreeTrade
=========
This application allows you to practice buying and selling stocks.
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Collections.ObjectModel;
using FreeTrade.Models;
using FreeTrade.Helpers;

namespace FreeTrade.ViewModels
{
    class TradeViewModel : ViewModelBase
    {
        public Search searchHelper = new Search();

        private string companyName;
        private string searchTerm;
        private Company selectedCompany;
        private bool isCompanySelected = false;

        public ObservableCollection<Company> companies;
        
        public TradeViewModel()
        {
            searchHelper.initialize();
            companies = new ObservableCollection<Company>();
        }

        #region PROPERTIES

        public string CompanyName
        {
            get
            {
                return companyName;
            }
            set
            {
                if (companyName != value)
                {
                    companyName = value;
                    RaisePropertyChanged("CompanyName");
                }
            }
        }

        public string SearchTerm
        {
            get
            {
                return searchTerm;
            }
            set
            {
                if (searchTerm != value)
                {
                    searchTerm = value;
                    RaisePropertyChanged("SearchTerm");
                }
            }
        }

        public ObservableCollection<Company> Companies
        {
            get
            {
                return companies;
            }
            set
            {
                if (companies != value)
                {
                    companies = value;
                    RaisePropertyChanged("Companies");
                }
            }
        }

        public Company SelectedCompany
        {
            get
            {
                return selectedCompany;
            }
            set
            {
                if (selectedCompany != value)
                {
                    selectedCompany = value;
                    RaisePropertyChanged("SelectedCompany");

                    if (selectedCompany != null)
                    {
                        IsCompanySelected = true;
                        RaisePropertyChanged("IsCompanySelected");
                    }
                    else
                    {
                        IsCompanySelected = false;
                        RaisePropertyChanged("IsCompanySelected");
                    }

                }
            }
        }

        public bool IsCompanySelected
        {
            get
            {
                return isCompanySelected;
            }
            set
            {
                if (isCompanySelected != value)
                {
                    isCompanySelected = value;
                    RaisePropertyChanged("IsCompanySelected");
                }
            }
        }

        #endregion PROPERTIES

        #region METHODS
        public void Search()
        {
            Companies = searchHelper.search(searchTerm);
        }

        public bool CanSearch()
        {
            return true;
        }
        #endregion METHODS

        #region COMMANDS
        private ICommand searchCommand;

        public ICommand SearchCommand
        {
            get
            {
                if (searchCommand == null)
                {
                    searchCommand = new RelayCommand(
                        param => this.Search(),
                        param => this.CanSearch()
                    );
                }
                return searchCommand;
            }
        }
        #endregion COMMANDS
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using System.Windows.Forms;
using FreeTradeWindowsForms.Controllers;
using FreeTradeWindowsForms.Models;
using System.Threading;

namespace FreeTradeWindowsForms
{
    public partial class MainForm : Form
    {
        User user;
        List<Company> results = new List<Company>();
        Thread refreshThread;
        System.Timers.Timer refreshTimer;
        public MainForm()
        {
            InitializeComponent();
            showLogin();
            updateMarketStatus();
            initializeUser();
            refreshThread = new Thread(refresh);
            refreshThread.Start();
            refreshTimer = new System.Timers.Timer(30000);
        }

        public void refresh()
        {
            Thread.Sleep(30000);
            this.Invoke((MethodInvoker)delegate
            {
                if (mainTab.SelectedIndex == 0)
                {
                    user.refresh();
                    updateOverview();
                }
            });
            refresh();
        }

        public void updateMarketStatus()
        {
            Stock marketCheck = new Stock();
            if (marketCheck.IsOpenStockMarket())
            {
                marketStatus.Text = "Open";
                marketStatus.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                marketStatus.Text = "Closed";
                marketStatus.ForeColor = System.Drawing.Color.Red;
            }
        }


        public void showLogin()
        {
            Login login = new Login();
            DialogResult result = login.ShowDialog();
            if (result == DialogResult.Cancel)
            {
                Environment.Exit(0);
                return;
            }
            user = LoginController.Login(login.getUsername(), login.getPassword());
            if (user == null)
            {
                MessageBox.Show("Invalid username or password.");
                showLogin();
            }
        }

        public void initializeUser()
        {
            statusUserCash.Text = user.Cash.ToString("C2");
            statusUsername.Text = user.Username;
            updateOverview();
        }

        public void updateOverview()
        {
            LabelCashOverview.Text = user.Worth.ToString("C2");
            updateWatchlistBox();
            UpdateTopGainersListbox();
            LabelOverallWorth.Text = user.Worth.ToString("C2");
            double userTotalReturns = ((user.Worth / user.borrowedCash) - 1);
            LabelTotalReturns.Text = userTotalReturns.ToString("P");
            if (userTotalReturns < 0)
                LabelTotalReturns.ForeColor = Color.Red;
            else
                LabelTotalReturns.ForeColor = Color.Green;
            LabelCashOverview.Text = user.Cash.ToString("C2");
        }

        private void updateWatchlistBox()
        {
            ListBoxWatchlist.Items.Clear();
            List<Company> comps = user.WatchList;
            comps.Reverse();
            foreach (Company company in comps)
            {
                ListBoxWatchlist.Items.Add(String.Format("{0} - {1}", company.Name, company.getStockPrice().ToString("C2")));
            }
        }

        private void UpdateTopGainersListbox()
        {
            ListBoxTop5Gains.Items.Clear();
            ListBoxTop5Loss.Items.Clear();
            List<Holding> topGainers = user.GetTopGainers(5, true);
            foreach (Holding holding in topGainers)
                ListBoxTop5Gains.Items.Add(String.Format("{0} | %{1}", holding.companyName, holding.GetPerformance().ToString("P"))); 
            topGainers = user.GetTopGainers(5, false);
            foreach (Holding holding in topGainers)
                ListBoxTop5Loss.Items.Add(String.Format("{0} | %{1}", holding.companyName, holding.GetPerformance().ToString("P")));
        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            results = new List<Company>();
            searchResults.Items.Clear();
            string query = searchBox.Text;
            Search search = new Search();
            results = search.search(query);
            if (results != null)
            {
                foreach (Company company in results)
                {
                    searchResults.Items.Add(String.Format("{0} - {1}", company.Name, company.Symbol));
                }
            }
        }

        private void searchResults_SelectedIndexChanged(object sender, EventArgs e)
        {
            Stock stock = new Stock();
            int index = searchResults.SelectedIndex;
            if (index >= 0)
            {
                Company company = results[index];
                tradeCompanyName.Text = company.Name;
                tradeSymbol.Text = company.Symbol;
                tradeStockPrice.Text = company.getStockPrice().ToString("C2");
                tradeExchange.Text = stock.getExchange(company.Symbol);
                tradeIPO.Text = company.IPOyear;
                tradeIndustry.Text = company.Industry;
                tradeHigh.Text = stock.getStockYearHigh(company.Symbol).ToString("C2");
                tradeLow.Text = stock.getStockYearLow(company.Symbol).ToString("C2");

                List<Holding> holdings = user.Holdings;
                //loop through the purchased stocks.
                foreach (Holding holding in holdings)
                {
                    if (holding.stockSymbol.Equals(company.Symbol))
                    {
                        tradeCurrentSharesBox.Text = holding.numOfShares.ToString();
                        break;
                    }
                    else
                    {
                        tradeCurrentSharesBox.Text = "0";
                    }
                }
            }

        }

        private void searchEnter(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                searchButton_Click(null, null);
                e.Handled = true;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void buyButton_Click(object sender, EventArgs e)
        {
            int index = searchResults.SelectedIndex;
            if (index > -1)
            {
                Company company = results[index];
                int numOfShares = 0;

                bool bParse = int.TryParse(tradeNumOfShares.Text, out numOfShares);
                
                DateTime now = DateTime.Now;
                
                // had to use short circuiting to make sure stocks were not bought with an ammount of zero. //rework of code??
                if (bParse && numOfShares > 0 && user.BuyStock(company.Name, company.Symbol, company.getStockPrice(), numOfShares, now))
                {
                    statusUserCash.Text = user.Cash.ToString("C2");

                    if (string.IsNullOrEmpty(tradeCurrentSharesBox.Text))
                    {
                        tradeCurrentSharesBox.Text = numOfShares.ToString();
                    }
                    else
                        tradeCurrentSharesBox.Text = (Convert.ToDouble(tradeCurrentSharesBox.Text) + numOfShares).ToString();
                }
                else
                {
                    if(numOfShares < 1)
                         MessageBox.Show("Invalid Data in number of stocks.");
                }
            }
            else
            {
                MessageBox.Show("No company selected or field is empty!!!");
            }
        }

        private void tradeNumOfShares_TextChanged(object sender, EventArgs e)
        {
            int index = searchResults.SelectedIndex;
            if (index > -1 && tradeNumOfShares.Text.Length>0)
            {
                Company company = results[index];
               
                 int numOfShares = 0;
                 bool bParseSucces = false;

                bParseSucces = int.TryParse(tradeNumOfShares.Text, out numOfShares);

                if (bParseSucces)
                {
                
                    transAmBox.Text = (company.getStockPrice() * numOfShares).ToString("C2");
                }
             
                else
                {
                    MessageBox.Show("Non-Numerial Entry in Number of Share", "Invalid Input");
                    tradeNumOfShares.Text = "";
                }
            }
            else if (tradeNumOfShares.Text.Length == 0) 
            {
               
            }
            else
            {
                MessageBox.Show("No company selected!!!!");
            }

        }

        private void mainTab_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mainTab.SelectedIndex == 0)
                updateOverview();
            if (mainTab.SelectedIndex == 1)
                fill_Portfolio();
            if (mainTab.SelectedIndex == 2)
                clearTrade(); 
            else
                clearTrade();
            if (mainTab.SelectedIndex == 3)
                updatePerformance(); 
        }

        public void clearTrade()
        {
            searchBox.Text = "";
            tradeCurrentSharesBox.Text = "";
            tradeCompanyName.Text = "";
            tradeSymbol.Text = "";
            tradeStockPrice.Text = "";
            tradeExchange.Text = "";
            tradeIPO.Text = "";
            tradeIndustry.Text = "";
            tradeHigh.Text = "";
            tradeLow.Text = "";
            tradeNumOfShares.Text = "";
            transAmBox.Text = "";
        }

        public void fill_Portfolio()
        {
            portDataGrid.Rows.Clear();
            portDataGrid.Refresh();
            portDataGrid.ColumnCount = 7;
            portDataGrid.Columns[0].Name = "Company Name";
            portDataGrid.Columns[1].Name = "Company Symbol";
            portDataGrid.Columns[2].Name = "Number of Shares";
            portDataGrid.Columns[3].Name = "Current Price";
            portDataGrid.Columns[4].Name = "Worth";
            portDataGrid.Columns[5].Name = "Total Invested";

            List<Holding> stocks = user.Holdings;
            //loop through the purchased stocks.
            foreach (Holding stock in stocks)
            {
                string[] row = new string[6];
                row[0] = stock.companyName;
                row[1] = stock.stockSymbol;
                row[2] = stock.numOfShares.ToString();
                row[3] = stock.currentSharePrice.ToString("C2");
                row[4] = stock.worth.ToString("C2");
                row[5] = stock.totalInvested.ToString("C2");
                portDataGrid.Rows.Add(row);
            }
        }

        private void label9_Click(object sender, EventArgs e)
        {

        }

        private void tradeSellButton_Click(object sender, EventArgs e)
        {
            int index = searchResults.SelectedIndex;
            if (index > -1)
            {
                Company company = results[index];
                int numOfShares = 0;
                bool bParse = int.TryParse(tradeNumOfShares.Text, out numOfShares);
                DateTime now = DateTime.Now;
                double price = company.getStockPrice();

                //had to use short circuiting 
                if (bParse && numOfShares > 0 && user.SellStock(company.Name, company.Symbol, price, numOfShares, now))
                {
                    tradeCurrentSharesBox.Text = (Convert.ToDouble(tradeCurrentSharesBox.Text) - numOfShares).ToString();
                }
                else
                    MessageBox.Show("Error in Number of stocks.");
                statusUserCash.Text = user.Cash.ToString("C2");
               
            }
                
            else
            {
                MessageBox.Show("No company selected!!!");
            }
        }

        private void watchButton_Click(object sender, EventArgs e)
        {
            int index = searchResults.SelectedIndex;
            if (index > -1)
            {
                Company company = results[index];
                user.AddToWatchList(company);
            }
            else
            {
                MessageBox.Show("No company selected.");
            }
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings settings = new Settings(user);
            settings.ShowDialog();
            user=settings.getUser();
            statusUserCash.Text = user.Cash.ToString("C2");
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            refreshThread.Abort();
            base.OnFormClosing(e);
            LoginController.Logout(user);
            if (e.CloseReason == CloseReason.WindowsShutDown) return;
        }

        public void updatePerformance()
        {
            performanceHoldingsBox.Items.Clear();
            List<Holding> holdings = user.Holdings;
            //loop through the purchased stocks.
            foreach (Holding holding in holdings)
            {
                performanceHoldingsBox.Items.Add(String.Format("{0} | {1} | {2}", holding.companyName, holding.currentSharePrice.ToString("C2"), holding.GetPerformance().ToString("P")));
            }

            //load initial graph.
            updatePerformanceGraph("", "");
        }

        public void updatePerformanceGraph(string symbol, string timePeriod)
        {
            performancePic.Load("http://chart.finance.yahoo.com/z?s=" + symbol + "&t="+timePeriod);
        }

        private void performanceHoldingsBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            updatePerformanceGraph(getHoldingBoxString(), getTimeBoxString());
        }
        private string getHoldingBoxString()
        {
            int i = performanceHoldingsBox.SelectedIndex;
            if (i < 0)
                return "";
            List<Holding> holdings = user.Holdings;
            return holdings[i].stockSymbol;
        }

        private void performanceTimeBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            updatePerformanceGraph(getHoldingBoxString(), getTimeBoxString());
        }
        private string getTimeBoxString()
        {
            int i = performanceTimeBox.SelectedIndex;
            if (i == 0)
                return "1d";
            else if (i == 1)
                return "5d";
            else if (i == 2)
                return "3m";
            else if (i == 3)
                return "6m";
            else if (i == 4)
                return "1y";
            else if (i == 5)
                return "2y";
            else if (i == 6)
                return "5y";
            else if (i == 7)
                return "my";
            else
                return "";
        }

        private void whatIfToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WhatIf whatIf = new WhatIf();
            whatIf.Show();
        }

        private void ButtonWatchlistDelete_Click(object sender, EventArgs e)
        {
            user.WatchList.RemoveAt(ListBoxWatchlist.SelectedIndex);
            ListBoxWatchlist.Items.RemoveAt(ListBoxWatchlist.SelectedIndex);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.DefaultExt = "*.ftr";
            DialogResult result = fileDialog.ShowDialog();
            if (result == DialogResult.OK)
                user.GenerateReport(fileDialog.FileName);
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace transaction
{

    struct CompanyStockInfo
    {
        public string Name;
        public string Symbol;
        public string Spent;
        public string Earned;
        public string Shares;
    
    }

    class CompanyStock
    {
        String sName;
        string sSymbol;
        double dSpent;
        double dEarned;
        double dShares;

        public CompanyStockInfo GetDescriptor()
        {
            CompanyStockInfo Temp = new CompanyStockInfo();
            Temp.Name = sName;
            Temp.Symbol = sSymbol;
            Temp.Spent = dSpent.ToString();
            Temp.Earned = dEarned.ToString();
            return Temp;
            
        
        }
        public CompanyStock()
        {
            sName = "default";
            sSymbol = "dt";
            dSpent = 0;
            dEarned = 0;
            dShares = 0;
        }

        public CompanyStock(string name, string symbol, double spent, double earned, double shares)
        {
           if(!SetName(name)) // bad name entered
           {
              sName = "Error";
           }
            if(!SetSymbol(symbol))
            {
               sSymbol = "err";
            }

            if(!SetSpent(spent))
            {
               dSpent = 0.0;
            }

            if(!SetEarned(earned)) // again an error by the user.
            {
               dEarned = 0.0;
            }

            if(!SetShares(shares))
            {
               dShares = 0.0;
            }
        
        }
        
        public string GetName()
        {
            return sName;
        }

        public bool SetName(string name)
        {
            if (name != null && name.Length > 0)
            {
                sName = name;
                return true;
            }
            return false;
        }

        public string GetSymbol()
        {
            return sSymbol;
        }

        public bool SetSymbol(string symbol)
        {
            if (symbol != null && symbol.Length > 0)
            {
                sSymbol = symbol;
                return true;
            }
            return false;
        }

        public double GetSpent()
        {
            return dSpent;
        }

        public bool SetSpent(double spent)
        {
            if (spent >= 0.0)
            {
                dSpent = spent;
                return true;
            }
            return false;
        }

        public double GetEarned()
        {
            return dEarned;
        }

        public bool SetEarned(double earned)
        {
            if (earned >= 0.0)
            {
                dEarned = earned;
                return true;
            }
            return false;
        }

        public double GetShares()
        {
            return dShares;
        }


        public bool SetShares(double shares)
        {
            if (shares >= 0.0)
            {
                dShares = shares;
                return true;
            }
            return false;
        }

    }
}
