Appcelerator Developer Blog

Appcelerator Node.ACS Financial Stock Watch List

Implementing a Financial Stock Watch List may seem pretty straightforward at first, but optimizing it for mobile in the most efficient way possible presents a few challenges. Today, I’d like to walk you through how you can use the Appcelerator Mobile Platform to streamline API calls and data over the wire for your mobile applications leveraging remote data sources.

Appcelerator Custom Cloud Service (Node.ACS) allows Node.js based custom services to be published into the cloud and can be used to create a middleware tier to expose mobile-optimized web services to your application.

Instead of making multiple calls from the Titanium mobile client directly to the stock quote web service, we will create a Node.js service which will make multiple calls to a back end Stock Quote web service over the high speed internet and present aggregated data to the Titanium mobile client. The Titanium mobile client can then make a single mobile optimized web service call to Node.ACS over the slower cellular network to retrieve the Stock Watch List data. Furthermore, since the Watch List only displays 3 data values from the 13 provided by the stock quote web service, a substantial reduction in overhead is achieved which results in improved user experience and reduced data transmission.

The Problem

The mobile watch list we are trying to create is shown below:

The Stock Watch List displays a list of Stock Symbols as well as the Last Price and Change (from the prior day) for each stock symbol in the list. The “As of” time and date is useful to display as well so the user can see when the stock data was last retrieved.

The stock web service used in this example is from Markit On Demand.

In order to implement the watch list, repeated calls to a stock quote web service needs to be made; one call for each stock symbol the user is “watching”. The data then needs to be assembled and applied to a list control (i.e. TableView).

Below is an example of a stock quote REST web service call and JSON reply from MarkitOnDemand for the stock symbol AAPL (Apple Inc):

Call:

 

http://dev.markitondemand.com/Api/Quote/json?symbol=AAPL

Reply:

{
	"Data":{
		"Name":"Apple Inc", "Symbol":"AAPL", "LastPrice":424.04,
                "Change":-3.36899999999997,
		"ChangePercent":-0.788237964104632,
		"Timestamp":"Tue Jan 22 10:58:00 UTC-07:00 2012",
		"MarketCap":395266765800,
                "Volume":263809,
		"ChangeYTD":402.64,
                "ChangePercentYTD":5.31492151798133,
                "High":424.99,
		"Low":423.22,
		"Open":424.86
	}
}

From the reply above, you can see that we only need 3 of the 13 values returned by the web service for our watch list: LastPrice, Change and Timestamp. While these calls can be made from the Titanium mobile client, there is a large amount of overhead due to the unused data returned by the web service. Also, these calls are made across the often slow and unreliable cellular network as illustrated in the diagram below:

SOLUTION

One solution to this problem is to change the application architecture so that the watch list is retrieved by Appcelerator’s Node.ACS Platform as a Service (PaaS). Then the Titanium mobile client only needs to make one web service call to Node.ACS to retrieve the watch list data. The Node.ACS service makes the repeated calls to the Stock Quote web service to collect the watch list data but it does this across the high speed Internet instead of the slow cellular network as illustrated below:

The custom Node.ACS service is shown below. Note that an additional feature in this Node.ACS service is that the Watch List symbols are retrieved from ACS Custom Object. This enables watch lists to be maintained across mobile devices.

var ACS = require('acs').ACS;
var logger = require('acs').logger;
var EventEmitter = require('events').EventEmitter;
var https = require('http');
var sessionID = null;
var stocks;
ACS.init('', ''); // use your ACS OAuth key and secret

function refreshPrice(req, res) {
    var uid = req.query.uid;
    var Event = new EventEmitter;
    var results = [],
        evt_count = 0;
    // SETUP EVENT LISTENER
    Event.on("HTTP_COMPLETE", function (e) {
        console.log("EVENT: HTTP_COMPLETE");
        evt_count++;
        console.log(evt_count);
        if (evt_count >= stocks.length) {
            console.log("close response, results = " + JSON.stringify(results));
            res.write(JSON.stringify(results));
            res.end();
        }
    });
    ACS.Objects.query({
        page: 1,
        per_page: 100,
        classname: "stocks",
        where: {
            user_id: uid,
        }
    }, function (data) {
        console.log(JSON.stringify(data));
        stocks = data.stocks;
        var l = stocks.length;
        if (l == 0) {
            Event.emit("HTTP_COMPLETE");
        };
        for (var i = 0; i < l; i++) {
            marketOnDemandQuote(stocks[i].symbol);
        }
    })

    function marketOnDemandQuote(symbol) {
        var myreq =
            https.get('http://dev.markitondemand.com/Api/Quote/json?symbol=' + symbol, function (r) {
            r.setEncoding('utf8');
            r.on('data', function (chunk) {
                console.log(chunk);
                var o = {}, d = JSON.parse(chunk);
                o.symbol = d.Data.Symbol;
                o.name = d.Data.Name;
                o.lastPrice = d.Data.LastPrice;
                o.change = d.Data.Change;
                o.changePercent = d.Data.ChangePercent;
                o.timestamp = d.Data.Timestamp;
                results.push(o);
                Event.emit("HTTP_COMPLETE");
            });
        });
    }
};
exports.refreshPrice = refreshPrice;
// Source code attribution: Asim Siddiqui and Bert Grantges

