Posts Tagged jumping into javascript
Jumping into Javascript – Good news and bad news
Posted by Nick Zarczynski in Javascript, Programming on 2011/11/14
I have resumed development of the JamochaTrade project and there has been a lot of progress over the last week or so. The last article left off with a very rudimentary candlestick chart that got its data via cross-domain JSON. I am pleased to announce that a UI has been added, along with the ability to buy and sell stocks, limit and stop orders, 5 different chart types (candlestick, bar, ohlc, hlc and line), a portfolio view, pending orders view, advancing time by week/month is animated as well as a host of other improvements.
Unfortunately the speed at which these features have been added has ended the step-by-step nature of this series. I will continue to provide progress updates and hope to produce a number of articles based on architecture or challenges that arise during development. Though there is not much discussion, you can still follow along with the commit log of the project. Each commit is relatively small and, in most cases, addresses a single concern. There is also some information provided in the issue tracker, which I have been making heavy use of and almost every commit has an associated issue.
The project is not yet ready for release, however there is a preview version available. Criticisms, comments, bug reports and feature requests are more than welcome. You can leave comments below or file a bug report or feature request on the issue tracker.
Try the demo
Features:
- 5 chart types (candlestick, bar, ohlc, hlc, line)
- 15, 30, 60 and 90 day charts
- Change chart colors
- Advance time by day, week or month (animated)
- Buy/sell stocks
- Portfolio view
- Sell directly from portfolio view
- Market, limit and stop orders
- Pending order pane
- Cancel pending orders
- Change theme of site
- Previously viewed stock data is cached for fast switching
- Most features auto-hide when not necessary to reduce clutter
- Account balance and total portfolio value show gains/losses
Jumping Into Javascript – Drawing JSONP Data on the Canvas
Posted by Nick Zarczynski in Javascript, Programming on 2011/04/05
The last article in this series was a bit of a digression into the module pattern and namespaces in Javascript. This article will focus on a very simple charting algorithm.
Now that we have the data to draw and know how to move things on the canvas, we need to focus on making the chart look more like a normal chart. This post will focus on the drawing algorithms that will turn our data into a nice display and redrawing that same chart at different time periods/scales. Here’s the screenshot representing our progress from last time.

The first step is to find out the lowest value that will have to be drawn on the chart. We can align all the rest of the values with the bottom of the chart if we subtract the lowest value from each value on the chart. To do this we first have to traverse the sequence of data that will be shown and look for the lowest value.
var width = 600, height = 500
var chart = document.getElementById("chart");
var c = chart.getContext("2d");
chart.width = width; chart.height = height
//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//
function getUrl(symbol) {
return "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D" + symbol + "%26d%3D2%26e%3D27%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&format=json&callback=?";
}
$.getJSON(getUrl("ibm"), init);
function init(result) {
var data = result.query.results.row;
drawRects(data, 1);
}
//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//
function drawRects(d, s) {
var e = s + 30;
var low = d[s].col3;
for (var i = s; i < e; i++) {
if (d[i].col3 < low) { low = d[i].col3 }
}
for (var i = s; i < e; i++) {
c.fillRect(i*30, height-(d[i].col1-low), 20, d[i].col1 - d[i].col4);
}
}

The next thing to do is scale up the bar heights to match the height of the chart. For this we also have to determine the highest high. Then we take the difference between the highest high and the lowest low and divide the chart height by that number, this gives us our multiple. Then we take the multiple and use it to compute the lower starting position as well as the height of each bar.
Before we were using the open data, however this won’t always give the lowest price. On any day the stock price fell, the open will represent the highest price. We don’t have to compute if the open is lower or higher than the close because our data gives us the low and high prices for the day. This is also beneficial as the low or high from the day could be significantly lower/higher than the open or close.
Also we’ve been drawing our chart backward, to flip it we need to subtract the offset from the width of the chart. In addition we should put in some color to tell what days are up or down. Since code is probably the best description of this formula I’ll stop trying to explain it and just show you the algorithm. I’m sure there is a cleaner/simpler solution (or maybe this solution is even too simple) however this can be updated a bit later down the road.
var width = 600, height = 500
var chart = document.getElementById("chart");
var c = chart.getContext("2d");
chart.width = width; chart.height = height
//chart.onclick = moveRects;
//___________________________________________________________________________//
// Query and Init Procedures
//___________________________________________________________________________//
function getUrl(symbol) {
return "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D'http%3A%2F%2Fichart.finance.yahoo.com%2Ftable.csv%3Fs%3D" + symbol + "%26d%3D2%26e%4D04%26f%3D2011%26g%3Dd%26a%3D0%26b%3D1%26c%3D2000%26ignore%3D.csv'&format=json&callback=?";
}
$.getJSON(getUrl("ibm"), init);
function init(result) {
var data = result.query.results.row;
console.log(data[1].col0);
drawRects(data, 1);
}
//___________________________________________________________________________//
// Chart Drawing Procedures
//___________________________________________________________________________//
function drawRects(d, s) {
var e = s + 15;
var low = d[s].col3;
var high = d[s].col2;
for (var i = s; i < e; i++) {
if (d[i].col3 < low) { low = d[i].col3 }
if (d[i].col2 > high) { high = d[i].col2 }
}
var mul = height / (high - low);
for (var i = e; i > s; i--) {
if (d[i].col1 < d[i].col4) { c.fillStyle = "#00f"; }
else { c.fillStyle = "#f00"; }
c.fillRect(width - (i*30),
height - (mul * (d[i].col1-low)),
20,
(mul * (d[i].col1 - d[i].col4)));
}
}

