if

Syntax (if-expression)

plot <plot_name> = if <condition>
then <expression1>
else <expression2>;

plot <plot_name> = if <condition1>
then <expression1>
else if <condition2>
then <expression2>
else <expression3>;

Syntax (if-statement)

plot <plot_name>;
if <condition1> [then] {
<plot_name> = <expression1>;
} else if <condition2> [then] {
<plot_name> = <expression2>;
} else {
<plot_name> = <expression3>;
}

plot <plot_name>;
if <condition1> [then] {
<plot_name > = <expression1>;
} else {
if <condition2> [then] {
<plot_name> = <expression2>;
} else {
<plot_name> = <expression3>;
}
}

Description

As a reserved word, if is used in if-expressions and if-statements to specify a conditional operator with then and else branches. Both branches are required for the operator to be valid. However, while the if-expression always calculates both then and else branches, the if-statement only calculates the branch defined by whether the condition is true or false. In thinkScript®, there is also If-function having syntax and usage different from those of the reserved word. The if-expression can also be used in other functions such as, for example, AssignValueColor, AssignPriceColor, etc. Note that you can also use a def variable instead of input price = close;
input long_average = yes;

plot SimpleAvg = Average(price, if long_average then 26 else 12);

plot ExpAvg;
if long_average {
ExpAvg = ExpAverage(price, 26);
} else {
ExpAvg = ExpAverage(price, 12);
}

In this example, if-expression and if-statement are used to control the length parameter of moving averages.

Example 2. Recursive usage

def myHigh;

if high > myHigh[1] {
myHigh = high;
} else {
myHigh = myHigh[1];
}

plot H = myHigh;

This example script plots the highest high value by comparing the high price with the variable myHigh. If the high price is greater, the value of myHigh is rewritten, otherwise the variable keeps its previous value as defined by the else branch.