Conclusion

Appcelerator’s Node.ACS Platform as a Service can be used to build mobile optimized middleware services in Node.js. The middleware service reduces the overhead in retrieving the watch list data by making repeated calls to a stock quote web service and presents the aggregated data that the mobile application needs. This results in improved user experience and reduced latency and throughput requirements of the mobile application.

While this example was designed around a stock watch list, the principles can be applied to many other use cases such as sales flash reports, key performance indicator dashboards and other applications where the back end data is not optimized for the mobile application or when data needs to be mashed up from disparate back end data sources.

The Node.ACS online documentation is a good next step for learning about Appcelerator Custom Cloud Service and can be found here: http://docs.appcelerator.com/titanium/latest/#!/guide/Node.ACS


Using ACS as a back-end for your App

On a previous post, I talked about consuming web services. Today I want to talk about ACS (Appcelerator Cloud Services), but before I go into what it is and how it can help you, let’s take a look at a scenario.

Your client asks you to build an App where people can create an account, log in and display a feed with photos that people have uploaded. Any user can then can snap a picture, upload it to the server and after being approved by an administrator let everyone else see it.

The App itself seems pretty straightforward.

  1. User login and photo feed are two API calls: you already know how to do that.
  2. Taking a picture is easy using the Ti.Media.takePicture method. Then another API call to upload.

Now the back-end, that’s another story. You need to:

  1. Find a server to host your back-end app
  2. Create the database, establish relations between tables (unless you’re using NoSQL Databases)
  3. Expose an API that returns JSON
  4. Create an admin interface
  5. Provide security
  6. Get ready to scale in case your App is very successful and you need more space or bandwidth

What if I tell you that with ACS you can do that right now, and maybe build your full App (front-end and back-end) in a day or two? In fact, let’s do it!

Setting up your app

Launch Titanium Studio and go to File > New > Mobile Project. Then select your Project Template. Now on the New Mobile Project screen, make sure you select “Cloud-enable this application”.

Studio has added for you the ti.cloud module, and has created two API Keys: One for production and one for development. What this really means is that you already have a back-end for your app!. Let’s check it out.

Go to my.appcelerator.com and click on My Apps; Login if you have to. You’ll be taken to a screen with a list of all your Apps. Locate the App you’ve just created and click on Manage ACS. You are now on your Adminstrative Console.

Using ACS

ACS has too many features to mention in a single post. If you want to know all there is to know about ACS, I’d suggest you go to http://docs.appcelerator.com/cloud/latest/. For our example we’ll be using two services: Photos and Users. To use ACS on your App, start by getting an instance to the ti.cloud module.

var Cloud = require('ti.cloud');

Your App already knows your API keys, so you’re ready to go. The ACS API follows a very simple pattern:

Cloud.Namespace.method({
     property1: 'here',
     property2: 'here'
},function(e){
     // I'm the callback.  The method will call me and the response object is in e
});

Both the properties for the method and the object that is returned are documented on the API reference. If you’d rather have a more tangible example, there’s a ACS KitchenSink at https://github.com/appcelerator-modules/ti.cloud/tree/master/commonjs/example.

User Login

For simplicity, I will not implement a way of creating a new user from the App. I’ll assume that the user is already created. To create a new user, scroll down on your ACS console, click on “Users” and then on “Create a New User”.

Fill out Email, Username, Password and Password Confirmation, and click “Submit”. Now you have a user on the system and you’re ready to login. As explained on the API documentation, and based on the simple pattern described earlier, you can call the login method sending two properties: Login (can be email or userid) and Password. Upon successful login you’ll receive an object with data for this user.

Success Example:

Error Example:

PRO TIP: On Titanium you can do console.log(JSON.stringify(your_object)) to inspect the contents of the object that was returned. Here I’m taking that response and viewing it on jsoneditoronline.org

This means that your Titanium code may look something like this:

function doLogin(e){
     Cloud.Users.login({
        login: $.uid.value,
        password: $.pwd.value
    }, function (e) {
        if (e.success) {
            var win=Alloy.createController('feed').getView();
            win.open();
        }
        else {
           alert(e.message);
        }
    });
}

The Photo Feed

