To control what part of your program is executed under certain conditions, you use the If statement. For example, you only want your program to draw a line on the screen if the calculated line for your result is above a certain level; otherwise, you want to do some additional calculations before the line is drawn.
The crucial part of an If statement is usually the condition that decides when one or the other statement is executed. You should put some thought into your condition and test it thoroughly in order to avoid unexpected results. A condition is an ordinary Boolean expression that gives you a value of either True or False.
Tip If statements are sometimes also used to make sure that all values needed for some calculation are actually available and valid before you start the calculation; therefore, the function IsValid is often used as the condition.
An If statement consists of three parts, of which at least the first two must be provided:
▫ If + condition(s): The first part declares the condition(s) that have to be verified. Depending on the outcome of the calculation of the condition, which normally is a Boolean expression, different actions are carried out.
▫ Then + statement(s): This part is only executed when the condition is met, that is to say when the Boolean expression used in the If part is True.
▫ Else + statement(s): This part is only executed when the condition is not met, that is to say when the Boolean expression used in the If part is False.
You can skip the Else part if you do not need it, but you cannot skip the Then part.
If
Condition Then
Statement1;
or
If
Condition Then
Statement1
Else
Statement2;
If |
Starts the If statement |
Condition |
Boolean expression that decides if the Then or Else block is executed |
Then |
Starts the Then execution block: This block is executed only if Condition is True. This part is mandatory. |
Statement1 |
Any command statement or block statement that will be executed when the condition is met. Don't put a semicolon at the end of this statement if you want to add an Else block. |
Else |
Starts the Else execution block: This block is executed only if Condition is False. This part is optional. |
Statement2 |
Any command statement or block statement that will be executed when the condition is not met |
You can concatenate several If-Then-Else statements, which means that you use another If statement in the Else part of the previous If statement:
If
Condition1 Then
Statement1
Else If Condition2 Then
Statement2
...
Else If
ConditionN Then
StatementN
Else
Statement0;
Checks if a value is valid before drawing a line using that value:
If
IsValid(Source) Then
DrawLine("ROC", roc(Source, period));
Concatenated If statements to sum up values similar to the Sum function:
If
CurrentBar = 1 Then
Result = source[0]
Else If CurrentBar < period Then
Result
= Result[1]
+ source[0]
Else
Result
= Result[1]
+ source[0]
– source[period];