Ejemplo n.º 1
0
        public IHttpActionResult GetHistoricalQuotes(int id, int days = 350)
        {
            string stockSymbol = db.Stocks.Where(s => s.ID == id).Select(s => s.Symbol).First();

            if (stockSymbol == null)
            {
                return(Content(HttpStatusCode.BadRequest, "Stock symbol not recognized."));
            }

            List <HistoricalStockPrice> result = new List <HistoricalStockPrice>();

            //Create startDate to be able to submit LINQ expression.
            DateTime startDate = DateTime.Now.AddDays(-days);
            List <HistoricalStockPrice> dbResult = db.HistoricalStockPrices.Where(hsp => hsp.StockID == id && hsp.Date >= startDate).OrderBy(s => s.Date).ToList();

            //if dbResult does not find the total number of days.
            if (dbResult.Count < ((Helper.GetWorkingDays(startDate, DateTime.Now)) - 1))
            {
                //Get historical quotes from API and save the missing dates in the DB.
                try
                {
                    List <HistoricalStockPrice> apiResult = DataFetcher.GetHistoricalStockPrice(stockSymbol, DateTime.Now.AddDays(-days), DateTime.Now, id).OrderBy(s => s.Date).ToList();
                    //var comparedResult = apiResult.Except(dbResult, new HistoricalStockPriceComparer()).ToList();
                    PostHistoricalStockPrices(apiResult.Except(dbResult, new HistoricalStockPriceComparer()).ToList());
                    result = apiResult;
                }
                catch (Exception)
                {
                    return(Content(HttpStatusCode.BadRequest, "Historical quotes not available at the moment."));
                }
            }
            else
            {
                //Othervise the dbResult is sufficient.
                result = dbResult;
            }

            //Add todays stock price to include it in the chart.
            StockPrice stockPrice = db.StockPrices.Where(st => st.StockID == id).OrderByDescending(st => st.Created).First();

            result.Add(
                new HistoricalStockPrice
            {
                AdjClose = stockPrice.Last,
                Close    = stockPrice.Last,
                Date     = stockPrice.Created,
                High     = stockPrice.DaysHigh,
                Low      = stockPrice.DaysLow,
                Open     = stockPrice.Open,
                Symbol   = stockPrice.Stock.Symbol,
                Volume   = 0
            }
                );

            return(Ok(result));
        }