Obtain correctly Previous Bar’s data for secondary timeframe (ThinkOrSwim)

OPEN/HIGH/LOW/CLOSE of secondary timeframe

thinkscript value open close

If you use ThinkOrSwim platform, and wanted to code an indicator/strategy, where you have to use secondary timeframe data, then you should code that correctly, because it has some hidden glitches. Well, when you want to get values of prior bar of secondary timeframe (using i.e. close_secondary_data[1] command), then in some cases, you might see that you get previous bar’s value (of Primary Timeframe), instead of previous bar’s value of Secondary Timeframe. I will review a small snippet to show the differences (by Date, 2018).

Correct ThinkScript code:

Let’s say, we are on 1 minute  chart and you want to use aggregationperiod.Day as Secondary TF;

To define variable and get value (i.e. Open) of current Daily Bar, we use:

def daily_close = open(period=aggregationperiod.DAY);
plot a = daily_close[1];                                  //This will be CLOSE of 1 Day ago
plot b = daily_close[2];                                  //This will be CLOSE of 2 Day ago
...... and so on

As you see, in this case, displacement is done well:

correct value
(you see that previous line displacement is done correctly by yellow lines)

However, there is something interesting bug in TOS (or maybe it’s not a bug at all, I do not know, I’ve already reported to TOS, and waiting their answer). When you use the same variable inside IF/ELSE logic where CURRENT TF variable is used (i.e. o/h/l/c/),  then you will get incorrect value:

  def smth = if condition then CLOSE else daily_close[1];        // <---- this wont get previous daily close

incorrect displacement

You see, that it doesnt get the PREVIOUS DAILY_CLOSE price, instead, it get’s previous previous bar’s data from CURRENT TF. If you just replace the word CLOSE with any other static value/number, then it will correctly get PREVIOUS DAILY_CLOSE.

The same happens with FUNCTIONS:

def smth = average(daily_close, 14);            // <---- this wont get average of daily closes, instead, it will give you average of variable during last 14 bars of PRIMARY TIMEFRAME


The only workaround I’ve found till date (until TOS updates version and this bug will be fixed) is to use such DIRECT ACCESS to value:

def smth = if condition then CLOSE else CLOSE(period=aggregationPeriod.Day)[1];

So, as you see, the only solution is to use DISPLACEMENT directly with the function. Otherwise, there is no way to displace using variable.

NOTE: Once again, this topic only concerns when using inside IF/ELSE where there appears any of CURRENT TF’s   o/h/l/c value!

Leave a Reply

Your email address will not be published. Required fields are marked *