RealTime Stock Quotes with MooTools Request.Stocks and YQL

By  on  

It goes without saying but MooTools' inheritance pattern allows for creation of small, simple classes that possess immense power.  One example of that power is a class that inherits from Request, Request.JSON, and Request.JSONP:  Request.Stocks.  Created by Enrique Erne, this great MooTools class acts as a wrapper for Request.JSON and Yahoo!'s YQL service.  Let me show you how to user Enrique's awesome MooTools JavaScript class!

The HTML

The stock content will be built by javascript but we will have two DIVS created within the page:

<div id="stockIndicator">Retrieving stock information....</div>
<div id="stockContainer"></div>

One DIV is an indicator which fades in an out during data fetch, the other is the container which will hold the stock information.

The CSS

As always, the styling of elements is subject to however you'd like them to look, but here's a really basic style set:

#stockContainer, #stockIndicator { width:500px; }
#stockContainer		{ background:#343434; padding:10px; }
#stockIndicator		{ text-align:right; visibility:hidden; padding:5px; }
.stockRow			{ padding:5px 10px; clear:both; margin-bottom:5px; }
	.stockName		{ font-size:14px; font-weight:normal; float:left; }
	.stockData		{ font-size:11px; float:right; width:200px; text-align:right; }

/* stock differential */`
.stockSame			{  }
.stockUp			{ background:lightgreen; }
	.stockUp .stockName	{ color:green; }
.stockDown			{ background:pink; }
	.stockDown .stockName { color:red; }

Stocks that are above for the day are green, below are red.  Stocks which have stayed the same are black.  Style however you'd like though.

The MooTools JavaScript

Before attacking an example usage, let's talk about about Request.Stocks.  This class is an extension of JSONP, setting numerous defaults that correspond to using Yahoo's YQL service, and adding additional options to customize the data you want to receive from Yahoo.  A few of the custom options include:

  • stocks: An array of symbols to retrieve stocks for
  • sortBy: The data field to sort by
  • display: The data fields to retrieve from Yahoo.  A few of the fields you can retrieve include: Ask, AverageDailyVolume, Bid, AskRealtime, BidRealtime, BookValue, Change&PercentChange, Change, Commission, ChangeRealtime, AfterHoursChangeRealtime, DividendShare, LastTradeDate, TradeDate, and more!

More detail on all of the custom options, some of which are not listed on this blog, can be found here.

So now to the class usage.  The sample code looks long but that's due to my commenting:

// When the dom is ready...
window.addEvent("domready",function() {
	// Get the stock container and indicator
	var container = document.id("stockContainer");
	var indicator = document.id("stockIndicator");
	// Create the instance
	var request = new Request.Stocks({
		// Stocks to retrieve
		stocks: ["AAPL","GOOG","MSFT"],
		// Formatter upon result
		onComplete: function(result) {
			// Log out the result to see the structure
			console.warn(result);
			// Hide the indicator
			indicator.fade(0);
			// Create a template with which to display the information
			var template = ' \
				<div class="stockRow stock{UpDown}"> \
					<div class="stockName">({symbol}) {Name}</div>\
					<div class="stockData">{Ask} {Change} {ChangeinPercent}</div> \
					<br class="clear" /> \
				</div> \
			';
			// For every stock , display its information in the template
			var html ="";
			Array.from(result.query.results.quote).each(function(quote) {
				// Add an "UpDown" property to the quote object
				var change = Number.from(quote.Change);
				quote.UpDown =  change == 0 ? "Same" : change > 0 ? "Up" : "Down";
				// Update running contnet
				html += template.substitute(quote);
			});
			// Update the content
			container.set("html",html);
		},
		// Show the indicator upon request
		onRequest: function () {
			indicator.fade(1);
		}
	});
	// Send the request every 20 seconds
	(function() {
		request.send();
	}).periodical(20 * 1000);
	// Send right away
	request.send();

Request.Stocks' onComplete method provides a method to handle the result from Yahoo.  Notice how I build the content string (using MooTools' string.substitute) and then set the element's HTML, instead of appending to the element's innerHTML property -- that's the more efficient way to change a node's content.  Also, remember that this class contains every method that Request, Request.JSON, and Request.JSONP have.

Request.Stocks is an outstanding utility class for developers looking to create applications based on stock market data.  The mix of flexibility and simplicity are real strong points of this class.  If I had one criticism of this class, it would be that it doesn't provide a method to add or remove stocks on the fly.  This functionality would allow the developer to create applications which allow users to add their own portfolio stocks without needing them all defined immediately.  Other than that, this class rock solid and I look forward to seeing where it goes in the future!

Recent Features

Incredible Demos

Discussion

  1. andy

    might be nice to take that console.warn out of the code, I had to open firebug to get it to work

  2. Yeah I agree with @andy – had to open up firebug to see the demo. Blame it on that console.warn()

  3. @davidwalsh thanks for featuring Request.Stocks.js. Asking for stocks on the fly will come for sure, though I’ll be quite busy for the next 2 month. It probably should be an optional argument to the send method.
    For issues, feature or pull request please https://github.com/eerne/Request.Stocks/issues

    Always enjoying your blog (especially today), DW FTW!

    • No worries dude, was just sharing an idea. Keep up the good work!

  4. hamburger

    sorry, my (the) demo do not show any stocks, it’s just black on firefox 3.6
    firebug do not show any error

    • hamburger

      it is working now. It seems that yahoo do not provide the data all time.
      now it’s OK.
      great david

    • Yeah, I’m probably making too many requests with all the hits the site gets. Sorry!

  5. kind of remember reading about a daily limit of 1000 hits, and with yahoo api key 100’000 hits/day.

  6. John Sanborn

    This is great! Is it possible to get the value of the indexes to show up?

    Like S&P 500, Dow, etc? I can get the change and percent change to show but not the {Ask}.

    thanks

  7. Works with long intervals. Maybe there is a new solution? Does anyone know how to insert the yahoo api key in the code?
    Thank you.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!