Saturday, December 11, 2010

thinkScript Color Output

thinkScript Problem

I was working on a scan and wanted to give an indication to whether the recent price trend was ascending or descending. There are a couple of built-in functions that represent this, but I was looking for a way to output the results in a custom scan column. At first I wanted to return a string like "Ascending" or "Descending". I need to go back to this, but I had first concluded that the output must be a numerical value.

So how do you make a distinction? Try a different color value depending on whether the security is ascending or descending. Didn't seem too difficult, but what I found is that you can't perform some functions within the if/then/else block. For example:

plot ema = roundUp(MovAvgExponential(close, 5), 3);

if IsAscending(close, 3) {
ema.AssignValueColor(Color.RED);
} else {
ema.AssignValueColor(Color.CYAN);
}

Didn't work for me; the result was the error "can not be called within branching: assignvaluecolor". I had tried a few other ideas, but found the same error related to functions within if/then/else branches.

Documentation Saves The Day

I was on the right track with the AssignValueColor function, but I wasn't using it correctly for what I wanted to do. I didn't realize the function could take a condition as input. Clearly described in the example, I was able to adapt the code to suit my needs.

plot ema = roundUp(MovAvgExponential(close, 5), 3);
ema.DefineColor("Asc", Color.CYAN);
ema.DefineColor("Des", Color.RED);

ema.AssignValueColor(if IsAscending(close, 3) then
ema.color("Asc")
else
ema.color("Des"));

And with that, I was able populate my column, and have a visual distinction to securities within the scan that are ascending or descending in price for the time period. I'll refactor the code to see if I can return a string value, like I had originally thought. thinkScript and the Think or Swim platform is great, but not always intuitive. Hitting the TOS_thinkscript Yahoo! Group and the documentation, is your best option when stomping through little gotchas within the platform.