Overbasic – IF .. THEN .. ELSE

Table of Contents

IF, THEN and ELSE keywords allow you to condition the execution of a set of statements. In other words, statement blocks can only be executed under specific conditions.

Syntax #

If <condition> Then
    <IF..THEN statement block> 'to be executed if <condition> is TRUE
Else
    <ELSE statement block> 'to be executed if <condition> is FALSE
EndIf

IF statement consists of two blocks:

IF..THEN block: (mandatory) statements contained in this block are executed ONLY if <condition> is TRUE

ELSE block: (optional) statements contained in this block are executed ONLY if <condition> is FALSE

<condition> is any equation/inequality (or a set of equations/inequalities linked together by AND/OR operators)

IF..THEN and ELSE statement blocks can contain any type of statement including other IF..THEN..ELSE (nested) statements:

If <condition1> Then
    If <condition2> Then
        ...
        ...
    EndIf
Else
    If <condition3> Then
        ...
    Else
        ...
    EndIf    
EndIf

In the case of multiple nested IF statements, it is sometimes convenient to use an alternative (simplified) syntax that makes use of the ELSEIF keyword:

If <condition1> Then
    ...
ElseIf <condition2> Then
    ...
ElseIf <condition3> Then
    ...
Else
    ...
EndIf

Usage #

IF..THEN without ELSE block:

If (Close > Open) Then
    PositiveBars = PositiveBars + 1
EndIf

If (Close > Open) And (Close > Close(-1)) Then
    PositiveTrend = True
EndIf

IF..THEN with ELSE block:

If (Close > Open) Then
    PositiveBars = PositiveBars + 1
Else
    NegativeBars = NegativeBars + 1
EndIf

IF..THEN..ELSE nested:

If (Close > Open) Then
    PositiveBars = PositiveBars + 1
Else
    If (Close = Open)
        NeutralBars = NeutralBars + 1
    Else
        NegativeBars = NegativeBars + 1
    EndIf
EndIf

IF..THEN..ELSE with ELSEIF block/s:

If (Close > Open) Then
    PositiveBars = PositiveBars + 1
ElseIf (Close = Open)
    NeutralBars = NeutralBars + 1
Else
    NegativeBars = NegativeBars + 1
EndIf