My First Impressions of Grails (Tyro Trader)

, , February 22nd, 2008

I’m embarrassed to say that I’ve become a “Java Guy”. It’s fine to know a language well, but when you become defined by a single language, you’ve given up learning. It’s a polite way of saying that you stopped caring. At different points in my life I’d try new languages, new tools and play around, just to learn. In fact, that was how I got interested in Java in the beginning - I was in school and I heard of this new “Java” thing which was only in version 0.6 or 0.7 but already it seemed pretty cool so I printed off the specs and got ahold of the alpha releases from sun and started hacking. What a hoot!

I’ve only done something like that a handful of times and in each case, real life work ground me down. The last time was when I got interested in AspectJ and Aspect Oriented Programming. It seemed very cool and I talked a lot about it with my co-workers and then made the mistake of pushing to get it adopted on a big project. Next thing I new, every bug and every question that arose in any one of a dozen different teams spread across three countries would arrive at my desk and I quickly grew to loathe the whole process. Now that I’m working independently, I’ve had a chance to look into a number of different toolkits and languages, but I never drifted too far from Java.

On a whim, I started playing with a language called Groovy and Grails which compile down to Java bytecode which was “safe” and smart as it let me use all the libraries I’ve already written, but wow, what an difference! To start, here’s what I had in mind for the application.

I want something which can centralize a lot of the swing trading related tasks that I perform regularly and I thought it would be interesting to place them all into a single webapplication. It would let me import all of the executions from Interactive Brokers into a database, define my trades with stoplosses, handle reporting and generate charts (all things I do now using a fat client I wrote in SWT a couple years back), but it would also display an updating list of the most active stocks on the exchanges, compare the different sectors, list some of my watchlists and gather together the different scans that I run during the week.

Over the years, I’ve written dozens of web apps and I’ve grown to hate them. So bloody tedious. If you want to add a page which does something slightly different like say search for trades within a certain date range, then you’ve got to code the new command, register the new command in three different configuration files so the servlet engine knows how to handle it, add new search methods to your DAO, write new SQL to retrieve the data and splatter it throughout your configuration files, handle errors and on and on. I grew to accept it, but I never liked it which is why I wrote my first application for trading as a fat, desktop application - I’d had it with web apps.

But Groovy on Grails is different. It’s founding principle is “Don’t Repeat Yourself” and it does it excellently. It takes some of the strongest features of Groovy and pushes them hard. The domain objects just declare their fields and their constraints and Grails maintains all of the database tables, the CRUD methods (Create, Retrieve, Update, Delete) and a boggling-array of retrieval methods. It also has the simplest way of adding new web services I’ve seen - you just add a new method (”Closure”, really) to a controller class and Grails will do all the wiring for rendering the page. For instance, my domain object “Executions” comes with list functionality by default, but I really want to list the Executions that haven’t been added to a trade, and I wanted to list the results. It wouldn’t be complicated to do using Struts or other frameworks, but it would be tedious and require changing a lot of files.

In Grails, it takes exactly two changes. I added one line to my gsp (”Groovy Server Page”) to link to the new search page:

    <g:link action="searchUnassigned">Search for Unassigned</g:link>

Then in the controller, I added a new “closure” matching this action:

def searchUnassigned = {
    render(view:'list',
        model:[exs: Execution.findAllByTradeIsNull()])
}

It builds a list of executions which do not have trades associated, and sends them to the list view. I didn’t even have to write any of the SQL, all the necessary information is in the function name and Grails is smart enough to handle it properly. And it works, first try!

I then went on to look at adding new Trades and found a line of code which really highlights why Groovy kicks so much ass over Java. The “saveTrade” method would have to extract all of the params from the request object, convert them to the correct object type, munge the order and pass it to the constructor, something like:

public void saveTrade(Request req, Response resp) {
try {
    Map<string,string> params = req.getHttpParameters();
    String symbol = (String)params.get("symbol");
    Date lastupdate = pstDateFormatter.parse((String)params.get("lastupdate"));
    double stoploss = Double.parseDouble((String)params.get("stoploss"));
    boolean isComplete = Boolean.parseBool((String)params.get("isComplete"));
} catch( Exception e ) {
    resp.redirect("error.jsp");
    return;
}
if( symbol == null || symbol.size()<> 6 ) {
    // invalid size
    resp.redirect("error.jsp");
    return;
}
// [...  more error checking ...]

Trade trade = new Trade(symbol, lastupdate, stoploss, isComplete);
if( !WebDAO.saveTrade(trade) ) {
    resp.redirect("error.jsp");
}

resp.put("trade", trade);
resp.redirect("show.jsp");
}

And that’s the short version without all the error checking (and no flames if the syntax isn’t quite correct - that should illustrate how hard it is to get this working properly). To make matters fun, all this stupid error checking has to be done everywhere that a trade is created. It’s bloody irritating and it’s hard to maintain. And this doesn’t even go into the depth of coding the freaking saveTrade() method, which is a pain in itself.