And here’s the Yahoo Finance chart as comparison…

Finally here’s a snapshot of pyTrade, the father of JamochaTrade. Something similar to this is the ultimate goal of JamochaTrade.

As you can see our chart now looks a lot more like a stock chart! However, we still have a long way to go. Wicks, labeled axes, hover tags and much more need to be added, not to mention different styles of charts (line, mountain, dot, etc.). There are also a few bugs with our current implementation that need to be worked out.
The next article will concentrate on refactoring and debugging. Notably we’ll move our code into a namespace, as was discussed in the previous article. We’ll also rip out the drawing logic and put it into a function so we can make a more general drawing procedure that can handle different types of bar charts (Candlestick, OHLC, HLC).
Jumping Into Javascript – Namespaces, we should have more of these
Posted by Nick Zarczynski in Javascript, Programming on 2011/04/04
The last article dealt with cross-domain data retrieval. This article will be a short discussion about namespaces and the module pattern in Javascript.
Here’s a snippet from the Zen of Python that I think should be included in some theoretical incantation of the Zen of Javascript:
Namespaces are one honking great idea — let’s do more of those!
Namespaces are an important concept in any programming language. Programming without them is inevitably an exercise in tracking down hard-to-find bugs that occur when a definition is clobbered by an unrelated assignment.
Here’s the problem: There is a single global namespace for all the scripts running in a page!
This means that defining: a = 42 in the file display.js will clobber the: a = 7 definition in database.js! Let me restate that. When you are creating global variables in a Javascript file, you must know about ALL the global variables created in ALL the other script files.
This may be possible for small apps that you write by yourself. However for large apps and/or when multiple programmers are working on the same project, this is a nightmare. Luckily there is a solution and it’s called the namespace pattern.
The namespace pattern is very similar to, but not quite the same as, the module pattern. The module pattern is designed to allow private/public attributes of an object, which has benefits and drawbacks that are outside the scope of this article.
Links that describe these patterns can be found at the bottom of this page. It is not within the scope of this series to describe all the aspects of the module pattern. I will, however, give a short overview of the two approaches that I think are worthy of consideration. The first is the module pattern and the second doesn’t have a name that I have found, so I’ll call it the Prototype Pattern.
Module Pattern
var MODULE = (function () {
// all code here
return {
// return everything you want to be public
}
}());
Prototype Pattern
var MODULE = {};
MODULE.variable = 42;
MODULE.fn = function (x) {return x*x};
With the module pattern you must declare everything you want to be public. With the prototype approach you must prefix every attribute creation/access with the namespace. I have read some articles that suggest that prototypes are more efficient than constructor functions. I simply don’t know enough about Javascript at the moment to make that claim. Please research this yourself if it is important to you, don’t take my word for it.
You may come across some “Module Pattern Considered Harmful” type articles when researching. To save you some time here’s the argument: the module pattern is not a solution for every conceivable problem, therefore it should be avoided. Some of these articles do raise valid use cases where the module pattern is not applicable, if you’re interested in that they are a good read. Just don’t drink the kool-aid and believe that they are always useless/harmful.
Most of the issues with the module pattern revolve around private attributes. I have spent most of my time programming in Python and Scheme and, in the general case, I haven’t had a need for private attributes. However the real benefit of the module pattern (IMHO) is not private attributes, but avoiding the global namespace problem. A problem for which the module pattern is an adequate solution.
GOTO Part 6 – Drawing JSONP Data on the Canvas
Links
JavaScript: The Good Parts
A Google Tech Talk given by Doug Crockford. This talk is a great overview of the good and the bad of Javascript for experienced programmers.
Javascript Programming Patterns
A good article that covers a number of methods of tackling the namespace problem.
JavaScript Module Pattern: In-Depth
More information about the module pattern.





