You are on page 1of 10

Building a Yahoo stock quote ticker: ASP Alliance Page 1 of 10

ASPAlliance: Articles, reviews, and samples for .NET


Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1

Building a Yahoo stock quote ticker


by Jason Perry page
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 75782/ 464

Summary
This article will take you through a step-by-step guide on how to create a Yahoo Stock Quote Ticker using ASP.Net and Flash
Remoting.

This tutorial requires prior knowledge of ASP.Net web services using C# and Flash MX as well as Flash UI component set 2 and
Flash Remoting installed.
Yahoo Stock Quote Ticker Overview
The Yahoo Quote Ticker consists of an ASP.Net web service that connects to Yahoo quotes and grabs detailed data on stocks. The
application also features a Flash-based user interface that scrolls through each stock using the Flash Ticker component.

This application follows n-tier application design by dividing the application into data, business, and presentation logic. This way a
designer can focus on building usable interfaces and leave the structure of the backend to the developers.
Building the Web Service
The first step in developing the Yahoo Quote Engine is creating the web service. The web service will be responsible from grabbing
the data from Yahoo and parsing this to create a friendly structure. In this application I'll use ASP.Net with C#, but web services
can easily be developed using VB.Net, Java and Code fusion.

We can start our web service by creating a file named YahooQuoteWebService.asmx in the editor of your choice. I'll use
DreamWeaver MX.

Once the file is created we'll declare the contents of the file as a web service using C# and also provide the class name with its
namespace.

<@ WebService Language="c#" class="outthebox.web.services.YahooQuoteWebService" >

http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 2 of 10

Next, let's build the structure for our web service by defining the namespaces to use, providing a namespace where our web
service will sit, and defining our service as a public class that implements the WebService object.

using System.Collections;
using System.Web.Services;
using System.Net;
using System.IO;

namespace outthebox.web.services
{

[WebService(Namespace="outthebox.web.services")]
public class YahooQuoteWebService : WebService
{
}
}

With our class declared we can implement the one and only method for this web service GetQuote( string ). This method will
handle the logic involved in getting our quotes from Yahoo.

[WebMethod(Description="Using stock symbol gets delayed stock information from Yahoo.",EnableSession=false)]


public string[] GetQuote( string symbol )
{
string url; //stores url of yahoo quote engine
string buffer;
string[] bufferList;
WebRequest webRequest;
WebResponse webResponse;

url = "http://quote.yahoo.com/d/quotes.csv?s="+symbol+"&d=t&f=sl1d1t1c1ohgvj1pp2wern";

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[] {','} );
return bufferList;
}

The above is a lot of code so I'll take you through the implementation chunk-by-chunk.
http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 3 of 10

First we have to create a connection to Yahoo and grab the quotes. The following code grabs a comma delaminated file from
Yahoo using the symbol variable and stores the results in a string variable named buffer.

url = "http://quote.yahoo.com/d/quotes.csv?s=" + symbol + "&d=t&f=sl1d1t1c1ohgvj1pp2wern";

Creates a connection to the url and stores our results in the string buffer array.
webRequest = HttpWebRequest.Create( url );
webResponse = webRequest.GetResponse();
using( StreamReader sr = new StreamReader( webResponse.GetResponseStream() ) )
{
buffer = sr.ReadToEnd();
sr.Close();
}

Once we have the results from Yahoo we need to break it up and store the results in a string array. This code calls the string
method Split( char[] ) to separate the buffer string into chunks using the comma as the delaminator. The method returns a string
[] (string array) with quotes details.

buffer = buffer.Replace( "\"", "" );


bufferList = buffer.Split( new char[] {','} );
return bufferList;

Now that you have a working web service, place it on your web server and go to the address in a web browser. You should see
Microsoft's web service page with information on how to access this web service. If you don't see the page make sure ASP.Net is
installed properly on your web server and check your code for errors.

http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 4 of 10

Connecting Flash to the Web Service