To implement the Photo Feed, we use the “query” method in the Photos namespace. This method can receive many optional parameters. We’ll only use one for retrieving the results in reverse order, so we do -created_at; the minus sign reverses the order. The method will return an object will all the photos.

Example Success

As you can see, ACS has already created 6 different versions of your photo: square_75, thumb_100, small_240, medium_500, medium_640 and large_1024.

PRO TIP: Paging is supported using the “page”, “per_page”, “limit” and “skip” parameters, so implementing “lazy loading” is just a matter of writing the front-end code.

To display the feed is as simple as looping through the “photos” array. Your code may look something like this:

    Cloud.Photos.query({
        order: "-created_at"
    },function (e) {
        if (e.success) {
            if (e.photos.length == 0) {
                // no photos
                alert('There are no photos');
            }
            else {
                e.photos.forEach(function(item){
                    // work with this photo
                })
            }
        }
        else {
            alert(e);
        }
    })

Uploading Photos

To upload photos we use the “create” method, which receives the photo in binary form in a property named “photo”. You may get the photo from the photo gallery using Ti.Media.openPhotoGallery or from the camera using Ti.Media.takePicture. Once you have the photo, you may call the “create” method something like this:

     Cloud.Photos.create({
          photo : event.media
     }, function(e) {
          if(e.success) {
               // reload the feed?
          } else {
               alert(e.message);
          }
      });

So there you have it. You very own secure and scalable cloud-based back-end! I have built a proof-of-concept located at github.com/ricardoalcocer/tiphotogram. Here’s how it looks.

I’ve thrown in some bonus conditional Alloy code to use Toolbars on iOS and ActionBar on Android.

This is not a finalized app, just a quick example of you can quickly put together an Alloy-based front-end with an ACS back-end. Feel free to use, fix and improve upon it.

Final thoughts

You can use ACS with or without Titanium, so if you’re looking for a back-end for your web-based app, ACS may be what you’re looking for. For this example we used the ACS SDK for Titanium, but you could also use the native iOS or Android SDK as well as the REST API. ACS offers 20 pre-build services, one of which is Custom Objects. This means that you can create your own data-sets, with your own data structure, and automatically get a REST API to interact with them.


Please Review ListView Phase 2 specification

Last month as part of our 3.1.0 release we introduced a new, faster version of TableView called ListView. As a refresher, it has several key features:

  • Data-oriented vs view-oriented architecture
  • A separate module. Does not replace the existing TableView so you can migrate on your schedule
  • Extremely performant

We’re now working on phase 2 of that implementation. Please review the specification and add your comments by EOD 5/15 (Next Wednesday).

Link: https://wiki.appcelerator.org/display/community/Titanium+ListView+Specification


Featured Developer – Lark Cookbook

Our featured developer spotlight this week comes from Jared Stoneberg. Jared and his web development company, Number 10 Web Company, leveraged a Kickstarter campaign to help fund the beautiful Titanium app “Lark – Cooking Against the Grain”. Read more about how Jared and team pulled together this app to showcase the favorite recipes of James Beard Award-winning Chef John Sundstrom.


Lark icon

Tell us a little bit more about your product and app
James Beard Award-winner and Food & Wine Magazine Best New Chef John Sundstrom takes you on a culinary journey through the Pacific Northwest. His Seattle restaurant, Lark, is a beloved institution, and in this app, he shares 144 of his favorite recipes, all lushly illustrated with full color step-by-step photographs and beautiful HD video demos and vignettes (video | iTunes). Organized according to three distinct seasons – Evergreen, Bounty and Mist – the app is an homage to the majesty and bounty of the Northwest. Rich in detailed instruction, inspiring recipes, and stunning images, this app is a must-have for all home cooks.

Lark cookbook

Why did you decide to use a mobile development platform instead of developing with the native SDKs?
We are a web development shop that has seen a growing number of requests from our clients for native app development over the last 2 years. Our decision to use Titanium allowed us to put to work the Javascript expertise we use everyday in web development to build native applications and for us that is very valuable.

Why did you pick Titanium for your development needs? What other platforms did you consider?
We also explored Phonegap/Cordova. Our experience was that when rendered on the device the experience felt nicer with Titanium. We also wanted to be able to have more complex controls, and performance seemed to suffer when we built these in HTML5. We took a short dead end path into using phonegap, but quickly realized it was not going to be suitable for our application requirements.

What Titanium modules did you use in your app? Did you develop any of your own modules?
As we were developing a cooking app, we were most concerned with the quality of the content. Our editorial team was also widely distributed, with the Author and Chef developing the recipes, his staff turning them into things a normal person could cook at home, and a large panel of testers cooking (and eating) the results. We had folks all over the US, and even an editor in London helping out. As a result we need a good toolset for data entry and management. The Drupal tools we use for our normal web development allowed us to build an online data entry site for everyone to use as a collaborative tool.

