How can I keep the ATR of a specific candlestick inside a variable without it changing with each new

Here is my code: def TrueRange = ATR(14)[1]; On each new candlestick, thinkorswim generates a new ATR value and TrueRange fills with the ATR value of the previous candlestick. I'm looking for a way to keep the ATR value of the first candlestick on the chart inside TrueRange without it changing with every new candlestick.

Here is my code:

def TrueRange = ATR(14)[1];

On each new candlestick, thinkorswim generates a new ATR value and TrueRange fills with the ATR value of the previous candlestick.

I'm looking for a way to keep the ATR value of the first candlestick on the chart inside TrueRange without it changing with every new candlestick.

Can anyone help me?

1 Answer

You can use a recursive variable:

def TrueRange; if BarNumber() == 1 { TrueRange = ATR(14)[1]; } else { TrueRange = TrueRange[1]; } 
  • The first line declares the variable.
  • If you're at the first bar, set the variable to the value for that bar.
  • Otherwise, keep the variable at the value it was before.

Edit: you can also do this in one line:

def TrueRange = ( if BarNumber() == 1 then ATR(14)[1] else TrueRange[1] ); 

Edit 2: if you're using multiple offset/length values, thinkScript will override length/offset values on variables and plots to use the highest value present in the script, rather than what is specified. In that case, you would need to use CompoundValue to force the script to use the correct offset.

def TrueRange = CompoundValue(length=1, "visible data"=if BarNumber() == 1 then ATR(14)[1] else TrueRange[1], "historical data"=Double.NaN); 

Reference my CompoundValue discussion at Understanding & Converting ThinkScripts CompoundValue Function

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobW9uY2WDeYOOoaawZZOWu261jKScnqhdqbWmecCtqWanlmKubr%2FPnpqinpmYeqStzZ2jnquknrCsecinqqKclWKubsLAq6Campyaeri106GmrqxdnsFur8c%3D

 Share!