In order for your flash application to communicate with the web service, you need to install the Flash remoting package from
Macromedia. Also, it's very important that you place the flashgateway.dll file (included with Flash remoting for ASP.Net) into your
web server's bin folder and make the below changes to your web.config file. These changes will allow Flash to determine what
calls are meant for your flash application and call the proper web service. You'll also need to create a blank file named
gateway.aspx and place it on your web server. I placed this file in the same location as my web service, but it's up to you.

<httpModules>
<add name="GatewayController" type="FlashGateway.Controller.GatewayController,flashgateway" />
</httpModules>

To establish the connection to our web service we must include the NetServices.as file. This file, included with Flash remoting, will
implement the classes necessary to create a wrapper to our service.

Then we can create a connection to the web server gateway. In your code you will replace the //gateway.aspx
and //YahooQuoteWebService.asmx?wsdl with the address of your web server and path to the gateway.aspx and
YahooQuoteWebService.asmx files.

#include "NetServices.as"

////////////////////////////////////////////
// Inits Web Service
////////////////////////////////////////////

//
http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 5 of 10
//creates connection to ASP.Net web service
//should never ever run more than once!!
if( init == null )
{
//insures this code block is only run once
init = true;

//sets the gatway will always be this


NetServices.setDefaultGatewayURL("http:////gateway.aspx");
gatewayConnnection = NetServices.createGatewayConnection();

//gets the Yahoo quote service and sets instance


//uses WSDL to create proxy dll file
YahooQuoteWebService = gatewayConnnection.getService("http:////YahooQuoteWebService.asmx?wsdl", this);

We need to develop call back functions and wrappers for our web service methods. When we call the GetQuote( string ) method
on our web service, Flash will connect to the service and send the response back to _Result( result ) or _Status( error ). If a error
occurs while trying to connect to the service, the _Status( error ) call back will be used, otherwise _Result( result ) will be called
with the data from the service in the result object. Our result object is an array of strings so we can access this array like we
would any Flash array object. NOTE: For a full list of result objects supported by Flash, see the Flash Remoting documentation.

////////////////////////////////////////////
// Call Back Function Wrappers
////////////////////////////////////////////

//gets quote data from web service


function GetQuote( symbol )
{
YahooQuoteWebService.GetQuote( symbol );
trace( "getting " + symbol + " from yahoo quote web service" );
}

////////////////////////////////////////////
// Call Back Functions
////////////////////////////////////////////

//call back function for GetQuote method


function GetQuote_Result( result )
{
buffer = result[ 0 ] + " " + result[ 1 ] + " " + result[ 4 ];
trace( buffer );
}

//
http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 6 of 10
//call back function tracks status of GetQuote method
function GetQuote_Status( error )
{
trace( error.details );
}

After building our call back functions we can test our application by inserting the below lines of code at into our Action Script. This
code will get the symbol, current value, and change data for Microsoft and display it in your trace window.

GetQuote( "MSFT" );
Stop();
Creating the Flash Ticker Component
Now that the logic to grab our quotes is in place, we need to build the actual ticker. To do this you must install Flash UI
Components 2 from Macromedia and drag and drop the Ticker object into the main movie clip.

Next select your new ticker object and select the parameters tab on the properties bar. This will let us make the below
customizations for the desired look and feel.

z Speed = 15
z Spacing = 20
z Orientation = Horizontal

z Scroll Direction = Decremental


http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 7 of 10
z Frame Width = 0
z Highlight Color = #000066

You should also create a box with color #000066 behind the ticker for our background and reset the document size to 325 * 25.
When done your ticker should look like the one below.

With the look down, let's remove the test code on the main movie clip, GetQuote( "MSFT" ), and replace it with the below code.
This will allow us to enter as many stock quotes as we like at once.

////////////////////////////////////////////
// variables
////////////////////////////////////////////

quoteArray = new Array( "MSFT", "COKE", "SUNW", "MACR", "AAPL", "CTL", "AMD", "INTC", "DELL", "CSCO", "YHOO");
stop();

Next, let's change the instance name of our ticker to stockTicker and insert this code into the stockTicker movie clip. This code will
loop through the quoteArray array and insert each quote into our ticker when it loads.

//sets interval for timer


onClipEvent( load )

{
//
http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 8 of 10
//sets first set of stocks
_root.quoteArray.sort();
for( quotes in _root.quoteArray )
{
_root.GetQuote( _root.quoteArray[quotes] );
}

this.setDataAllWidth( 0 );
this.sortItemsBy( "text", "ASC" );
}

We're almost done, but first we need to change our GetQuote_Result( result ) call back function to add the quotes into the
stockTicker. The stockTicker.addItem method takes a string or TextFormat object and places it into the ticker.

//call back function for GetQuote method


function GetQuote_Result( result )
{
buffer = result[ 0 ] + " " + result[ 1 ] + " " +result[ 4 ];
stockTicker.addItem( { text:buffer, textColor:0xFFFFFF, background:false, bold:true, size:10 } );
}

Test the application and watch the stocks scroll.


Auto-Updating the Flash Ticker
We could stop here, but why not make our ticker auto update? We know that the Yahoo stock data is updated every 20 minutes
so let's make our stock ticker check how long its been running and update itself using that interval.

Luckily, Flash has included the getTimer() method, which allows us to get the time in milliseconds our application has been
running. With this we can set the current time on the timer and set an interval equal to 20 minutes or (20 * 60000). Now using
the ClipEvent( enterFrame ) call back function we can determine if the ticker has been running for 20 minutes and, if so, update
the stocks. For those who don't know, the ClipEvent( enterFrame ) is constantly called during the life time of an Flash Application,
making it a good place for constant data checks.

To implement the timer, make the following code changes to the stockTicker movie clip.

//sets interval for timer


onClipEvent( load )
{
var current = getTimer();
var interval = (20 * 60000); //every 10 minutes syncs stock data

//sets first set of stocks


this.removeAll();

_root.quoteArray.sort();

http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 9 of 10
for( quotes in _root.quoteArray )
{
_root.GetQuote( _root.quoteArray[quotes] );
}

this.setDataAllWidth( 0 );
this.sortItemsBy( "text", "ASC" );
}

//checks to see if timer has elapsed


onClipEvent( enterFrame )
{
//time has elapsed
if( (current + interval) <= getTimer() )
{
current = getTimer();

//gets new data fro stocks


this.removeAll();
_root.quoteArray.sort();
for( quotes in _root.quoteArray )
{
_root.GetQuote( _root.quoteArray[quotes] );
}

this.setDataAllWidth( 0 );
this.sortItemsBy( "text", "ASC" );
}
}
Conclusion
Conclusion

As you can imagine, this is only the tip of the iceberg. The possibilities of combining the power of ASP.Net for data and business
logic with the rich real time interface of Flash can make the most complex web applications simple to use. If you have any
questions or comments feel free to contact me at jason@jasonmperry.com and also download the source files here.

Product Spotlight
FREE Live Web Site Chat
Totally FREE for 1 Operator. No monthly fees. 100% ASP.NET. Initiate chat sessions from any web site. Sets up in
minutes. Click to Continue >>

http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008
Building a Yahoo stock quote ticker: ASP Alliance Page 10 of 10
Online Stock Trading
Trade stocks, CFDs on 21 major world
exchanges. Free Download!
www.SaxoBank.com

Average 30-150 pips daily


Signals from Automatic Forex System +
Expert Advisors for MetaTrader4
forexsoft.us

Excellent Investment
Fast-growing tropical hardwood trees are "a
near perfect asset".
tropicalhardwoods.com

©Copyright 1998-2008 ASPAlliance.com | Page Processed at 8/19/2008 9:40:47 PM


About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search

http://aspalliance.com/articleViewer.aspx?aId=112&pId=-1 8/20/2008

You might also like