So how is this done in Groovy?

def save = {
def trade = new Trade(params)

if(!trade.hasErrors() && trade.save()) {
    flash.message = "Trade ${trade.id} created"
    redirect(action:show,id:trade.id)
}
else {
    render(view:'create',model:[trade:trade])
}
}

Because Groovy’s constructors take a map, you can just pass in the params map. Sweet, there’s a couple dozen lines shrunk down into one. And because the trade object already has a save() method built for you, no need to code it up. What’s especially interesting is that this reduced method (closure, actually) has better error handling than the huge Java method. And all of that work trying to check for valid data in the Java code? Simple, Grails lets you declare that in one place - in the Trade class where it belongs. Here’s what it looks like:

static constraints = {
symbol(maxLength:6,blank:false)
stoploss(min:1.00d, max:100000.00d)
}

How sweet is that? You do it in one place in a simple, declarative fashion without all the messy code and if you ever violate one of these constraints, it even generates friendly error messages telling you what went wrong! It’s just brilliant! It’s exactly how you want to write it, simple and clear and because it’s so simple and clear (and not replicated everywhere) it’s much less likely to have bugs.

AJAX and Plugins

AJAX is one of the Big Things in web sites these days. It’s the technology which allows Google Maps and GMail to act like desktop applications. It decomposes the page into tiny elements and uses JavaScript and custom web services to populate each element separately. That way you can read mail and refresh only the current message, and you can get notifications when new messages arrive without redrawing the entire page, and it lets you scroll Google Maps as if you had downloaded the entire atlas yet still lets pages load quickly. There are a lot of nifty tools to let you develop these applications without having to hand-code all of the JavaScript (like Google’s GWT) and Grails is no exception.

Grails isn’t wedded to a single technology either and lets you pick and choose, but this can lead to potential problems. One of the big failings that I’ve found with these large frameworks is how poorly integrated they are with other tools. Sure you can use JSF or portlets but can you make them work with anything else? Grails has dealt with this issue through the use of “plugins”. The Grails home stores a list of plugins that are vetted to work with the framework and you can automatically download them and all of the associated library versions. There are a lot of cool features of plugins (like integration with the Grails version) but I’ll just show you how easy they are to use.

I had always wanted to have a UI which would show a calendar-based view of my trades, much like Dave’s excellent Stocktickr journal tool but I couldn’t find a way to cram it into my SWT, Swing or AWT tools. But in the web world, MIT has a free tool called SIMILE | Timeline which does just what I want using a goop-load of JavaScript and XML. Fortunately, there is a plugin (”richui”) which simplifies most of the process. In your GSP, you add the tag:

<richui:timeline
    style="border: 1px; height: 450px; width: 100%;"
    startDate="${new Date() - 20}"
    datasource="http://localhost:8080/StockMonitor/reporting/timeEvents" />

and then in the ReportingController, create the “timeEvents” method (really a Closure, but that’s a discussion for another time) which returns the XML data to display. Again, Groovy comes to our aid with the Builder tools, letting us build the XML in a language-friendly fashion.

For my tool, I wanted to query all trades between a user-supplied interval and show my winners in green and losers in red, with incomplete trades marked with an icon and their symbol name:

def timeEvents = {
initParams(params)
   def trades = Trade.findAllByLastupdateBetween(
                        params.startDate, params.endDate)

render(contentType: "text/xml") {
    data() {
       trades.each() { trade ->
         if( trade.isComplete) {
            event('start':dateForm.format(trade.start()),
                  'end':dateForm.format(trade.end()),
                  'title': rForm.format(trade.R())+ "R",
                  )
         } else {
            event('start': dateForm.format(trade.start()),
                  'end':dateForm.format(new Date()),
                  'title': "${trade.symbol}",
                  'color': "blue"
                  )
          }
      }
    }

To non-coders it may look like a mess, but it’s pretty simple. It starts by fetching all matching trades, then builds the XML structure. The event() method declares an node with the attributes “start”, “end”, and “title”. And if you want to change from XML to JSON or other protocols, you just change the content type of the render() method and everything else remains the same!

The result is this:

(Perceptive readers may notice one reason why I’m trading very small size and why I’m not totally stoked with my performance in the market right now.)

So that’s one of the things I’ve been doing in my spare time. I also wrote a Groovy-based API for QuoteTracker which I’m cleaning up and bug testing with the hopes of writing a simple ATS that leverages the charting, studies and alert system of QuoteTracker (this was by far the hardest bit of code that I encountered on my last attempt and I’m trying to learn from my mistakes). I hope to expand this over the coming months and see if I can’t resurrect some day trading ideas.

Tyro Trader (Original)

Tags: , ,