Tradingview – Tracking The High/Low of a Custom Session

Sometimes it can be useful to track price or indicator movements during a specific time range. A classic example of this would be tracking the high or lowof a session (such as the Asian session in Forex) and then using those levels to set up a breakout range. In this article, we will take a look at one way you can accomplish this. We will also take an alternative slant on it by on it tracking the high/low of an EMA (exponential moving average) instead of focusing on OHLCdata exclusively.

Since this article will not contain a strategy, we will jump straight into the code.

The Code

Code Commentary

First things first, we create a couple of inputs to set our custom session range and ema1length. In the example, the default will track a window over lunchtime.

Following this, the next thing we need to do is track when we enter and are within our session. Tradingview wiki actually provides some good examples of how to do this and the example above is taken from the wiki. You can find a link to it here.

We need to know when the session starts so that we can set our initial value. Once the session starts, the highandlowof the ema1for the period is actually the same. As such, we set the values of ema_highand ema_lowto ema1. Following this, we just need to know whether we are still in the session. If so, we save whatever is greater between the highand the last ema_high and whatever is lower between the low and the last ema_low. Finally, if we are not in the session we just keep using the same value as the previous bar. We set all of these values to ema_highandema_lowusing a ternary conditional operator.

Returning to the session code, the function we use to detect a new session might appear to be daunting at first:

However, all we are doing in this function is using time()to detect whether we are in a session and then doing a simple check. If during the last bar we were not in the session, but now we are in a session, then we have a new session!

In fact, that whole function could be re-written to simply use our in_sessionvariable.

This works the same and is much more intuitive. However, the function from the wiki was left in the example code to give us a chance to discuss and explain it.

On The Charts

Once you load up the code, you should see something like this:

tracking the high/low

That is all there is to it. Take a closer look and you will see the high/low adjusting to the movement of the EMA during the lunch break. After this, the lines remain fixed until the next day.

Now it is time to get creative. Try tracking some things you wouldn’t normally think about. In addition to this, you can move away from tracking sessions. The exact same technique could be used to track between entry signals or the last swing high. Anything you can think of!