Then we extended the site using a Drupal query builder called Views so we could expose the data directly to Titanium via a REST interface with endpoints on the recipe data set. On the Titanium side, we chose to use a module called JSONDB (deprecated now in favor of SculeJS) for local data storage since it provided a familiar MongoDB style of interaction. During data entry and content testing we ran regular exports from the site so we could develop against a “real” data set. Once the data was finalized it was a simple matter of importing into the local database, knowing we had already found most of the edge cases during data entry.

Can you walk me through how you developed this application?
Early on in the process we realized that implementing our interface design was going to present some major performance challenges. The book is broken up into “plates” each of which consists of one or more recipes, and each recipe has multiple steps. Each step is made up of a large number of views, with up to 5 variable length text items, and dynamically determined spacing for controls on each step.

While displaying some of this complex data we experienced significant lag that caused a poor user experience. Drawing these steps means calculating text lengths dynamically, and the combined rendering and redraw time after the length could be calculated was unacceptable. Our solution was to create a second “render robot” app from the same code base, that ran through the entire data set, rendered the displays, and stored the heights/lengths of all the steps in a JSONDB table. We then were able to use that table to display the steps in the real app using absolute measurements, which resulted in a massive improvement in performance even on the most visually complex screens! See a short video here of this in action here:

LARK – Cooking Against the Grain iPad App Demo from Lark Cookbook on Vimeo.

A short tour of the iPad cookbook app with a look at the Chocolate Madeleines recipe.


Big thanks to Jared for taking the time to give us some insight into his experience and success with Titanium app development. Interested in having your Titanium app showcased? Send us an email at community@appcelerator.com and share your story with us!


Beginners: Javascript Objects and Arrays

If you’re new to Titanium, first of all Welcome!

If you are just starting out with Javascript, this post will definitely help you understand two very important features of Javascript: Object and Array literals. Knowing their syntax will not only help you understand how Titanium works, but will speed up your understanding of CommonJS and JSON.

Perhaps you don’t know them by name, but the truth is that when you work with Javascript, you’re working with Objects all the time without realizing it. Take a look at the following example:

var carmake='Honda';
console.log(carmake.toUpperCase());

Where did toUpperCase come from? Here you have used an Object. Every time you create a String variable, you’re actually creating a String Object. This object has properties and methods, toUpperCase being just one of them. More details about the String object here. Get used to the word “Object”, because is the foundation of modern programming.


Object Literals

Object Literals are Objects that you create on the fly. The syntax for Object literals is simple:

  • Enclose it in curly brackets
  • separate properties with comma
  • separate keys and values with a colon
var person={
    name: 'jack',
    email: 'jack@ctu.com',
    twitter: '@jackb_ctu'
};

To access the values on this object, you can use “dot notation”, that is, the name of the object, a dot, and the name of the property.

console.log(person.name);
console.log(person.twitter);


Array Literals

Just like objects, arrays can also be created on the fly. The syntax rules for array literals:

  • Enclose it in square brackets
  • separate each element with comma
var arr=[
            'value1',
            'value2',
            'value3'
        ];

To access the values, you use a numerical index:

console.log(arr[0]);


The fun part

The power of Javascript Object and Array literals comes by combining them. A combination of Objects and Arrays make up a complex, multidimensional object.


Array literal with two objects as values

var arr=[
           {key1:'value1'},
           {key2:'value2'}
        ];
console.log(arr[0].key1);


Object literal with a two-item array as property

var obj={
            key:[
                   'value1',
                   'value2'
                ]
        };
console.log(obj.key[1]);


Array literal with one property that is a two-item array

var arr=[
           {
              key:[
                    'value1',
                    'value2'
                  ]
            }
         ];
console.log(arr[0].key[1]);

This syntax is very popular in today’s web services and perhaps you’ve heard of JSON (Javascript Object Notation). JSON is an implementation of this syntax designed to be a way of transporting data across the Internet.


Applying these concepts in Titanium

Titanium itself is a JavaScript SDK (Software Development Kit) that works as an “Object Factory”. This means that it has methods that generate Objects, and most of the times these methods receive Objects as arguments. It sounds more confusing than it is.

var win=Titanium.UI.createWindow({
    backgroundColor: '#fff',
    fullscreen: true
})

The result of this operation is a Titanium Window Object stored in the variable win. However, the createWindow method received an object as argument, and object with the properties backgroundColor and fullscreen. As you can see, knowing how an object is constructed allows you to understand that the createWindow() and the toUpperCase() methods are very similar. The difference is that you are sending an Object Literal to the createWindow method.

A full description of Titanium’s objects can be found at Titanium API Documentation.

I hope this short tutorial can help you understand Titanium’s syntax and how powerful it can be.

Codestrong!

Page 3 of 9212345...102030...Last »