public SelectList GetPossibleStocks() { List <StockQuote> Quotes = new List <StockQuote>(); List <string> TempList = new List <string>(); List <string> Newlist = new List <string>(); var query = (from s in db.StockLists select new { value1 = s.Ticker, value2 = s.StockType, value3 = s.TransactionFee }).Union(from sp in db.StockLists select new { value1 = sp.Ticker, value2 = sp.StockType, value3 = sp.TransactionFee }).Union(from spz in db.StockLists select new { value1 = spz.Ticker, value2 = spz.StockType, value3 = spz.TransactionFee }); foreach (var item in query) { TempList.Add(item.value1 + "," + Convert.ToString(item.value2) + "," + Convert.ToString(item.value3)); } foreach (string Ticker in TempList) { int final = Ticker.Length; int begin = Ticker.IndexOf(','); int end = Ticker.LastIndexOf(','); string Tick = Ticker.Substring(0, begin); StockQuote sq = GetQuote.GetStock(Tick); sq.Type = Ticker.Substring(begin + 1, end - begin - 1); string finalfee1 = Ticker.Substring(end + 1, final - end - 1); decimal finalfee = Convert.ToDecimal(finalfee1); sq.Fee = finalfee; Quotes.Add(sq); } foreach (StockQuote quote in Quotes) { Newlist.Add(quote.Symbol + ", " + Convert.ToString(quote.PreviousClose) + " per share, " + quote.Name + ", " + quote.Type + ", " + Convert.ToString(quote.Fee) + " per purchase"); } SelectList selectedStock = new SelectList(Newlist); return(selectedStock); }
protected StockQuote MapJsonToStockitems(string jsonResults) { using (var sr = new StringReader(jsonResults)) { var sq = new StockQuote(); string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith(",\"t\"")) { sq.Ticker = line.Replace(",\"t\" : ", "").Trim().Trim('"'); continue; } if (line.StartsWith(",\"c\"")) { sq.Change = decimal.Parse(line.Replace(",\"c\" : ", "").Trim().Trim('"')); continue; } if (line.StartsWith(",\"l\"")) { sq.LastTradePrice = decimal.Parse(line.Replace(",\"l\" : ", "").Trim().Trim('"')); continue; } if (line.StartsWith(",\"ltt\"")) { sq.LastTradeTime = line.Replace(",\"ltt\":", "").Trim().Trim('"').Replace("EST", "").Trim(); continue; } } return(sq); } }
public void RetrieveQuotes(int count) { // make a request for data from ETrade StockSymbol Symbol; string responseXML; string symbol; StockQuote stock; for (int i = 0; i < count; i++) { Symbol = StockSymbols.Instance.GetNextStock(); symbol = Symbol.Symbol; System.Threading.Thread.Sleep(250); responseXML = eTradeModel.GetQuote(symbol, "ALL"); if (responseXML != null) { WriteXML(responseXML); stock = StockQuote.ReadStockQuote(Symbol.Id, responseXML); _messages.AddMessage("Asked for " + symbol + ", Received " + stock.Quote.QuoteData.Product.Symbol); } else { _messages.AddMessage("Asked for " + symbol + ", Received nothing."); } } }
private void btnEtfBuyBasket_Click(object sender, EventArgs e) { if (etf == null) { return; } var orders = new List <Dwjk.Dtp.PlaceBatchOrder.Types.BatchOrderItem>(); etf.Items.ForEach((item) => { Stock stock = StockFacade.GetStock(item.Code); StockQuote quote = StockFacade.GetQuote(item.Code); if (stock == null || quote == null) { return; } if (!string.Equals(item.ReplaceFlag, "1")) { return; } orders.Add( Trader.NewBatchOrderItem( stock.SecurityId.Exchange == Exchange.Sh ? Dwjk.Dtp.Exchange.ShA : Dwjk.Dtp.Exchange.SzA, item.Code, quote.HighLimited.ToString(), (uint)item.Quantity, Dwjk.Dtp.OrderSide.Buy )); }); if (FrmOrderConfirm.ShowList(orders)) { Trader.BatchOrder(orders); } }
public OrderStatusType PlaceSellOrder(StockQuote quote, double price, double volume) { if (!OpenedPositions.TryGetValue(quote.Ticker, out var openedPosition)) { return(OrderStatusType.DeniedNoOpenPosition); } if (!price.InOpenRange(quote.Low, quote.High)) { return(OrderStatusType.DeniedOutOfRange); } if (volume >= openedPosition.Volume) { volume = openedPosition.Volume; OpenedPositions.Remove(quote.Ticker); } else { openedPosition.Decrease(volume); } TheLedger.Add(new StockTransaction { Ticker = quote.Ticker, Date = quote.DateParsed, Price = price, Volume = volume, TransactionType = StockTransactionType.Sell }); UpdateBalance(price, volume, StockTransactionType.Sell); return(OrderStatusType.Accepted); }
/// <summary> /// Refresh or add a stock symbol. /// </summary> /// <param name="symbol"> /// The symbol. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task <StockQuote> RefreshOrAdd(string symbol) { var quote = new StockQuote(); if (string.IsNullOrEmpty(symbol)) { return(quote); } try { quote = await this.stockQuoteService.GetStockQuoteAsync(symbol); var existingQuote = this.StockQuotes.Data.Cast <StockQuote>().FirstOrDefault(a => a.Symbol == symbol); if (existingQuote == null) { this.StockQuotes.Add(quote); } else { this.StockQuotes.Replace(existingQuote, quote); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } return(quote); }
private static Company GetStub() { const string ticker = "test"; var testQuote = new StockQuote { Close = 10, Date = 20001010, Ticker = ticker, High = 10, Low = 10, Volume = 1000, Open = 10, TotalSharesEmitted = 100000, MarketCap = 200000, BookValue = 1000, DividendYield = 1.0, PriceToEarningsRatio = 2 }; var testStock = new Company { Quotes = new List <StockQuote> { testQuote }, Ticker = ticker }; return(testStock); }
public List <StockQuote> StockQuotes() { UserManager <AppUser> userManager = new UserManager <AppUser>(new UserStore <AppUser>(db)); //Get the current user as an AppUser object var user = userManager.FindById(User.Identity.GetUserId()); //Get the list of the ticker for each stock in the user's portfolio List <StockDetail> stockDetailList = user.StockPortfolio.StockDetails; List <string> tickersInAccount = new List <string>(); foreach (StockDetail detail in stockDetailList) { string tickerInQuestion = detail.Stock.StockTicker; tickersInAccount.Add(tickerInQuestion); } //Return a quote for each stock in the user's account List <StockQuote> Quotes = new List <StockQuote>(); foreach (string ticker in tickersInAccount) { StockQuote sq1 = GetQuote.GetStock(ticker); Quotes.Add(sq1); } //Return the list with a quote for each stock that is in the account return(Quotes); }
public static StockQuote GetStock(String symbol, DateTime date) { if (date == DateTime.Today) { return(GetStock(symbol)); } //http://finance.yahoo.com/q/hp?s=WU&a=01&b=19&c=2010&d=01&e=19&f=2010&g=d String month = (date.Month - 1).ToString(); String day = date.Day.ToString(); String year = date.Year.ToString(); string baseURL = "http://ichart.finance.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d&ignore=.csv&h=npl1v"; //http://ichart.finance.yahoo.com/table.csv?s=WU&a=01&b=19&c=2010&d=01&e=19&f=2010&g=d&ignore=.csv&h=pl1vn string url = string.Format(baseURL, symbol, month, day, year, month, day, year); //Get page showing the table with the chosen indices System.Net.HttpWebRequest request = null; Console.WriteLine(url); //csv content string docText = string.Empty; StockQuote stock = null; try { request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); request.Timeout = 300000; using (var response = (HttpWebResponse)request.GetResponse()) using (StreamReader stReader = new StreamReader(response.GetResponseStream())) { string output = stReader.ReadLine(); //go to line with actual data output = stReader.ReadLine(); //output = stReader.ReadLine(); //Date,Open,High,Low,Close,Volume,Adj Close //2010 - 02 - 19,16.389999,16.459999,16.27,16.35,6963200,13.508243 string[] sa = output.Split(new char[] { ',' }); stock = new StockQuote(); stock.Symbol = symbol; stock.Name = GetStock(symbol).Name; stock.PreviousClose = double.Parse(sa[4]); stock.LastTradePrice = double.Parse(sa[6]); stock.Volume = double.Parse(sa[5]); } } catch (Exception e) { //Throw some exception here. } return(stock); }
public void EqualsReturnsFalseForUnequalStocks(StockQuote quote1, StockQuote quote2) { Assert.False(quote1 == quote2); Assert.False(Equals(quote1, quote2)); Assert.False(quote1.Equals(quote2)); Assert.False(quote2.Equals(quote1)); }
public ActionResult About() { ViewBag.Message = "Your application description page."; StockQuote stockquote = ctx.StockQuotes.Where(x => x.Close == 14).FirstOrDefault(); return(View(stockquote)); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var quote = (StockQuote)e.Parameter; Quote = quote; }
private static decimal CalculateGainLoss(StockQuote quote, Position position) { var moneyISpent = position.PricePerShare * position.Shares; var moneyItsWorth = position.Shares * quote.LastTradePrice; return(moneyItsWorth - moneyISpent); }
public static void RetrieveQuotes() { // make a request for data StockSymbol Symbol; StockQuotesDataService DataService = new StockQuotesDataService(); string symbol; do { Symbol = StockSymbols.Instance.GetNextStock(); symbol = Symbol.Symbol; StockQuote stock = new StockQuote(Symbol.Id); stock.Quote.QuoteData.Product.Symbol = symbol; string url = GetURL(2, symbol); Console.WriteLine(url); Stream stream = GetResponse(url); // responseXML = eTradeModel.GetQuote(symbol, "ALL"); // WriteXML(responseXML); StreamReader sr = new StreamReader(stream); string line = sr.ReadLine(); // skip the header while (sr.Peek() >= 0) { line = sr.ReadLine(); stock.Parse(line); stock.Save(DataService); } //stock = StockQuote.ReadStockQuote(Symbol.Id, responseXML); } while (StockSymbols.Instance.Index > 0); // _messages.AddMessage("Asked for " + symbol + ", Received " + stock.Quote.QuoteData.Product.Symbol); }
private void UpdateQuoteListViewItem(ListViewItem item, StockQuote quote) { item.Tag = quote; if (quote != null) { item.ForeColor = this.stocksView.ForeColor; item.SubItems["Volume"].Text = quote.Volume.ToString("N0", CultureInfo.CurrentCulture); item.SubItems["Last"].Text = quote.Last.ToString("N4", CultureInfo.CurrentCulture); item.SubItems["Change"].Text = quote.Change.ToString("N2", CultureInfo.CurrentCulture); item.SubItems["Change"].ForeColor = quote.Change < 0d ? Color.Red : Color.Green; item.SubItems["PercentChange"].Text = quote.PercentChange.ToString("P", CultureInfo.CurrentCulture); item.SubItems["PercentChange"].ForeColor = quote.PercentChange < 0d ? Color.Red : Color.Green; item.SubItems["LastUpdate"].Text = quote.LastUpdate.ToLongTimeString(); } else { item.ForeColor = Color.Gray; item.SubItems["Volume"].Text = "--"; item.SubItems["Last"].Text = "--"; item.SubItems["Change"].Text = "--"; item.SubItems["PercentChange"].Text = "--"; item.SubItems["LastUpdate"].Text = "--"; } StartFlash(item); }
private static TileText CreateNameTextForQuote(StockQuote quote) { return(new TileText { Text = quote.Symbol, Style = TileTextStyle.Body }); }
private void RefreshQuotes(List <string> symbols) { IDictionary <string, StockQuote> refreshedQuotes = null; try { refreshedQuotes = this.stockQuoteService.GetQuotes(symbols); } catch (StockQuoteServiceException) { logger.Log("Error invoking service", TraceEventType.Error); this.view.NotifyServiceStatus("Error invoking service"); return; } catch (Exception) { logger.Log("Unknown error invoking service", TraceEventType.Error); this.view.NotifyServiceStatus("Unknown error invoking service"); return; } List <StockQuote> updatedQuotes = new List <StockQuote>(); lock (quotesLock) { foreach (KeyValuePair <string, StockQuote> kvp in refreshedQuotes) { StockQuote currentQuote; StockQuote updatedQuote = kvp.Value; if (this.quotes.TryGetValue(kvp.Key, out currentQuote)) { if ((currentQuote == null && updatedQuote != null) || (currentQuote != null && updatedQuote != null && currentQuote.LastUpdate < updatedQuote.LastUpdate)) { this.quotes[kvp.Key] = updatedQuote; updatedQuotes.Add(updatedQuote); logger.Log("StockQuote for " + kvp.Key + " was updated", TraceEventType.Information); SaveQuote(updatedQuote); } else { logger.Log("StockQuote for " + kvp.Key + " was not updated", TraceEventType.Information); } } else { logger.Log("Received quote for unknown symbol " + kvp.Key, TraceEventType.Warning); } } } if (updatedQuotes.Count > 0) { logger.Log("Updates received, updating view", TraceEventType.Information); this.view.UpdateQuotes(updatedQuotes); } }
private decimal CalculateBidAskDiff(StockQuote stock) { decimal bidVol = stock.TotalBidVol; decimal askVol = stock.TotalAskVol; return(bidVol - askVol); }
public void GetQuoteCallback(IAsyncResult ar) { Thread.Sleep(5000); asd = ((YahooQuotesClient)ar.AsyncState).EndGetQuoteForStockSymbol(ar); MessageBox.Show("작업 완료"); }
private static TileText CreateArrowTextForQuote(StockQuote quote) { return(new TileText { Text = quote.IsDown ? "▼" : "▲", Style = TileTextStyle.Body, Align = TileTextAlign.Right }); }
public IActionResult Quote() { List <Company> companies = JsonConvert.DeserializeObject <List <Company> >(TempData["Companies"].ToString()); Dictionary <String, Dictionary <String, Quote> > companiesQuotes = JsonConvert.DeserializeObject <Dictionary <String, Dictionary <String, Quote> > >(TempData["CompaniesQuote"].ToString()); StockQuote companiesQuoteRoot = new StockQuote(companies, companiesQuotes); return(View(companiesQuoteRoot)); }
/// <summary> /// Update a single StockQuote /// </summary> /// <param name="id"></param> /// <param name="stockQuote"></param> public void PutStockQuote(string id, StockQuote stockQuote) { stockQuote.SetIdentifier(id); if (!stockQuoteStore.Update(stockQuote)) { throw new HttpResponseException(HttpStatusCode.NotFound); } }
public IActionResult Index() { var model = new StockQuote { Symbol = "HLLO", Price = 3200 }; return(View(model)); }
public static bool UpdateStockObjectWithTechnicalAnalysisData(StockQuote qoute, ref Stock stock) { //---------variables-----------// int count = qoute.stock_candles.Count; int outBegIdx = 0; int startIdx = 0; int endidx = 0; int outNBElement = 0; int[] outInteger = new int[1]; double[] outDouble = new double[1]; float[] outFloat = null; float[] inOpen = new float[count]; float[] inClose = new float[count]; float[] inHigh = new float[count]; float[] inLow = new float[count]; int i = 0; int outBegIndex; double[] output = new double[1]; // ---------------------------// foreach (Candle candle in qoute.stock_candles) { inOpen[i] = candle.open; inClose[i] = candle.close; inHigh[i] = candle.high; inLow[i] = candle.low; i++; } Core.RetCode retCode; endidx = inOpen.Length; startIdx = endidx - 3; //200 sma retCode = Core.Sma(startIdx, endidx, inClose, 200, out outBegIndex, out outNBElement, outDouble); stock.Sma200d = output[0]; //retCode = Core.Cdl3LineStrike((startIdx, endidx, inOpen, inHigh, inLow, inClose, 0, out outBegIndex, out outNBElement, outInteger); //if (retCode == Core.RetCode.Success) //{ // stock.JapaneseCandleStickPattern = (JapaneseCandleStick)Enum.Parse(typeof(JapaneseCandleStick), "CdlMorningDojiStar"); //} return(false); }
static PlainSingletonUseCase() { var logger = new Logger(); var errorHandler = new ErrorHandler(logger); var database = new Database(logger, errorHandler); stockQuote = new StockQuote(logger, errorHandler, database); authenticator = new Authenticator(logger, errorHandler, database); }
public ActionResult StocksOwned() { //Gets user ID based on signed in user, and pulls their stock portfolio string user = User.Identity.GetUserId(); var query = from s in db.StockPortfolios where s.AppUser.Id == user select s.StockPortfolioID; List <Int32> Newlist = query.ToList(); //Grabs the StockPortfolioID from that user's stock portfolio Int32 StockPortID = Newlist[0]; //Get the associated Stock bridges var query2 = from s in db.StockPortfolios where s.StockPortfolioID == StockPortID select s.StockBridges; List <List <StockBridge> > Bridge1 = query2.ToList(); List <StockBridge> Holder = Bridge1[0]; List <StockBridge> Bridge = new List <StockBridge>(); foreach (var item in Holder) { Bridge.Add(item); } List <StockViewModel> Views = new List <StockViewModel>(); foreach (var item in Bridge) { if (item.NumberShares != 0) { //Create an instance of the StockViewModel Model StockViewModel entry = new StockViewModel(); //Selects the name of the stock associated with the current instance of Bridge var query3 = from s in db.StockLists where item.StockList.StockListID == s.StockListID select s.Name; //Selects the Ticker symbol of the stock associated with the current instance of Bridge var query4 = from s in db.StockLists where item.StockList.StockListID == s.StockListID select s.Ticker; List <string> Temp = query4.ToList(); StockQuote sq = GetQuote.GetStock(Temp[0]); List <string> Temporary = query3.ToList(); entry.StockName = Temporary[0]; entry.Symbol = Temp[0]; entry.PurchasePrice = item.OriginalPrice; entry.NumShares = Convert.ToInt32(item.NumberShares); entry.CurrentPrice = Convert.ToDecimal(sq.PreviousClose); entry.Difference = entry.PurchasePrice - entry.CurrentPrice; entry.TotalChange = (entry.PurchasePrice - entry.CurrentPrice) * entry.NumShares; entry.StockBridgeID = Convert.ToString(item.StockBridgeID); Views.Add(entry); } } ViewBag.Views = Views; return(View(Views)); }
static void Main(string[] args) { var quote = new StockQuote("test", "6.1e-7"); string data = JsonConvert.SerializeObject(quote); Console.WriteLine(data); StockQuote quoteTwo = JsonConvert.DeserializeObject <StockQuote>(data); Console.ReadLine(); }
/// <summary> /// Delete a single StockQuote /// </summary> /// <param name="id"></param> public void DeleteStockQuote(string id) { StockQuote toDelete = stockQuoteStore.Get(id); if (toDelete == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } stockQuoteStore.Delete(id); }
public ActionResult Create([Bind(Include = "StockQuoteID,Symbol,StockType,Name,PreviousClose,LastTradePrice,Volume,PurchasePrice,PurchaseFee")] StockQuote stockquote) { if (ModelState.IsValid) { db.StockQuotes.Add(stockquote); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(stockquote)); }
public void ToStringReturnsTickerAndDate() { const string ticker = "IDK"; const int date = 19900101; var tested = new StockQuote { Ticker = ticker, Date = date }; Assert.Equal($"{ticker} {date}", tested.ToString()); }
private decimal CalculateAvgTradeVol(StockQuote stock) { decimal vol = stock.Volume; int trades = stock.NumTrades; if (trades == 0) { return(Decimal.Zero); } return(vol / trades); }
private static void Main() { IStockQuote qt = new StockQuote(); WebService svc = new WebService(qt); FetchStockQuotesSync(svc); FetchStockQuotesApm(svc); #if AsyncEnumerator FetchStockQuotesAsyncEnumerator(svc); #endif FetchStockQuotesAsyncCtp(svc); Console.ReadLine(); }
public StockQuote GetQuoteForStockSymbol(String tickerSymbol) { StockQuote sq = new StockQuote(); string buffer; string[] bufferList; WebRequest webRequest; WebResponse webResponse; // Use the data dictionary at the end of the big listing to // decipher the end of this url. String url = "http://quote.yahoo.com/d/quotes.csv?s=" + tickerSymbol + "&f=l1d1t1pomvc1p2n"; // ok, now that we have a URL, we'll go get some data which will return to us // in a nicely packaged csv format. webRequest = HttpWebRequest.Create(url); webResponse = webRequest.GetResponse(); // Now we'll put it in a stream buffer to make text replacement easier using (StreamReader sr = new StreamReader(webResponse.GetResponseStream())) { buffer = sr.ReadToEnd(); sr.Close(); } // We're going to strip out the " marks buffer = buffer.Replace("\"", ""); // Now we'll put it in a char array bufferList = buffer.Split(new char[] { ',' }); sq.LastTradePrice = bufferList[0]; // 1l sq.DateOfTrade = bufferList[1]; // d1 sq.TimeOfTrade = bufferList[2]; // t1 sq.PreviousClose = bufferList[3]; // p sq.Open = bufferList[4]; // o sq.DaysRange = bufferList[5]; // m sq.Volume = bufferList[6]; // v sq.Change = bufferList[7]; // c1 sq.PercentageChange = bufferList[8]; // p2 sq.CompanyName = bufferList[9]; // n return sq; }
private void PrintQuote(object sender, RoutedEventArgs e) { if( asd == null) { MessageBox.Show("작업 중"); return; } LastTradePrice.Content = asd.LastTradePrice; TradeDate.Content = asd.DateOfTrade; LastTradeTime.Content = asd.TimeOfTrade; DaysRange.Content = asd.DaysRange; DaysChange.Content = asd.Change; DaysPercentage.Content = asd.PercentageChange; CompanyName.Content = asd.CompanyName; asd = null; }
public StockQuote GetQuoteForStockSymbol(String tickerSymbol) { StockQuote sq = new StockQuote(); string buffer; string[] bufferList; WebRequest webRequest; WebResponse webResponse; String url = "http://quote.yahoo.com/d/quotes.csv?s=" + tickerSymbol + "&f=l1d1t1pomvc1p2n"; webRequest = HttpWebRequest.Create(url); webResponse = webRequest.GetResponse(); using (StreamReader sr = new StreamReader(webResponse.GetResponseStream())) { buffer = sr.ReadToEnd(); sr.Close(); } buffer = buffer.Replace("\"", ""); bufferList = buffer.Split(new char[] { ',' }); sq.LastTradePrice = bufferList[0]; sq.DateOfTrade = bufferList[1]; sq.TimeOfTrade = bufferList[2]; sq.PreviousClose = bufferList[3]; sq.Open = bufferList[4]; sq.DaysRange = bufferList[5]; sq.Volume = bufferList[6]; sq.Change = bufferList[7]; sq.PercentageChange = bufferList[8]; sq.CompanyName = bufferList[9]; return sq; }
private void SyncQuote(int id) { OPIMsysContext stockquotes = new OPIMsysContext(); DateTime weekago = DateTime.Today.AddDays(-7).ToUniversalTime(); DateTime lessFifteen = DateTime.Today.AddMinutes(-15).ToUniversalTime(); //Remove any quotes over a week old or under 15 minutes var deleteQuotes = from r in stockquotes.StockQuotes where (r.QuoteDate < weekago || r.QuoteDate > lessFifteen) && r.StockSymbolId == id select r; foreach (var deleteQuote in deleteQuotes) { stockquotes.StockQuotes.Remove(deleteQuote); } var stock = stockquotes.StockSymbols.FirstOrDefault((s) => s.StockSymbolId == id); if (stock != null) { var market = (from s in stockquotes.Markets where s.MarketId == stock.MarketId select s).FirstOrDefault(); switch (market.MarketName) { case "NYM": { //Test for weekday if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday) return; //Test for open hours var time = market.MarketOpen.Split(':'); DateTime mrkOpen = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); time = market.MarketClose.Split(':'); DateTime mrkClose = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); if (DateTime.Now.ToUniversalTime() < mrkOpen || DateTime.Now.ToUniversalTime() > mrkClose) return; string symbol = stock.Symbol; if (symbol == "CL") { switch (DateTime.Today.Month) { case 1: symbol = "CLG"; break; case 2: symbol = "CLH"; break; case 3: symbol = "CLJ"; break; case 4: symbol = "CLK"; break; case 5: symbol = "CLM"; break; case 6: symbol = "CLN"; break; case 7: symbol = "CLQ"; break; case 8: symbol = "CLU"; break; case 9: symbol = "CLV"; break; case 10: symbol = "CLX"; break; case 11: symbol = "CLZ"; break; case 12: symbol = "CLF"; break; } symbol += DateTime.Today.Year.ToString().Substring(2); } string url = "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + ".NYM" + "&f=d2ohgc1vl1"; WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); StockQuote quote = new StockQuote(); quote.StockSymbolId = stock.StockSymbolId; quote.QuoteDate = DateTime.Now.ToUniversalTime(); if (returnVal[0] != "-") quote.TradeDate = DateTime.Parse(returnVal[0]); if (returnVal[1] != "N/A") quote.Open = Decimal.Parse(returnVal[1]); if (returnVal[2] != "N/A") quote.High = Decimal.Parse(returnVal[2]); if (returnVal[3] != "N/A") quote.Low = Decimal.Parse(returnVal[3]); if (returnVal[4] != "N/A") quote.Change = Decimal.Parse(returnVal[4]); if (returnVal[5] != "N/A") quote.Volume = Int32.Parse(returnVal[5]); if (returnVal[6] != "N/A") quote.LastPrice = Decimal.Parse(returnVal[6]); stockquotes.StockQuotes.Add(quote); stockquotes.SaveChanges(); break; } case "NYSE": { //Test for weekday if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday) return; //Test for open hours var time = market.MarketOpen.Split(':'); DateTime mrkOpen = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); time = market.MarketClose.Split(':'); DateTime mrkClose = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); if (DateTime.Now.ToUniversalTime() < mrkOpen || DateTime.Now.ToUniversalTime() > mrkClose) return; //Get stock quote string url = "http://finance.yahoo.com/d/quotes.csv?s=" + stock.Symbol + "" + "&f=d2ohgc1vj3eyl1"; WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); StockQuote quote = new StockQuote(); quote.StockSymbolId = stock.StockSymbolId; quote.QuoteDate = DateTime.Now.ToUniversalTime(); if (returnVal[0] != "-") quote.TradeDate = DateTime.Parse(returnVal[0]); if (returnVal[1] != "N/A") quote.Open = Decimal.Parse(returnVal[1]); if (returnVal[2] != "N/A") quote.High = Decimal.Parse(returnVal[2]); if (returnVal[3] != "N/A") quote.Low = Decimal.Parse(returnVal[3]); if (returnVal[4] != "N/A") quote.Change = Decimal.Parse(returnVal[4]); if (returnVal[5] != "N/A") quote.Volume = Int32.Parse(returnVal[5]); if (returnVal[6] != "N/A") quote.MarketCap = returnVal[6]; if (returnVal[7] != "N/A") quote.EarningPerShare = Decimal.Parse(returnVal[7]); if (returnVal[8] != "N/A") quote.Dividend = Decimal.Parse(returnVal[8]); if (returnVal[9] != "N/A") quote.LastPrice = Decimal.Parse(returnVal[9]); stockquotes.StockQuotes.Add(quote); stockquotes.SaveChanges(); break; } case "TSX": { //Test for weekday if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday) return; //Test for open hours var time = market.MarketOpen.Split(':'); DateTime mrkOpen = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); time = market.MarketClose.Split(':'); DateTime mrkClose = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); if (DateTime.Now.ToUniversalTime() < mrkOpen || DateTime.Now.ToUniversalTime() > mrkClose) return; //Get stock quote string url = "http://finance.yahoo.com/d/quotes.csv?s=" + stock.Symbol + ".TO" + "&f=d2ohgc1vj1eyl1"; WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); StockQuote quote = new StockQuote(); quote.StockSymbolId = stock.StockSymbolId; quote.QuoteDate = DateTime.Now.ToUniversalTime(); if (returnVal[0] != "-") quote.TradeDate = DateTime.Parse(returnVal[0]); if (returnVal[1] != "N/A") quote.Open = Decimal.Parse(returnVal[1]); if (returnVal[2] != "N/A") quote.High = Decimal.Parse(returnVal[2]); if (returnVal[3] != "N/A") quote.Low = Decimal.Parse(returnVal[3]); if (returnVal[4] != "N/A") quote.Change = Decimal.Parse(returnVal[4]); if (returnVal[5] != "N/A") quote.Volume = Int32.Parse(returnVal[5]); if (returnVal[6] != "N/A") quote.MarketCap = returnVal[6]; if (returnVal[7] != "N/A") quote.EarningPerShare = Decimal.Parse(returnVal[7]); if (returnVal[8] != "N/A") quote.Dividend = Decimal.Parse(returnVal[8]); if (returnVal[9] != "N/A") quote.LastPrice = Decimal.Parse(returnVal[9]); stockquotes.StockQuotes.Add(quote); stockquotes.SaveChanges(); break; } case "TSX.V": { //Test for weekday if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday || DateTime.Today.DayOfWeek == DayOfWeek.Sunday) return; //Test for open hours var time = market.MarketOpen.Split(':'); DateTime mrkOpen = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); time = market.MarketClose.Split(':'); DateTime mrkClose = DateTime.Today.AddHours(Double.Parse(time[0])).AddMinutes(Double.Parse(time[1])); if (DateTime.Now.ToUniversalTime() < mrkOpen || DateTime.Now.ToUniversalTime() > mrkClose) return; //Get stock quote string url = "http://finance.yahoo.com/d/quotes.csv?s=" + stock.Symbol + ".V" + "&f=d2ohgc1vj1eyl1"; WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); StockQuote quote = new StockQuote(); quote.StockSymbolId = stock.StockSymbolId; quote.QuoteDate = DateTime.Now.ToUniversalTime(); if (returnVal[0] != "-") quote.TradeDate = DateTime.Parse(returnVal[0]); if (returnVal[1] != "N/A") quote.Open = Decimal.Parse(returnVal[1]); if (returnVal[2] != "N/A") quote.High = Decimal.Parse(returnVal[2]); if (returnVal[3] != "N/A") quote.Low = Decimal.Parse(returnVal[3]); if (returnVal[4] != "N/A") quote.Change = Decimal.Parse(returnVal[4]); if (returnVal[5] != "N/A") quote.Volume = Int32.Parse(returnVal[5]); if (returnVal[6] != "N/A") quote.MarketCap = returnVal[6]; if (returnVal[7] != "N/A") quote.EarningPerShare = Decimal.Parse(returnVal[7]); if (returnVal[8] != "N/A") quote.Dividend = Decimal.Parse(returnVal[8]); if (returnVal[9] != "N/A") quote.LastPrice = Decimal.Parse(returnVal[9]); stockquotes.StockQuotes.Add(quote); stockquotes.SaveChanges(); break; } } } else throw new HttpResponseException(HttpStatusCode.NotFound); }