I am a beginning thinkscript programmer and I am learning the syntax of thinkscript pretty fast. However, I am having trouble with the if statements. I understand you can have one statement inside of an if block but is it possible to have multiple statements in an if block?
Not: if (condition) then (this) else (that);
but: if (condition) then { (this); (that);};
thinkScript essentially has three forms of if
usage. All three forms require an else
branch as well. One form allows for setting or plotting one or more values. The other two only allow one value to be set or plotted.
if
statement: can set one or more values, for plot
or def
variables, within the brackets.def val1;
plot val2;
if (cond) {
val1 = <value>;
val2 = <value>;
} else {
# commonly used options:
# sets the variable to be Not a Number
val1 = Double.NaN;
# sets the variable to what it was in the previous bar
# commonly used for recursive counting or retaining a past value across bars
val2 = val2[1];
}
if
expression: all-in-one expression for setting a value. Can only set one value based on a condition, but can be used within other statements. This version is used commonly for recursively counting items across bars and for displaying different colors, say, based on a condition.def val1 = if <condition> then <value if true> else <value if false>;
if
function: similar to the above, but more compact, this is thinkScript(r)'s version of a ternary conditional statement. It's difference is that the true and false values must be double values. Therefore, it can't be used in setting colors, say, or other items that don't represent double values.def var1 = if(<condition>, <value if true>, <value if false>);
The following example, modified from the thinkScript API doc for the if
function, demonstrates using all three versions. I've added a 2nd variable to demonstrate how the if
statement can set multiple values at once based on the same condition:
# using version 3, "if function"
plot Maximum1 = if(close > open, close, open);
# using version 2, "if expression"
plot Maximum2 = if close > open then close else open;
# using version 1, "if statement", with two variables, a `plot` and a `def`
plot Maximum3;
def MinimumThing;
if close > open {
Maximum3 = close;
MimimumThing = open;
} else {
Maximum3 = open;
MinimumThing = close;
}
As a side note, though the example doesn't show it, one can use the def
keyword as well as the plot
keyword for defining variables' values with these statements.