How to make a variable retain its value on successive bars?


Category:
0
0

Hello, I’ve been writing code in TS EasyLanguage for nearly 25 years, but I’m relatively new to writing thinkScript.  This is probably something pretty easy, but I can’t figure it out due to my limited fluency in thinkScript.

As far as I can tell, the value of a variable in thinkScript is only available for the bar on which the condition(s) are met.  I can’t find a way to make a variable retain a value on successive bars after the bar where the condition were met. In EasyLanguage, when a value is assigned to a variable that value is held in a table similar to an array and the value can be called on the same bar or any bar after the value has been assigned (until the value is changed by the code).

Since you have been writing code in TS for a while now, perhaps I can most concisely demonstrate what I’m trying to do by presenting what I’m attempting to accomplish in thinkScript with equivalent EasyLanguage code.

var: MyCross ;

If close crosses above Average(close, 14) then

    MyCross = close ;  { <this is the variable assignment I need to use in thinkScript}

Thank you for any help you might be able to offer.

Regards,

Tom

RESOLVED
Marked as spam
Posted by (Questions: 1, Answers: 1)
Asked on July 11, 2018 5:15 pm
416 views
0
Private answer

The term for this is recursion. Which is when you assign to a variable a previous value of itself. So when the condition is true we assign the initial value. Then for every other bar that the condition is false we assign the value of the previous bar. This has the affect of holding the value across many bars for later use.

The process is very much the same for both EasyLanguage and Thinkscript. I personally do not use the method you provided in your example. I prefer to make very definitive value assignments which I control. So I will provide an example of how I do this for both languages.

For EasyLanguage:

Variables: myClose(0);
If Close crosses above Average(Close, 14) Then Begin
myCross = Close;
End
Else Begin
myCross = myCross[1];
End;

For Thinkscript:
rec myCross = if close crosses above Average(close, 14) then Close else myCross[1];

That is a single line method of recursion in Thinkscript.

You can also do it this way:
rec myClose;
if (close crosses above Average(close, 14)) {
myClose = close;
} else {
myClose = myClose[1];
}

Occasionally in Thinkscript we need to employ a method named CompoundValue() to initialize a recursive variable. You can read more about that here: http://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Others/CompoundValue.html

Marked as spam
Posted by (Questions: 37, Answers: 4118)
Answered on July 11, 2018 8:20 pm