Thinkscript Tip: Dealing With Added Bars On Charts

My Formatted Pivot Points Thinkscript was designed to dynamically hide faraway pivot levels based on where the price is currently. If you are down under S1, you don’t want to be looking at R3 all day long. The only problem was that whenever the current bar close would tick above or below the local pivot level, the respective hidden lines would appear and disappear on my chart, making the screen flash like something from YTMND. Easy fix, make the hiding depend on “close[1]” instead of “close”! Not so fast…

If you add extra bars to the right hand side of the chart (which I like to do), then “close[1]” IS NOT the prior bar! Neither is “close” the current bar. “Close” actually refers to the furthest right “bar” on the chart. If you added 5 bars, then “close” is the bar 5 periods into the future. Since this value doesn’t exsist yet, it is assigned the value N/A, and the value returned by calls to the “close” function are the last good value for close, which is the current bar closing price. Most of the time, this is fine since all you care about is the current bar anyway. But if you add bars, and then want to reference bars in the recent past, you won’t get the values you think you will. If I added 5 bars to the right, to get the bar one previous to the current one, I’d have to reference “close[6]”. But you can get around this by using this code:

# Define lastclose = last completed bar close:
rec lastclose=if isnan(close[-1]) then lastclose[1] else close;

Then you use “lastclose” in your code instead of “close”, and you will get the right values no matter how many extra bars you have on the right. I updated the Formatted Pivot Points code with this change, so no more seizures. You’re welcome.

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: