IIf
- immediate IF function

Trading system toolbox


SYNTAX IIf( EXPRESSION, TRUE_PART, FALSE_PART )
RETURNS ARRAY or NUMBER
FUNCTION "Immediate-IF" - a conditional function that returns the value of the second parameter (TRUE_PART) if the conditional expression defined by the first parameter (EXPRESSION) is true; otherwise, the value of third parameter is returned (FALSE_PART). Please note that IIF is a function - so the result of evaluation is returned by that function and should be assigned to some variable. IIf always evaluates both TRUE_PART and FALSE_PART, even though it returns only one of them. Because of this, you should watch for undesirable side effects. The following example shows one common error made with IIF function: IIF( condition, result = 7, result = 9 ); // THIS IS WRONG Correct usage is: result = IIF( condition, 7, 9 ); /* 7 or 9 is *returned* and assigned to a variable depending on condition */

When all arguments are scalars (numbers) then resulting value is also a scalar (number). When any of arguments is an array then function returns an array.

When working on arrays, Iif function evaluates all bars, condition is checked on each bar and returned value for given bar is choosen appropriately on bar by bar basis. The following code shows how array operation of Iif is implemented internally. Take a look also at Understanding AFL chapter of the manual.

function IIF_AFL( condition, inputA, inputB )
{
     result =
Null;

    
for( bar = 0; bar < BarCount; bar++ )
     {
      
if( condition[ bar ] )
           result[ bar ] = inputA[ bar ];
      
else
           result[ bar ] = inputB[ bar ];
     }

    
return result;
}

EXAMPLE // The formula below
// will assign positive Volume values to the result variable on days when
// MACD was below its Signal line, AND negative Volume values on theother
// days.

result =
IIf( MACD() < Signal(), Volume, -Volume );

// The formula below
// will assign colorRed to the dynamic_color variable on days when
// Close < Open and color Green otherwise


dynamic_color =
IIf( Close < Open, colorRed, colorGreen );
Plot( Volume, "Color volume", dynamic_color, styleHistogram | styleThick );
SEE ALSO

Comments:

Tomasz Janeczko
tj --at-- amibroker.com
2003-06-16 03:04:48
IIF can be re-implemented using new if-else flow control statements. The code below shows this and explains what IIF in fact does internally.

function _IIF( ConditionArray, TrueArray, FalseArray )
{
for( i = 0; i < BarCount; i++ )
{
if( ConditionArray[ i ] )
{
result[ i ] = TrueArray[ i ];
}
else
{
result[ i ] = FalseArray[ i ];
}
}
}
Tomasz Janeczko
tj --at-- amibroker.com
2003-07-28 09:24:10
If you want to operate on STRINGS use WriteIF function:

result = WriteIF( condition, "Text 1", "Text 2" );

(note that this function returns single string, depending on 'selected value' of condition).

References:

The IIf function is used in the following formulas in AFL on-line library:

More information:

Updated on-line reference