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 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.


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 ="stockContainer");
	var indicator ="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
			// Hide the indicator
			// 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
		// Show the indicator upon request
		onRequest: function () {
	// Send the request every 20 seconds
	(function() {
	}).periodical(20 * 1000);
	// Send right away

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

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • By
    Create Snook-Style Navigation Using MooTools

    Jonathan Snook debuted a great tutorial last September detailing how you can use an image and a few jQuery techniques to create a slick mouseover effect. I revisited his article and ported its two most impressive effects to MooTools. The Images These are the same...

  • By
    Redacted Font

    Back when I created client websites, one of the many things that frustrated me was the initial design handoff.  It would always go like this: Work hard to incorporate client's ideas, dream up awesome design. Create said design, using Lorem Ipsum text Send initial design concept to the client...


  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

    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}.


  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!