Click here to Skip to main content
15,867,308 members
Articles / Web Development / XHTML

Stocks with Ext JS Charts

Rate me:
Please Sign up or sign in to vote.
4.71/5 (6 votes)
16 Jul 2009MIT7 min read 64.7K   1.4K   38   1
An example to display stock indexes in an Ext JS chart. Including an introduction to Ext JS, a simple introductory Ext JS example, and an introduction to the new charts feature. Concludes with a more comprehensive demo showing some more of Ext’s features.

This article has been taken from my blog. The original article is here.

Introduction

I'll keep the introduction to Ext JS brief, and then give a short primer to using Ext. Skip to the charts section if you're already familiar with Ext. Or skip straight to the end if you just want to see the final demo.

Ext JS is yet another JavaScript library. However, the emphasis is on UI widgets that allow you to build user interfaces in the browser. The concept is far from new, but the way Ext JS stands out from the contenders must be embarrassing. The library's widgets are visually stunning, feature-rich, and yet maintains high performance.

I will admit that I hadn't heard of Ext JS before working on a project last year that used it. I've been doing freelance web development for about five years, and I tend to keep quite up-to-date with web technologies, so I'm surprised that it had slipped under my radar.

Fairly recently, the team announced the latest release candidate of Ext 3.0. I wanted to experiment with some of the lesser-hyped new features, and so I've been working on a small experiment to display stock indexes using the new charts feature.

Hello, world!

Let's start by walking through a really simple Ext example before we look at the charts. Download the latest Ext release. Setup a simple HTML page and add a few includes:

XML
<link rel="stylesheet" type="text/css" 
  href="ext-3.0-rc3/resources/css/ext-all.css" />
<script type="text/javascript" 
  src="ext-3.0-rc3/adapter/ext/ext-base.js"></script>
<script type="text/javascript" 
  src="ext-3.0-rc3/ext-all-debug.js"></script>

At this point, we should be able to load the blank page in the browser without any errors.

The next step is to write some code to do something with the Ext library. So as not to upset the gods, we're going to make a pop-up 'hello world' window. The following is JavaScript code, so put it in a <script> tag or an external .js file.

JavaScript
Ext.onReady(function() {
  new Ext.Window({
    title: 'Hello, world!',
    width: 280,
    height: 120
  }).show();
});

We use Ext.onReady(...) to setup a callback for when the DOM is loaded. This callback will create a new Ext.Window object and show it. The parameter to the Ext.Window constructor is a configuration object.

The concept of configuration objects is used extensively throughout Ext, and it can be rather fiddly and difficult to get used to. You have to keep the Ext documentation open (see below) to know what parameters to use. In our simple example, all we do is specify the title and dimensions of the window.

Load the page in your browser. The result should look something like this:

hello-world.png

Notice that you can drag the window around the screen and resize it to your heart's content.

See the demo, or download the code.

For a nice collection of more advanced examples, check out the samples on the Ext site (they are also contained in the Ext download). These samples are great. My only criticism is that they can be a bit inconsistent in the way they implement features.

Another indispensable resource is the Ext documentation (this is also included in the download).

Ext JS Charts

In a way, it's a shame that Flash has been used to implement the charts feature, since the library has achieved so much without resorting to it in the past. Nevertheless, the actual Flash applet has been well contained, and even resizes smoothly with its container.

We can build on our simple example from above to add a chart to the window.

JavaScript
Ext.onReady(function() {

  var store = new Ext.data.JsonStore({
    url: 'data.php',
    baseParams: {
      symbol: 'GOOG'
    },
    autoLoad: true,
    root: 'data',
    fields: ['date', 'close']
  });

  new Ext.Window({
    title: 'GOOG',
    width: 400,
    height: 300,
    items: [
      new Ext.chart.LineChart({
        store: store,
        xField: 'date',
        yField: 'close'
      })
    ]
  }).show();
});

We are introducing two new concepts here. First of all, the use of a 'store'. In this case, a JsonStore. To quote the documentation:

The Store class encapsulates a client side cache of Record objects which provide input data for Components [...]

So basically, the store takes care of fetching and storing our data. The JsonStore uses a JsonReader to fetch the data in JSON format, keeping the data completely separate from the UI component. The data is then represented internally as a series of Records.

Let's look at the configuration parameters we have set. The first parameter, url, is the URL that we will be loading the data from, and baseParams specifies the parameters to send to this URL. By default, the store doesn't attempt to load the data straight away, so we specify the autoLoad parameter so that we don't have to call store.load() ourselves later on. The root parameter tells the store where to look in the returned object for the bulk of the records, and fields is a short-hand way to specify the structure of the individual records.

The second new concept we have introduced is the addition of a component to the window. We have done this by specifying an array of components in the 'items' property. The single item that we are adding is a LineChart component. The configuration here just links the component to the store we have defined, and specifies the fields to bind to the axes of the chart.

Once the store has been loaded, we should end up with this:

goog.png

See the demo, or download the code.

The current Ext documentation for styling the charts is fairly minimal. Since the underlying Flash applet for the charts is based on the one from the Yahoo! UI Library, further information on styling the charts can be obtained from their documentation.

Fetching the Data

Let's take a look now at the server-end of the process.

The data is generated by a PHP script which in turn gets the stock data from Yahoo!. Yahoo kindly provides a CSV-formatted data set of the daily stock prices (including open, close, high and low values) which go back about five years. We don't want to be pumping this much data to the browser, so we will take a few steps:

  1. Fetch the data if not already cached
  2. Extract the closing price for each day
  3. Cache the data
  4. Choose an appropriate range of dates to display
  5. Sample the remaining data to leave us with a suitable number of points that can be plotted
  6. Return the data encoded as JSON

We now have a simple Web Service that allows us to specify a number of parameters:

  • symbol — The stock ticker symbol. Required. Note that because we are using the Yahoo! stock data, we are limited to stocks listed on the NASDAQ.
  • start — The start date. Specified as a Unix timestamp. Defaults to roughly one year ago.
  • span — The timespan to get data for. Also given as a Unix timestamp. Defaults to roughly one year.
  • points — The number of points to sample. Defaults to 20.

An example result from the service would look a little like this:

{"symbol": "MSFT", "data": [
  {"date": "2008-07-24", "close": 25},
  {"date": "2008-08-12", "close": 28},
  //...
]}

I won't paste the PHP script here. It can, however, be downloaded.

Once the data has been successfully loaded, an event is raised, which the chart has been listening for. The chart can then re-draw itself using the new data.

Taking Things Further

In an attempt to mature our example a little, and to highlight a few of Ext's other features, I've put together a more substantial example. See the screenshot below, and refer to the live demo.

extstock.png

I won't go into much detail here, other than to list some of the features that I've used:

  • A Viewport together with the BorderLayout to ensure that the interface takes over all the space offered by the browser window.
  • A modal pop-up window which contains an auto-complete ComboBox. A list of the NASDAQ-100 is presented for the user to choose from.
  • A TabPanel to organise the different stocks that have been loaded. Selecting a different tab will change the chart being displayed, and closing a tab will unload the data and chart.
  • A ListView component, which is the new lightweight version of the GridPanel.
  • Some more advanced features of the Chart object—including making use of the TimeAxis, linking mouse movements to the ListView component, and making some changes to the chart's style.

I have left the JavaScript un-minified so feel free to take a look at it.

This article has been taken from my blog. The original article is here.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalhi Pin
chakram32121-Jul-09 18:59
chakram32121-Jul-09 18:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.