185

Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

  • Upload
    others

  • View
    69

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including
Page 2: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Beginner’s Guide To

AmiBroker

AFL Programming

This Book is dedicated to my family members

Copyright © 2019 by Ajan K K

All rights reserved

AmiBroker is a Trademark of Amibroker.Com

The author has no official partnership with Amibroker.com

Contents

Page 3: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 0 Before Learning AFLProgramming0.1

An Introduction

0.2

What is Amibroker?

0.3

Is AmiBroker easy to Learn?

0.4

The Formula Editor

0.5

The Guru Chart Commentary

0.6

What Next?

Page 4: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 1 Introduction to AFL1.1

Language Basics

1.2

Lexical Elements of AFL

1.3

Operator precedence and parentheses

1.4

Variables and Reserved words

Page 5: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 2 Array Programming2.1

Why AFL is called an Array Programming Language 2.2 ArrayProcessing in AFL

2.3

Accessing Array Elements. [ ] The subscript operator 2.4

Population of the built-in Arrays

2.5

Creating Arrays Manually

Page 6: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 3 Functions in AFL3.1

What are Functions?

3.2

User defined functions

3.3

AmiBroker Built-in functions

Chapter 4 Branching and Looping in AFL

4.1

Conditional execution

4.2

Nesting of if statements

4.3

Use of Arrays in if statement

4.4

Looping in AFL

4.5

Switch case statement

Page 7: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 5 Built-in Functions explored5.1

Page 8: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Introduction5.2

The Plot( ) function

5.3

ParamColor( ) function

5.4

ParamStyle( ) function

5.5

Param( ) function

5.6

Ref( ) function

5.7

Indicator Functions

5.8

The Cross( ) function

5.9

HHV Highest High Value

5.10 HHVBars

bars since highest high over a period

Page 9: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5.11 Highest highest value

5.12 HighestBars

bars since highest value

5.13 HighestSince highest value since condition met 5.14HighestSinceBars bars since highest value since condition met 5.15BarsSince

5.16 GapDown

5.17 GapUp

5.18 Inside

5.19 Outside

5.20 BarIndex

5.21 BeginValue

5.22 EndValue

5.23 abs

5.24 ceil

5.25 floor

5.26 int

5.27 frac

5.28 Max and Min

5.29 Round

5.30 Sum

Page 10: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5.31 Cum

5.32 ROC

5.33 ValueWhen

5.34 DayOfWeek

5.35 PlotShapes

Page 11: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 6 Write Your Own Functions6.1

User definable functions

6.2

#include

Chapter 7 How to make a Watchlist?

7.1

What is a Watchlist?

7.2

Watchlist Creation

7.3

How to add symbols to an existing Watchlist?

7.4

Create a Watchlist by importing from a text file 7.5

A practical example

Chapter 8 Create Your Own Exploration 8.1

Explore in AmiBroker

8.2

Customized Report Generation

Page 12: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 9 Back Testing TradingStrategies9.1

Introducing Trading Strategies

9.2

Amibroker Environment for Back testing

9.3

Reserved variables used in Back testing

9.4

A Back testing example

9.5

Backtester settings from within AFL code

Page 13: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 10 Revision ExercisesChapter 0

Before Learning AFL Programming

0.1

An Introduction

Before we start learning AFL Programming, certain clarificationshave to be made with regard to whom this course is intended for, theprerequisites and other requirements, if any.

• The material in this book is intended for the absolute beginner inAFL

Programming. Only the most basic aspects of the AFL programmingwill be dealt with in this book. Experienced AFL programmers maynot get anything useful in this book.

• This Book will not teach anything about Technical Analysis.

• No attempt is made in this book to teach Trading Strategies, otherthan references to it, when coding examples are required to befurnished.

• To learn AFL, you should have AmiBroker installed in yourcomputer.

• This book focuses only on the AFL programming part. The readershould know how to load charts, place technical indicators on thechart etc.

These are well described in the User Manual of AmiBroker.

0.2

Page 14: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

What is AmiBroker?

AmiBroker is a complete and advanced trading solution. It has manytools including Charting, Backtesting, Optimizing etc. You can displayCharts, add indicators, create watchlists, create trading strategiesand back test these trading strategies, create portfolios etc. It is not amere Charting tool. Any one showing interest in AmiBroker, meansthat he is showing interest in learning AFL, or at least should knowhow to use AFL developed by else body in their trading decisions.

0.3

Is AFL easy to learn?

This is a difficult question to answer. The answer is Yes and No. Ifyou are already proficient in any other programming language, thenthere should not be any problem. It will be a matter of learning thesyntax, keywords, functions etc of the new language. Everythingshould follow very easily. Otherwise, it should take time – there is alearning curve. The fact about AFL is that it is not a general purposelanguage like C, Pascal, Python etc but only specific to deal withfinancial quotation values like Close, Open, High, Low, Volume,Open Interest etc. And that AFL is an array programming, will makesome

Page 15: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

confusions to the beginner programmer. Soon the understanding thatan Array is something like the English collective nouns such as a“Library” of books, a “Herd” of cattle, a “Panel” of experts etc. willrelieve many of the doubts. An Array is simply a collection ofnumbers. Anything we do on the Array means, we are intending todo on every member of the Array and not on any single member ofthe Array. By studying carefully and doing lot of exercises, anybeginner can learn AFL and master it.

0.4

The Formula Editor

The program statements are entered into an Editor called theFormula Editor.

Like all Windows programs, Amibroker provides multiple ways oflaunching the Formula Editor. From the Analysis Menu Click theFormula Editor…. This will open the Formula Editor as shown below.

Fig 0.1 Formula Editor

It contains a blank Editor where the formula can be entered. See Fig0.2

Page 16: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

below.

Fig. 0.2 Editor Options

There are three editor options wherein we can check the syntax ofthe formula, apply the indicator to the chart pane and send theformula to Analysis window. After entering the formula to the Editorscreen, click the Verify syntax icon. If the formula is violating thesyntax of the language, errors will be reported. We can proceedfurther only after rectifying the errors.

An indicator formula or any other formula for plotting can be appliedto the charting pane by clicking the Apply to icon. The Analysiswindow is used for Scanning, Exploration and Back testing etc.There is a faster way of launching the Formula Editor. See Fig. 0.3below.

Fig.0.3 Launch Formula Editor

Page 17: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

From the Speed Bar buttons displayed, click on the Wrench like icon,to launch the Formula Editor.

0.5

The Guru Chart Commentary

This is where we learn and test most of our formulas. There are twoways of launching the Chart Commentary. From Analysis Menu clickCommentary…

or click on the Speed button icon shown in Fig. 0.3 above. Eitherway, it opens the Commentary window as shown below.

Fig. 0.4 Chart Commentary window

It has two tabs, Formula and Commentary. The formula can beentered in the Formula window screen, and the results can bedisplayed by clicking the Commentary tab. Write our first programnow. In the Formula editor screen type the following one lineprogram.

printf( “Hello, World.” );

Now click the Commentary tab to see the result as shown below.

Fig. 0.5 Hello World

We have successfully written our first AFL program. The formulacontains only one statement, that is a printf( ) function. We will beusing the printf function quite often from next Chapter onward. Solet’s look at the function carefully.

Page 18: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The printf function is used to print formatted output to the outputwindow.

Syntax:

printf( formatstr,…)

The printf function formats and prints a series of characters andvalues to the output window. If arguments follow the format string,the format string must contain specifications that determine theoutput format for the arguments.

• For numbers use %f or %g formatting.

• To print a single % sign use %% in the format string.

• A \n placed inside the format string will print a new line.

Example of a format string:

“The scores in Math AND History of the student are \n%g\n%g”,78,89

Whatever within the inverted commas is the format string. 78 and 89are two arguments that follow the format string. The number ofarguments should match the number of %g specifications inside theformat string. The two \n are given for printing new lines. Place theabove format string inside a printf statement in the Formula windowof Chart commentary. Click the Commentary tab to see the resultsas shown in Fig. 0.6 below.

Fig. 0.6 Commentary results

Page 19: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

To display a decimal number use the %f format. The total width andnumber of decimals to be printed can be specified by %w.d f format,where w will be the total width used for printing the number and d willbe the number of digits after the decimal point.

printf( “%5.2 f”, 25.6462);

The above printf statement results in the following value.

25.65

Note to accommodate a total width of 5, first a space is printed andthe number is rounded and not truncated.

Exercise 0.1

1. What will be the output of the following printf?

printf( “%g,%3.1f”,8,6.2 );

a) 8 6.2

b) 8,6.2

c) 8 6.20

Solution:

b)8,6.2 Whatever string placed within the quotes will be printed out.The comma ( , ) is necessarily to be printed.

2. Write a printf formula to get the following output.

My Name is :

Jacob

Solution:

Page 20: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf( “My Name is : \nJacob”);

3. Which formula gives the correct output as given below.

Your percentage score is 50.6%

a) printf( “Your percentage score is %4.1f%%”,50.6); b) printf( “Yourpercentage score is %5.1%”,50.6); c) printf(“ Your percentage scoreis %5.1%%”,50.6); Solution:

The correct answer is a). Though the third option c) looks correct, itwill print an extra space between ‘is’ and 50.6.

4. What is wrong with the following printf statement?.

printf( “Heights of the athletes are %4.1f,%4.1f,%4.1f”,6.3,6.1);Solution:

Three format specifications given. But only two arguments areprovided. These have to be matched. This will report an error.

0.6

What Next?

From the next Chapter onward we are beginning to learnprogramming AFL.

While learning programming, try to do as many problems aspossible. This is perhaps the only way to improve the skills inprogramming. Note that this book is not a replacement for theAmiBroker User Manual. The Manual is the ultimate source ofinformation about AmiBroker.

Chapter 1

Introduction to AFL

1.1

Page 21: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Language Basics

To learn a new language we must first study its basic building blocks.

Assume that we want to learn the English language. How do we startour study? We start our learning process by first studying thealphabets of the language. Simple and common words are thengrasped – spelling and meaning. By using the essential buildingblocks of words, we learn to make meaningful sentences. Theprocess continues by learning preposition, adjectives, nouns, verbs,subject, predicate and the grammar of the language.

When learning a computer programming language like the AFL, theidea to start is the same. We start studying the building blocks of thelanguage. From elementary building blocks we make completesentences (in this case statements). The syntax of the language isthen mastered. So what are the essential building blocks of the AFL?Let us explore it.

1.2

Lexical Elements of AFL

Word-like units used and recognized by the AFL interpreter areknown as Tokens. There are different categories of tokens used inAFL. We can consider these tokens as the basic building blocks ofAFL.

There are five classes of tokens in AFL:

Identifiers

Constants

String literals

Operators

Punctuators (also known as separators)

Page 22: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Identifiers

When a child is born, one of the few things we immediately do is tofind out a suitable name for him/her. Why? This is because without aname he or she loses his/her identity. This is exactly the case withwords used in AFL. Those have to be appropriately named. Theseare known as identifiers. Identifiers

are the names given to variables and functions used in AFL. Thereare certain rules to coin an identifier:

Identifiers can be of any length

Identifiers can contain upper case or lower case letters of thealphabet (a-z, A-Z)

It can contain the underscore character (“_”)

It can contain the digits (0-9)

The first character must be a letter

It is important to note that AFL identifiers are not case sensitive.

Though identifiers can be of any length, very long names will bedifficult to remember and type into the editor. Always try to givemeaningful names to identifiers. That is if an identifier is desired tohold the balance amount in the account, then give a name asaccountBalance rather than xyz12 etc.

Exercise 1.1

Which are legal names for identifiers?

1. myName

2. 1accountHolder

3. MonthlyExpense

Page 23: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

4. Account_balance

5. _totalSum

6. BILLTOTAL

7. $125

8. U_24587

9. myMovAverage

Solution:

1. Legal name

2. Illegal. Cannot start with a number. First character must be aletter.

3. Valid name

4. Legally acceptable

5. Illegal. Must start with a character

6. Acceptable name

7. Special characters are not allowed. First character must be aletter.

8. Acceptable name

9. Legal name.

Constants

Tokens representing fixed numeric or character values are known asConstants. A numeric constant is a number. It can optionally consist

Page 24: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

of a decimal point and a decimal fractional part. Negative numericconstant is prefixed by a unary minus (-) sign.

Examples of numeric constants:

125

8.56

-12

-2.02

String Literals

String Literals or string constants are written as a sequence of anynumber of characters surrounded by double quotes.

Examples of string constants:

“This is a String Constant”

“Account Closed”

“Balance Amount is: “

An empty (null) string is written as “”.

Let us see a practical example of using Constants and String Literalsand use of identifiers. Suppose that during the course of a computerprogram, the account in your balance is found to be Rs. 1200. Youwant to assign this constant value to an identifier and wish to benotified. The following program segment serves the purpose.

myBalance = 1200;

notify = “Your balance is: “;

Page 25: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf( notify + NumToStr( myBalance ) ); In the above code fragmentmyBalance and notify are named identifiers.

myBalance is assigned the numeric constant 1200. Thereafter theidentifier myBalance holds the number value 1200. The secondidentifier notify is assigned a String Literal “Your balance is: “. Theprintf () command combines the two identifiers and the followingresult is printed.

Your balance is 1200

The above program is now shown just to explain how constants andidentifiers are used in an AFL. In an actual program myBalance willnot be assigned this way, but will be computed and the result of thatcomputation will be assigned to myBalance.

Punctuator

The following are the punctuators (also known as separator)available in AFL:

Parentheses

The open parenthesis ‘(‘ and the close parenthesis ‘)’ are alwaysused together. They are used for grouping expressions, isolateconditional expressions and to indicate function calls andparameters. Parentheses are also used to override normalprecedence in calculations.

Examples:

Y = x * 5 + 6

Here x is first multiplied by 5 and the result is get added to 6.

But the user had intended 5 to be added to 6 and the result to bemultiplied by x.

Page 26: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

To override the normal precedence parentheses can be used asbelow.

Y = x * (5 + 6)

myFunc()

Here myFunc is a function call. To identify this as a function theparentheses are necessary. Functions are described later in thebook.

Comma ,

Functions in AFL may have arguments in its definition. The purposeof comma (,) in AFL is to separate the argument list in functions.

Examples:

HHV (array, periods)

Here HHV() is the function. The arguments of the function are arrayand periods. The comma is used to separate the arguments. Theuse of function HHV is described later in the book.

CategorySetName( name, category, number )

Here the function CategorySetName() has three argumentsseparated by commas.

Semicolon ;

In AFL every statement is terminated by a semicolon. If you miss asemicolon after writing a statement, the interpreter will throw anerror.

Page 27: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

An expression is a combination of values, variables and operators .A value all by itself is considered an expression and so is a variable.So the following are all legal expressions.

17

X

X + 20

(Assume that X has been assigned a value already.) Any legal AFLexpression followed by a semicolon is interpreted as a statement.This is known as an expression statement.

Example:

myAverage = MA(Close,20);

Equal Sign =

The equal sign (=) separates variable declarations from itsinitialization.

X = 20;

In the above example the value 20 is assigned to the variable X andthe equal sign separates the variable declaration and its initialization.

There are numerous built in functions in AFL. Some of thesefunctions use default values of parameters provided within thefunction. The equal sign is used to furnish default values ofarguments in functions.

Example:

Macd(fast = 12, slow = 26)

Page 28: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The macd() function uses two parameters, fast and slow. If nothing isspecified by the user, the default values will be fast = 12 and slow =26.

The dot .

The dot is a member access operator. We will not be using this inthis book.

Operators

There are six types of operators available in AFL.

Assignment Operators

Comparison Operators

Arithmetic Operators

Logical Operators

Compound Assignment Operators

typeof() Operator

Assignment Operator

= is the assignment operator. Its purpose is to assign a value to theidentifier on the left of the assignment operator =.

result = expression;

Here, ‘result’ is the variable and the value of expression is assignedto the variable.

Examples:

Page 29: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Total = 5 + 3 + 9;

The sum of the right side of = sign is computed and the value 17 isassigned to the variable Total.

Heading = “Values are computed as shown”; The text string on theright of assignment operator is assigned to the variable Heading.

longMA = MA(Close, 50);

An array of values is calculated on the right hand side and the resultis assigned to the variable longMA. The Moving Average FunctionMA() will be discussed later.

In AFL multiple assignments are possible using =.

A = B = C = 52;

Here A,B and C all are assigned the value of 52.

Comparison Operator

Comparison Operators can be of two types - Relational or Equality.The results of comparison operator will be either a true (1) or false(0).

Equality operator can be either Equal To ( == ) or Not Equal To ( != ).

Relation operators can be the following types: Symbol

Meaning

<

Less Than

>

Greater than

Page 30: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

<=

Less than or equal to

>=

Greater than or equal to

CAUTION: Do not confuse with the assignment operator ( = ) withequality check ( == ). This is a common cause of error.

Arithmetic Operator

The following are the arithmetic operators which can be used informulas.

Symbol

Meaning

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus ( or remainder)

Page 31: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

^

Exponentiation

|

Bitwise OR

&

Bitwise AND

The use of arithmetic operators are illustrated below, x = 12;

y = 5;

z = x + y;

m = x*y;

p = x/y;

q = x^y;

Logical Operators

There are three logical operators namely AND, NOT and OR.

Symbol

Meaning

NOT

Logical ‘NOT’. Gives ‘true’ when operated on a ‘false’

value and ‘false’ when operated on a ‘true’ value.

AND

Page 32: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Gives ‘true’ only when both operands are ‘true’

OR

Gives ‘false’ only when both operands are ‘false’

If a formula requires multiple conditions then logical operators can beused.

Suppose we want to make a condition to buy a security when itsclose price is greater than the 50 day moving average and at thesame time the 14 day relative strength is greater than 70, we canframe the condition as: Condition = (Close > MA(Close,50) ) AND (RSI(14) > 70 ); Here AND is used to combine the two requiredconditions and the variable

‘Condition’ on the left side will be ‘true’ only when both the conditionson the right side become ‘true’.

Compound Assignment Operators

Compound operators are specified in the following form: destinvar op= expr;

where destinvar is the variable, expr is the expression and op is oneof the following arithmetic operators: +,-,*,/,%,&,|

The destinvar op = expr behaves as destinvar = destinvar op expr.

Example:

total = total +2;

The value of total is incremented by two. This can be written as: total+= 2;

Typeof() operator

Page 33: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

It is used in the form of typeof(operand). The typeof() operatoroperates on an operand and returns a string indicating the type ofthe operand. The operand can be string, variable, function identifieror object for which the type is to be identified. In the case ofidentifier, it should be supplied alone without arithmetic operators,without extra arguments and without parentheses. To determine thetype of the value returned by a function, first assign the function to avariable and determine the type of the variable.

Possible return values of typeof():

Return value Description

Undefined

Identifier not defined

Number

Operand represents a number (scalar)

array

Operand represents an array

String

Operand represents a string

function

Operand is a built-in function identifier

User function

Operand is a user defined function

Object

Page 34: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Operand is represents COM object

member

Operand represents member function or COM

object property

handle

Operand represents Windows handle

Example:

//Code fragments

X = MACD(); //MACD() is a built-in function which returns an array Y= LastValue(Close);

//LastValue() returns a scalar, in this case the last period Close Pricevalue

/* A user defined function follows. More about user defined functionsin later Parts of the book

*/

Page 35: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

function myFunc()

{

Return 1;

}

With the above code fragments in mind the typeof() operator can betested.

typeof(X) ; This returns ‘array’

typeof(MACD); This returns ‘function’

typeof(Y); This returns ‘number’

typeof(myFunc); This returns ‘user function’

typeof (“My Name”); This returns ‘string’

Page 36: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

typeof(45.23); This returns ‘number’

typeof(Var1); This returns ‘undefined’ . The variable Var1 is notdefined.

Launch the Guru Commentary in AmiBroker. It has two tabsCommentary and Formula. Click the Formula tab and enter the codefragments shown above. When completed it looks like the figurebelow.

Fig. 1.1

Now click the Commentary tab to see the results of the typeof()operators used in the formula window. Fig1.2 below shows theresults.

Fig. 1.2

Note that when the type of MACD() is checked only the name MACDis used without parenthesis. Otherwise it will report an error.

Whitespace

Spaces (blanks), tabs, new line characters and comments arecollectively called whitespace. They can serve to indicate wheretokens start and end.

Page 37: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Whitespaces are ignored by the interpreter.

Comments

Comments are pieces of text to annotate a program. These are forthe use of the programmer or anybody else who happen to read theprogram. The comments are stripped from the source code whileinterpreting and parsing.

Two ways of commenting in AFL are:

1. Using two forward slashes //

This is the C++ style of commenting. Anything written after // will beignored by the interpreter. It can be placed anywhere in a line.

Examples:

//A comment is placed before the start of a program X = 5; //A valueof 5 is assigned to the variable X

2. Another way of commenting is using a pair of /* and closed by */.

Everything written within the pair are treated as comments andignored by the interpreter.

Example:

/*

All the comments can be

placed here……...

*/

1.3

Operator precedence and parentheses

Page 38: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

AFL supports parentheses in formulas. Operation precedence is theorder in which the operators are used in calculations. In calculationshigher precedence order operator is used first, next lower is usednext etc. However parentheses can be used to control thisprecedence. AFL always does the operations in the innermostparentheses first. When parentheses are not provided, theprecedence is as follows (higher precedence listed first).

No

Symbol

Meaning

1

++

Post increment/pre increment

2

--

Post decrement/pre decrement

3

[ ]

Array element (subscript) operator

4

^

Exponentiation

5

Page 39: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

-

Negation – Unary minus

6

*

Multiplication

7

/

Division

8

%

Remainder

9

+

Addition

10

-

Subtraction

11

<

Less than

Page 40: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

12

>

Greater than

13

<=

Less than or equal to

14

>=

Greater than or equal to

15

==

Equal to. The equality check

16

!=

Not equal to

17

&

Bit-wise AND

18

|

Page 41: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Bit-wise OR

19

NOT

Logical NOT

20

AND

Logical AND

21

OR

Logical OR

22

=

Variable assignment operator

23

Compound assignment operators

Exercise 1.2

1. Find out the value of the following expression 5 + 6*8

Solution:

53. Since multiplication has higher precedence than addition, 6*8 isfirst evaluated and then the result is added to 5.

2. 7*9 – 24/6*2 + (6-3). Evaluate this expression Solution:

Page 42: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

58. Here the division / and multiplication * has same precedence.Since /

came first 24/6 was first calculated and the result is multiplied by 2 toget a value of 8. The resulting expression becomes 63 – 8 + 3 givinga value of 58. If the intention was to multiply 6 by 2 and the result isrequired to divide 24 we should have explicitly used parentheses asbelow.

7*9 – 24/(6*2) + (6 – 3)

In this case the value would be 64.

3. Find out the value of 78 + 7*3^2 – 6*2 – 5

Solution:

124. Here ^ has top priority and hence 7 to be multiplied by 3^2which is 9. The expression becomes 78 + 63 -12 -5 resulting a valueof 124.

4. What will be the value of 24/6/2?

Solution:

This evaluate to 2, since for similar operators, the precedence isfrom left to right.

5. Put parentheses in the following expression to give a value of 3.

5 – 4*3 /2 - 1

Solution:

( 5 – 4 ) * 3 / ( 2 – 1 )

6. Check whether the following statements are True or False.

a) ( True OR False ) AND True

Page 43: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

b) ( False AND True ) OR False

c) ( False AND False ) AND ( True OR False ) d) ( True OR ( FalseAND True )) OR ( True OR True )

Solution:

a) True

b) False

c) False

d) True

1.4

Variables and Reserved Variables

A variable is an identifier that is assigned to an expression or aconstant. The number of variables that can be used in AFL isunlimited. Variables must be assigned before it is used in a formula.Or an error will be thrown. Variables cannot be assigned within afunction call. Naming conventions of a variable are alreadydiscussed.

User defined variables cannot be same as built-in function namessuch as ma, ema, iif, macd, rsi etc. or they cannot be same aspredefined array identifiers such as O, H, L, C, Open, High, Low,Close etc. While naming variables avoid these names.

AmiBroker uses some reserved variable names in its formulas suchas Buy and Sell. These reserved variable names should be usedonly for the intended purpose and should never be used to nameuser defined variables. Some common reserved variables and theiruse are given in the table below. For an exclusive list see theAmiBroker User Manual.

Variable

Page 44: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Usage

buy

Defines “buy”(enter long position) trading rule sell

Defines “sell”(close long position) trading rule short

Defines “short”(short sell ) trading rule

cover

Defines “cover”(close short position) trading rule buyprice

Defines buying price array

sellprice

Defines selling price array

coverprice

Defines buy to cover price array

filter

Used in exploration. Controls which symbols/quotes are accepted

Chapter 2

Array Programming

2.1

Why AFL is called an array programming Language?

One of the most important aspects of AFL is that it is an arrayprogramming language. It operates on arrays of values.

What is an Array?

Page 45: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

An array (or Vector) is simply a list of numbers. Suppose an array Ahas the following values in the list 2,6,8,5. Then a mathematicaloperation like A*2

will change all the values in the original array to be multiplied by 2and the result will be a new array with values 4,12,16,10. Similarly ifB is an array with values 4,5,3,2 then the operation A + B yield anew array with values of the corresponding array values addedtogether and the result is an array with values 6,11,11,7.

In AFL there are some predefined built-in price array identifiers. Theyidentify specific price fields that the formula can operate on. Thevalid price array identifiers are open, high, low, close, volume,openint, avg. These identifiers can be abbreviated as shown in thetable below. For example for identifying the open price we can eitheruse open or O. Also note that the identifiers are not case sensitive.That is high and HIGH both refer to the same array.

Long Name

Abbreviation

Open

O

High

H

Low

L

Close

C

Page 46: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

VolumeV

OpenInt

OI

Avg

<no abbreviation>

Avg, sometimes called the typical price is calculated as(High+Low+Close)/3.

OpenInt is the total number of outstanding shares and is used inFutures trading.

An AFL array can be thought of as a list of numbers with onenumber in the list for each bar in the currently selected chart. Whatthese numbers depends on the type of Array. For example for theOpen array, each number represents the opening price of thecorresponding bar in the chart. MA(Close,50) array represents thecalculated value of moving average for 50 periods for eachcorresponding bar. In this case the first 49 bars will not be havingmoving average values due to insufficient data, and these will befilled with ‘Null’.

Example of use of price identifiers in AFL formulas: MA( Close, 10 );

MA is a built-in function to calculate the moving average. Close is theclose price array. The parameter 10 is the look back period. Theabove statement calculates the 10 period moving average of theClose price Array and the result will be another array. We can assignthis to a variable like ma10.

Page 47: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

ma10 = MA( Close, 10 );

Now the variable ma10 will be an array, and it will have Barcountnumber of elements, just as the case of Close. However, the first 10elements of ma10

will not have values, and will be filled with “NULL”. When we plotma10 on the chart, the plot starts only from the 11th element onward.

2.2

Array Processing in AFL

The array processing in AFL is very fast. Unlike in other conventionalprogramming languages there is no separate code required forprocessing the array elements. The processing in AFL is just one go,like the processing in the case of scalars. Consider the followingstatement: midValue = (High+Low)/2;

When AFL is evaluating statements like the above one, it does notneed to re-interpret the code for each bar. Instead it takes the Higharray and Low array and adds corresponding array elements insingle stage. Then the resulting

array elements are divided by 2 in single stage. The resulting array isstored in the variable midValue.

Visualizing Array elements as a row of cells Let us visualize theClose array as a row of cells. Let there be 7 elements in the array.The row index starts from 0 and the last index will be 6 and not 7.

Here is how the Close array looks like:

Index

0

1

Page 48: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

2

3

4

5

6

Close

10.5

10.6

10.6

10.4

10.3

10.5

10.6

Each index corresponds to a trading bar. It can be daily, 5 minute, 1hour, weekly etc.

Operations whether they are mathematical or relational areperformed on each index.

Suppose we add two arrays and assign it to a variable: A = Open +Close;

Index

0

Page 49: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

1

2

3

4

5

6

Close

10.5

10.6

10.6

10.4

10.3

10.5

10.6

Open

10.4

10.5

10.3

10.2

10.5

Page 50: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

10.6

10.4

A

20.9

21.1

20.9

20.6

20.8

21.1

21

For each index the value of open and close will be added and a newarray created will be assigned to the variable A.

Another example:

upDay = Close > Open;

Index

0

1

2

3

4

5

Page 51: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

6

Close

10.5

10.6

10.6

10.4

10.3

10.5

10.6

Open

10.4

10.5

10.3

10.2

10.5

10.6

10.4

upDay

True

True

Page 52: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

True

True

False

False

True

Depending upon the values of close and open the upDay array isproperly flagged as True(1) or False(0).

Page 53: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

2.3

Accessing Array elements. [ ] - The subscript operator Eachindividual array element can be accessed by the subscript operator [], a pair of square brackets. The format is:

arrayidentifier[ expression ];

The expression must be evaluated to a number. It represents thevalue of the expression-th element of the array.

In the table given above, Close[0] will be 10.5, Open[2] will be 10.3,upDay[6]

will be ‘True’.

BarCount is a constant in AFL which gives the number of bars in thepredefined arrays like Open, High, Low, Close, Volume etc. Thearray elements are numbered from 0 (zero) to BarCount – 1. Henceto get the last bar of an array we have to use array[BarCount – 1].The name BarCount should not be used as user defined variables.

2.4

Population of the built-in price arrays

The price arrays O, H, L, C etc. are populated from the data of theselected (displayed) chart. As we change the symbols of stocks andhence the displayed chart, the array values get changed. How manyelements will be in the above arrays? There will be BarCountnumber of elements in the arrays. Open the Guru commentary andtype the following code to print the barcount value of the displayedchart.

Fig 2.1 Fig 2.2

Fig 2.1 shows the code for displaying the barcount value. Thecommentary window in Fig 2.2 shows the value of the result

Page 54: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

displayed. Try changing the selected chart and see how the result ofbarcount varies.

2.5

Creating Arrays manually

Arrays can be created manually by the following method. Let thearray to be created be named A. We then assign elements of thearray using the subscript operator.

A[0] = 2;

A[1] = 3;

A[2] = 5;

A[3] = 7;

A[4] = 6;

The above assignments creates an array A having its first fiveelements assigned as above. Does it mean that the array A haveonly 5 elements? No, it will have barcount number of elements andbarcount will depend on the number of bars in the selected chartwhich is currently displayed. The Typeof(A) will be ‘array’. Now if wemultiply A by 2, each element of A will be multiplied by 2.

B = A*2;

Typeof(B) will be ‘array’.

B[0] will be 4, B[1] will be 6, B[2] will be 10, B[3] will be 14, and B[4]will be 12.

Let C = A + B;

A new array C is created with each element becoming the sum ofcorresponding elements of A and B. C[0] will be 6, C[1] will be 9 etc.

Page 55: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Launch the Guru commentary to verify the above examples.

Fig. 2.3

Fig 2.4

Fig 2.3 and Fig 2.4 shows the formula and commentary windows forthe example above.

Exercise 2:

Page 56: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

1. With the value of Array C as computed above what will be thereturn of typeof(C)?

a. Array

b. Number

c. Undefined

2. What will be the typeof(C[1])?

a. Undefined

b. Number

c. An error is reported

3. Let O[0],O[1],O[2],O[3] respectively be 455,456,455.6 and 457and C[0], C[1], C[2], C[3] respectively be 455.7,455.5.456 and 457.3.What will be the values of the first 4 elements of the array C > O?

4. On a particular day the Close price is 45.6, Open price is 44.8,Low price is 44.2 and High price is 45.1. Which of the following givea True value?

a) C > O

b) O < L

c) H > C

5. Calculate range of the current trading day.

Solution:

1. Answer a. C will be an array.

2. Answer c. Here an error will be reported. You cannot passsubscripts,

Page 57: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

parentheses etc. to the typeof operator. The correct method ofgetting t he type of C[1] is to assign this to a variable first, anddetermine

the type of this variable.

U = C[1];

Typeof(U);

This will return ‘number’. Every individual element of array C is anumber.

3. C > O is a logical operation. It is asking whether Close is greaterthan Open. The result will be either a True or False. A true isrepresented by 1 and a false is represented by 0. So the array C>Owill have its first 4

elements will have values 1, 0, 1, and 1.

4. a and c will give True, while b will be False 5. The range is definedas the difference between the high price and the low price. Theanswer is H – L.

Chapter 3

Functions in AFL

3.1

What are Functions?

In programming, a function is a named sequence of statements thatperform a desired task. When we define a function we specify thename of the function and the sequence of statements. Later we cancall the function by its ‘name’

any number of times.

Page 58: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Functions in AmiBroker can be user definable or built-in. We havealready seen many built-in functions in the previous chapters.

3.2

User defined functions

User definable functions allow to encapsulate user code into easy touse modules that can be used in many places without need to copythe same code over and over again. All functions must have adefinition. The function definition includes the function body, the codethat executes when the function is called. The syntax for functiondefinition is given below:

function function_name ( [parameter,…] )

{

Statements;

[ return result;]

}

A function definition starts with the keyword function followed by thefunction name. The opening and closing parentheses are necessary.Included within the parentheses optional parameter list can be given.The body of the function is defined within the curly braces. A functionshould return a result to the calling program. The return is akeyword. Where the return is not used, it is not called a function buta procedure. The square brackets indicates optional parameters.The square brackets themselves are not part of the functiondefinition.

Examples:

1. Write a function to find the sum of two numbers Solution:

function findSum ( num1, num2 )

Page 59: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

{

total = num1 + num2;

return total;

}

Here findSum is the name of the function. Two parameters are num1

and num2. Within the body of the function these are added andreturned. We can call the function such as:

Y = findSum( 5, 8 ); // Gives a value of 13 and assigned to Y

2. Write a function to check if a candle is green/white.

Solution:

function isGreenCandle ( )

{

result = iif( C > O, True, False );

return result;

}

Scope of variables in functions

Unlike some other common programming languages, AFL does notrequire variables and its type to be declared ahead of its use. Avariable is treated as local or global depending upon where it is firstused. If a given variable first appears outside a function, it is treatedas a global variable. If a variable first appears inside a function thenit is treated as a local variable and confined within the function. If youtry to access the variable outside the function an error is reported.

Page 60: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

function test(a,b)

{

x = 20;

return (a+b);

}

printf(“%g”,x);

In the above program variable x is initialized inside the function andhence is a local variable. Trying to print x outside the function throwsan error as shown below.

Error in AFL formula:

x = 20;

return (a+b);

}

printf("%g",x)

-------------^

File: '___COMMENTARY___', Ln: 6, Col: 14

Error 29.

Variable 'x' used without having been initialized.

The default behavior of local and global variables can be overriddenby global and local keywords.

3.3

Page 61: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

AmiBroker Built-in Functions

AmiBroker houses a large collection of built-in functions. They canbe classified into various categories:

• Basic Price Pattern detection

• Composites

• Date/Time

• Indicators

• Information / Categories

• Lowest/Highest

• Math functions

• Miscellaneous functions

• Moving averages, summation

• Statistical functions

• String manipulation

• Trading system toolbox

• Exploration / Indicators

• File input/output functions

• Low level graphics

• Referencing other symbol data

• Time Frame functions

Page 62: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Without understanding the AFL built-in functions, no useful formulacan be written. The reader is advised to refer to the User Guide toget familiar with the functions, its syntax, usage and examples.Practicing with the examples given will give confidence to write yourown codes and apply into scans, back testing etc. In Chapter 5, wewill discuss some of the commonly used functions and see manyexamples of using them in practical situations.

Chapter 4

Branching and Looping in AFL

4.1

Conditional execution

The code fragments we saw till now, starts execution at the top ofthe program, goes in a progressive manner sequentially until the endof the program. Real life problems cannot always be made toprogram this way.

Depending on situations that may come on the way, some sequentialbreaks will have to be made. Sometimes certain parts of the programwill have to be executed a certain number of times. The conditionalexecution of a program need the ability to check conditions andchange the behavior of the program accordingly. Conditionalstatements give us this ability.

The if else statement in AFL is used for conditional execution. The ifand else are keywords in AFL and should not be used for variablenames.

The syntax of if else statement is:

if (expression)

statement1

[else

Page 63: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

statement2]

The expression is evaluated first. If the expression is true( nonzero ),the if executes statement1. When else is present, and theexpression evaluates to false, the statement2 is executed. Afterexecuting statement1 or statement2, the control transfers to the nextstatement.

The else statement2 is indicated in square brackets to show that it isoptional.

The if logic can be shown as a flow chart.

Fig. 4.1 If Logic

The if statement executes statement1 only if the expressionevaluates to true.

Page 64: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Otherwise it skips the statement1 group. The flow chart for if else isgiven below in Fig. 4.2.

Fig. 4.2 If else logic

Either statement1 or statement2 is executed depending upon thevalue of expression. The statement1 and statement2 can be singlestatements or compound statements within curly braces { }.

Examples:

1. //Example for simple if statement

X = 4;

If ( x < 10 )

printif( “x is lesser then 10.”);

2. i = 0;

x = 50;

if ( i != 0 )

printf( “Division is permitted”);

else

printf(“Division by zero not allowed”);

3. Write a code to check a variable is even or odd. (Hint: A number iseven if it leaves a remainder of zero when divided by 2.) if ( p%2 ==0 )

printf(“p is even”);

else

Page 65: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf(“p is odd”);

4.2

Nesting of if statements

if statements can be nested in the following way.

if (expression1)

statements1

if (expression2)

Statements2

else

Statements3

Using braces will give nesting apparent.

if (i>0)

{

if (j > i )

x = j;

}

else

x = i;

4.3

Use of Arrays in if statement.

Page 66: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

You cannot use Arrays directly in if statements. The following codewill not work but throws an error.

if ( Close > Open)

printf(“Green Candle”);

But the following code works and checks whether the last candleclose was greater than the open.

If ( Close [barcount -1] > Open [barcount – 1] ) printf( “ Closed aboveopen”);

Exercise 4.1

1. Write a program to compute the maximum between two numbers.

Solution:

//num1 and num2 be the two numbers to be compared if ( num1 >num2 )

printf( “num1 is maximum);

else

{

if ( num2 > num1 )

printf(“num2 is maximum”);

else

printf(“Both are equal”);

}

2. Write a program to find whether a given year is leap year or not.

Page 67: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Solution:

A year will be leap year if it is divisible by 4, not divisible by 100 anddivisible by 400. Otherwise it is not a leap year.

//Leap year check. Let year_check be the variable holding the yearto be

//checked

if ( year_check%400 == 0 )

printf( “Is a leap year”);

else

if ( year_check%100 == 0)

printf( “Is not a leap year”);

else

if ( year_check%4 == 0)

printf( “Is leap year”);

else

printf(“Not a leap lear”);

4.4

Looping in AFL

There are three ways you can make loops in AmiBroker.

• do

• while

Page 68: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

• for

The above statements can be used for doing repetitive tasks.

while statement

The while statement lets you repeat a statement until a specifiedexpression becomes false.

Syntax

while ( expression ) statement.

The expression must be arithmetic (numeric/Boolean type). Theexecution proceeds as follows:

1. The expression is evaluated.

2. If the expression is evaluated to true, control transfers to thestatement (it can be compound statement included in curly braces.).Control then transfers to expression for further evaluation. Thestatement is again executed if expression becomes true. Theprocess is continued until the expression evaluates to false, whencontrol transfers to the next statement in the program.

3. If the expression is initially false, the statement gets neverexecuted.

Page 69: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

4. If the expression is a nonzero constant, the statement getsexecuted indefinitely, an undesired trap.

5. There must be a mechanism in the statement portion to make theexpression false within a finite time.

The logic of while statement can be flow-charted as below.

Fig. 4.3 The while logic

Examples:

1. Write a program to print numbers 1 to 5 sequentially.

Solution:

number = 1;

while ( number <= 5 )

{

printf(“%g\n”,number); //%g is the format specifier for printing a

// number ( %d will not work).

number++; //This equivalent to number = number +1

}

Result:

1

2

3

4

Page 70: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5

2. Write a program to print only the even numbers between 1 and 50.

Solution:

i = 1;

while ( i <= 50 )

{

if ( i%2 == 0 ) //Here we check for even number printf( “%g “,i); //Printonly the even number i++;

}

Result:

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 4648

50

do-while statement

The do-while statement lets you repeat a statement or compoundstatement until a specified expression becomes false.

Syntax:

do statement while (expression) The expression is evaluated afterthe body of the statement. Therefor the statement is alwaysexecuted at least once.

The logic proceeds as follows:

1. The statement body is executed first. This is irrespective of thevalue of expression.

Page 71: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

2. Next the expression is evaluated. If expression is false, the do-while statement terminates and control passes to the next statementin the program. If expression is true, the process is repeated withstep 1.

The flow chart of do-while logic can be shown as: Fig. 4.4 The do-while logic

Examples:

1. x = 10;

do

{

printf(“%g “,x);

x = x -2;

}

while ( x > 0 );

Result: 10 8 6 4 2

Page 72: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Printf statement prints the initial value of x which is 10. The x value isthen decremented by 2. Expression is then tested and since itbecomes true the statements are executed to print value 8, and theprocess repeated up to 2. Thereafter the do-while statementterminates.

2. Write a program to find the sum of first 100 natural numbers. Thatis, we are required to find 1+2+3+4+………………+99+100.

We will start with two variables i and total. Initialize i to be 1 and totalto 0.

//Sum to the first 100 natural numbers. Demo of do-while loop i = 1;

total = 0;

do

{

total = total +i;

Page 73: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

i++;

}

while ( i <= 100 );

The counter i will be incremented and added to total until i equals100.

You should get a result of 5050. The Guru Chart commentary for thisis shown in Fig. 4.5 and Fig. 4.6.

Fig. 4.5 Formula

Fig. 4.6 Result

Page 74: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

for statement

The for statement lets you repeat a statement/compound statementa specified number of times. The body of a for statement is executedzero or more times until an optional condition becomes false.

Syntax:

for ( init-expression ; cond-expression ; loop-expression ) statementThe execution process is as below.

1. The init-expression is evaluated. This specifies the initialization forthe loop. There is no restriction on the type of init-expression.

2. The cond-expression is evaluated. If it is true the statement isexecuted.

Then loop-expression is evaluated.

3. The iteration continues until cond-expression becomes false.

A flow chart description of for statement is given below.

Fig. 4.7 The for statement logic

Page 75: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Examples:

1. A simple example of for loop is given below.

for ( i = 0; i < 6; i++ )

{

printf( “%g “,i );

}

Result: 0 1 2 3 4 5

2. Build a 5 period simple moving average of Close price using forloop.

There is a built-in function in AFL to find the simple moving average.

MA(Close,5) gives the 5 period simple moving average directly. Thisexample is for practicing the for loop. We can make an array bysimply assigning values to its subscripted elements. For example:MyAverage[0] =4;

MyAverage[1] =5;

MyAverage[2] = 6;

MyAverage[3] = 2;

MyAverage[4] = 9;

The above statements creates an array MyAverage having its firstfive elements assigned the above values. Typeof(MyAverage) will be‘array’.

The 5 period moving average of Close is the average of the sum ofthe prior 5 Closes. Since 5 values are required to calculate 5 period

Page 76: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

moving average, the first 4 elements of close will not be having theaverage due to insufficient data.

The first 4 values of moving average array will be Null. If we have acounter variable i, MyAverage can be generalized as: MyAverage[i] =( Close[i] + Close[i-1] + Close[i-2] + Close[i-3] + Close[i-4] )/5.

Note that the array indexes start from zero. We can let i start from 4and iterate the calculation until (Barcount -1) which will be the lastelement of the Close array. This will make the MyAverage Array.

//MyAverage – 5 period simple moving average of Close Period = 5;

for ( i = Period-1; i < barcount; i++)

{

MyAverage[i] = ( Close[ i ] + Close[ i-1 ] + Close[ i-2 ] + Close[ i-3 ] +

Close[ i-4 ] )/Period;

}

4.5

switch case statement

A switch case statement allows a variable to be tested for equalityagainst a list of values. Each value is called a case and the variablebeing switched on is checked for each switch case.

Syntax:

switch (expression)

{

case constant-expression1:

Page 77: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Statements;

case constant-expression2:

statements;

……

……

case constant-expressionN:

statements;

default:

statements;

}

Control passes to the statements whose case constant-expressionmatches the value of the switch expression. Execution of thestatement body begins at the selected statement and proceeds untilthe end of the body or until a break statement transfer control out ofthe body. The default statement is executed if no matching ofexpressions occurs. The default statement is optional. There can beonly one default statement and must come at the end.

Flow chart for a switch case can be shown as below:

Page 78: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 4.8 Switch case logic

4.6

Conditional Function IIF()

This is called the immediate if function. The iif() function is used tocreate conditional assignments.

Syntax:

IIF( expression, true-part, false-part) The function returns an array. Ifthe expression evaluates to true, the function returns the true-part,otherwise the false-part. The returned value should be assigned to avariable for further use. The iif() function is very important andcommonly used.

Examples:

1. colorMACD = iif( MACD() > 0, colorGreen, colorRed ); The valuefor the variable colorMACD is assigned depending on the conditionspecified in the first parameter. If its value is True, the secondparameter is assigned to the variable otherwise the third

Page 79: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

parameter is assigned to the variable. If MACD() is above zero,colorMACD is assigned colorGreen otherwise it is assignedcolorRed.

2. //Grading exam results

Grade = “B”;

switch (Grade)

{

case “A”:

printf(“Excellent”);

break;

case “B”:

case “C”:

printf(“Well Done”);

break;

case “D”:

printf(“Passed”);

break;

case “E”:

printf(“Try next time”);

break;

default:

Page 80: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf(“Invalid Grade”);

}

Result: Well Done. Here “Well Done” will be printed for either GradeB

or Grade C.

Exercise 4.2

1. Write a program using while loop for finding the HCF and LCM oftwo numbers.

Solution:

//HCF and LCM of two numbers

//Assign the numbers to two variables

a = 25;

b = 40;

//Preserve the variables

m = a;

n = b;

while (n != 0)

{

t = n;

n = m%n;

m = t;

Page 81: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

}

hcf = m; //Highest common factor

lcm = (a*b)/hcf; //Lowest common multiple

printf(“Highest common factor is %g and Lowest common multiple is

%g”,hcf,lcm);

Result: Highest common factor is 5 and Lowest common multiple is200

2. It is given that ma60 = MA( C, 60 ).

a) Is ma60 an Array or scalar?

b) If ma60 an Array, how many elements of ma60 will be NULL?

c) Write a code to determine the number of NULLs in ma60.( HINT:The IsNull() function checks for NULL values.)

Solution:

a) ma60 will be an Array.

b) A 60 period moving average calculation requires minimum 60 lookback period for its calculation. In AmiBroker the first 60 elements ofma60 will be assigned NULLs. ( Note: Though for the 60th element,ma60 is possible to be calculated, AmiBroker starts calculation fromthe 61st element on words. Some other systems calculate from the60th onward, leaving only 59 NULLs ).

c) //Find the number of NULLs

ma60 = MA( Close, 60 );

I = 0;

Page 82: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

while ( IsNull( ma60[ I ] ) )

{

I++; //Increment I as long as there are NULL values

}

//When loop exits, “I” will hold the number of NULLs.

WriteVal( I, 5.0 );

3. Write a program to print the Fibonacci Series up to 500.

Solution:

In a Fibonacci Series, the current number is the summation of theprevious two numbers. The first two numbers are defined to be 0 and1.

Thus the series is 0,1,2,3,5,8,…………..

The first two numbers are known. We can print that anyway. Thelooping starts from the third number onward.

firstNum = 0;

secondNum = 1;

printf( “%g, %g, “, firstNum, secondNum); //0 and 1 are printed.

X = 500;

nextTerm = firstNum + secondNum;

while ( nextTerm <= X )

{

Page 83: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf( “%g, “, nextTerm );

firstNum = secondNum;

secondNum = nextTerm;

nextTerm = firstNum + secondNum;

}

Result: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,

Chapter 5

Built-in Functions Explored

5.1

Page 84: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

IntroductionAFL has a large collection of built-in functions. A thoroughunderstanding of the functions are required for writing useful AFLprograms to display charts, scanning of securities, portfolio backtesting, developing trading systems, writing own indicators etc. Thesyntax and usage of all the functions are described in the AmiBrokerUser’s Guide. This book is not a replacement for the User’s Guide. Itis not possible to describe every function of AFL here.

However, some of the most important and often used functions aredetailed here for the guidance of the reader so that he can startusing the AFL

programming journey and build skills.

5.2

The plot() function

In AmiBroker we will be dealing mostly with charts and indicators ofvarious types. These are all plotted with the plot() function. So let usstart our study with the plot() function.

The plot() function plots a graph with the data points given in anarray, provided to the function as a parameter.

The syntax of plot() in its simplest form is given below: Plot( array,name, color, style );

The function returns a number. The function plots a graph using thearray data.

Parameters:

• array - This contains the data to be plotted

Page 85: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

• name - This defines the graph name to be displayed in the title bar

• color - This defines the color of the plot

• style - Style determines the style of the plot, such as line chart,histogram chart, thick line etc.

Style can be a combination of one or more of the following.

styleLine

normal line chart ( This is the default value )

styleHistogram

histogram chart

• styleThick

fat(thick) line – in combination with other styles

• styleDots

Page 86: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

dotted line

• styleDashed

dashed line style

• styleCandle

candlestick chart

styleBar

traditional bar chart

This is not a complete list. For complete style constants see theUser’s Guide.

Examples:

1. Plot the Average Directional Index in red color Solution:

The function ADX() returns an array of Average Directional Indexvalues for default 14 period.

Plot(ADX(),”ADX”,colorRed,styleLine);

Launch AmiBroker. Click on ‘Analysis’. From the drop down menuclick

‘Formula Editor’. This loads the Formula Editor.

Type in the above code. Now the Editor should look like the figurebelow.

Fig. 5.1 AFL Editor

Page 87: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Click on the Verify Syntax tick button. If no errors are reported, clickon the Apply Indicator button to draw the plot as shown below.

Fig. 5.2 Plot of ADX

2. Plot the MACD value as a histogram with points above zero ingreen and those below zero in red.

Solution:

We have the MACD() function to determine the MACD array.Additional task is given to determine color according to the MACDvalue. This can be done using the IIF() function.

ColorMacd = IIf(MACD() > 0, colorGreen, colorRed);Plot(MACD(),”MACD”, ColorMacd,styleHistogram); Apply theindicator to plot the function as shown below.

Fig 5.3 Plot of MACD as histogram

Page 88: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5.3

ParamColor() function

This function allows the user to change the color of the plotdynamically while displaying the chart. Rather than explicitly definingthe color in plot function, we can use the ParamColor() function. Thesyntax of paramcolor() is: ParamColor( “name”, defaultcolor )

This function adds a user definable parameter, which will beaccessible via the Parameters dialog. Right-click over the chart paneand select “Parameters” to change chart parameters.

• “name”

defines parameter name that will be displayed in the Parametersdialog box.

• defaultcolor

defines the default color value of the parameter Example:

Plot( RSI(), "RSI", ParamColor( "RSI Color", colorRed ) ); TheRelative Strength Index (RSI) is plotted. The ParamColor() functionis used in the place of color parameter of the plot() function. Notethat the style parameter is not used, which defaults to styleLine.

Launch the AFL Editor and type the above code. Verify the syntax forerrors and apply the indicator to display the following chart.

Page 89: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 5.4 Plot of RSI with Parameters dialog box displayed

Right-click and bring the Parameters dialog box. The “name” RSIColor shows the default Red color. The user can click the downarrow to open the color dialog box to select any color.

5.4

ParamStyle() function

In the previous plots we hard coded the style parameter. WithParamStyle() function we can allow the user to dynamically changethe style of the plot from the Parameters dialog box. The syntax ofparamstyle function is: ParamStyle( “name”, [defaultstyle =styleLine ], [mask=maskDefault] ) The parameters in squarebrackets are optional.

• “name”

is the parameter name displayed in the parameter dialog box

• defaultstyle

default value of style – takes a combination of style constants

• mask

binary mask that defines which styles should be visible in the dropdown list

maskDefault – show thick, dashed, hidden, own scale styles

(This is default mask for paramstyle)

maskAll – show all style flags

maskPrice – show thick, hidden, own scale, candle, bar

maskHistogram – show histogram, thick, hidden, own scale, area

Page 90: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5.5

Param() Function

The Param function is a very important function and is perhaps oneof the most used functions in AFL. The param function add userdefinable numeric parameters.

Syntax:

Param( “name”, defaultval, minval, maxval, [step], [sincr = 0]) Thefunction returns a number. The parameters in square brackets areoptional, but the square brackets are not part of the function. Thisadds a

user definable parameter dialog box accessible when right clickingthe chart pane. The dialog box allows changes in parameters, whosechanges are reflected immediately on the chart.

• “name”

defines parameter name that will be displayed in the dialog box

• defaultval

defines default value of the parameters

• minval, maxval

Page 91: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

define minimum and maximum values of the

parameter

• step

defines minimum increase of the parameter via slider in theParameters Dialog Box

• sincr

automatic selection increment value

The defaultval/minval/maxval/step have to be constant numbers.

Example:

1. p = Param( “RSI Period”,12, 2, 100 );

Plot( RSI( p ), “RSI”, ParamColor( “RSI Color”, colorRed), styleLine|styleThick );

The default parameter is 12. When displayed, the plot will be shownwith 12 as its look back period, though it can be varied between 2and 100 from the dialog box. The ParamColor has a default color ofred and it can be changed from the dialog box. Note the use ofcombination of styles. This will plot a thick line. See the plot in thefigure below.

Fig 5.5 Demo of Param() Function. The Parameter dialog box is alsoshown.

Page 92: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig 5.5 shows the plot of the function. Note how the “name”parameters are mapped to the Parameter dialog box. The defaultparameter 12 was changed to 100 in the dialog box.

5.6

Ref() Function

The Ref function is the easy way to refer the previous values of anarray. The use does not limit to arrays O, H, L, C etc. but on allderived arrays. This is an important function used extensively in AFLprogramming.

Syntax: Ref ( array, period )

The function returns an array. It references a previous or subsequentelement of the “array” passed. A positive period “p” references “p”periods in the future while negative period “p” periods ago.

The formula ref(Close, -5) refers to the Close price 5 periods ago.Let’s assign this to a variable x.

x = ref( Close, -5 );

The variable x will be an array. The value of x will be the close price5 periods ago. The figure below demonstrates this. The value of xwill be 45.5, the close Fig. 5.6 Ref() Function

Page 93: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

price of candle 5 (See figure 5.6), that is 45.5. Both the arrays Closeand x will have Barcount number of elements. However, the x arrayelements with index 0 to 4 (5 elements) will be “null”.

QUIZ::

What will be the value of the two printf statements?

printf( “%g”, x );

printf(“%g”, x[barcount-1]);

a. They will be same

b. They will be different

c. An error will be reported in the second printf() Solution:

a. They will be same.

Consider an example using the Ref in a practical situation. Supposeit is desired to enter a long position when the Close is greater thanthe previous bar’s High and when Close is greater than the 20 periodMoving Acerage of Close.

Such a condition can be verified using the following code.

Condition = Close > Ref(High,-1) AND Close > MA(Close,20); 5.7

Indicator Functions

AFL is equipped with lot of Indicator functions. These are used forthe Technical Analysis of the security concerned. Many of them canbe charted and studied. Some of the functions are given below:

• AccDist

accumulation/distribution

Page 94: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

• Adx

Average directional index

• ATR

Average true range

• BBandBot

Bottom bollinger band

• BBandTop

Top bollinger band

• CCI

commodity channel index

• MACD

moving average convergence/divergence

• OBV

on balance volume

• RSI

relative strength index

• StochD

stochastic slow %D

• StochK

stochastic slow %K

Page 95: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

This list is not complete. Refer to the AmiBroker User’s Manual forthe full list of indicator functions, its syntax and usage. As anexample let’s see how the MACD is used. MACD, the movingaverage convergence/divergence is a trend indicator. It is thedifference between two moving averages.

MACD = EMA(12) – EMA(26)

The EMA is the exponential moving average. 12 and 26 are theusual values used in the calculation of MACD. The Exponentialmoving averages are calculated on the security’s closing price.EMA(Close,12) is the function to

generate the ema values. In the MACD system a 9 period EMA ofthe MACD

itself is used as a signal line.

The syntax of MACD is macd( fast = 12, slow = 26 ).

This returns an array of values of macd using fast and slowaveraging periods.

While calling the function the desired values of the two variables canbe given.

If no values are given the default values of 12 and 26 are used.

The syntax of the signal line is signal(fast =12,slow=26,signal=9)The default values are 12,26 and 9.

Example:

Page 96: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Plot ( MACD(),”Macd”,colorBlue,styleLine);

Plot ( Signal(), “MacdSignal”,colorRed,styleLine); The above codeplots the Macd line in Blue color and Signal line in Red color in anew pane. The resulting plot is given in Fig. 5.7 below.

Fig. 5.7 Plot of Macd and Signal line

5.8

The Cross Function

This is an important function. It checks for the crossovers of twoarrays.

Syntax cross ( array1, array2)

The function returns an array and gives a True when array1 crossesabove array2 from below otherwise the result will be False(0). Todetermine when array1 cross array2 from above usecross(array2,array1). Fig. 5.8 shows two arrays array1 and array2plotted. At point A array1 is crossing array2 from below, while atpoint B, the array1 is crossing array2 from above.

Page 97: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig 5.8 Crossing of arrays.

Examples:

1. Moving average cross-over is a frequently used trading system,where one enter a long position when a fast moving average crossesa slow moving average and exit the position when the slow movingaverage crosses the fast moving average. The code below showshow one identifies the entry and exit.

//Simple moving average cross over system

//Demonstration of the cross() function

lengthFast = 10;

lengthSlow = 50;

fastMA = MA( Close, lengthFast);

slowMA = MA( Close, lengthSlow);

longEntry = Cross( fastMA, slowMA);

longExit = Cross( slowMA, fastMA);

True/False values in longEntry and longExit determine the conditionsfor buying the security and exit if already long.

2. ADX, the Average directional index is another trading indicatorused widely in trading. The main indicator is the ADX, the directionalindex itself. AmiBroker has a function ADX() to find the adx with adefault period of 14. Associated with the ADX, there are two otherindicators called the Positive Directional Index and NegativeDirectional Index.

There are two functions in AFL to determine these valuesrespectively called PDI and MDI. The cross-over of PDI with MDI is

Page 98: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

sometimes used for long entry. We can check this entry position withthe following code.

//+DI and -DI crossing trading system

//PDI() plots +DI line , MDI() plots -DI line

//All uses the default values of 14 period

positiveDI = PDI();

negativeDI = MDI();

Plot( positiveDI,”+DI”, colorGreen, styleLine | styleThick); Plot(negativeDI,”-DI”, colorRed, styleLine | styleThick); entryPoint =Cross( positiveDI, negativeDI); The procedure of capturing the entrysignals will be discussed later.

The Fig. 5.9 shows the buy signal generated of the above system.

5.9 Buy signal for +DI -DI cross-over

5.9

Page 99: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

HHV highest high value

Syntax: HHV (ARRAY, periods)

HHV calculates the highest high value in the passed ARRAY overthe preceding periods(periods include the current day). The formulaHHV(Close, 5) gives the highest high close price over the previous 5periods. Fig 5.10

shows how HHV works. HHV( Close, 5 ) gives 117.15. Most recentcandle is counted in “periods”.

Fig 5.10 HHV function

5.10 HHVBars bars since highest high over a period SyntaxHHVBars( ARRAY, periods)

The function returns an Array, and calculates the number of periodsthat have passed since the ARRAY have reached its peak within theperiod periods. For the case shown in the above Fig 5.10HHVBars(Close,5) gives the value 3.

5.11 Highest highest value

Syntax Highest ( ARRAY )

This function calculates the highest value in the ARRAY since thefirst day loaded in the chart.

Page 100: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5.12 HighestBars

bars since highest value

Syntax HighestBars ( ARRAY )

Calculates the number of bars that have passed since the ARRAY’shighest value. HighestBars (Close) returns the number of periodsthat have passed since the closing price reached its peak.

5.13 HighestSince highest value since condition met SyntaxHighestSince( EXPRESSION, ARRAY, Nth =1 ) Returns the highestARRAY value since EXPRESSION was true on the Nth most recentoccurrence.

Example:

HighestSince( Cross( Close, MA( Close, 20)), Close, 1 ) This returnsthe highest close price since the Close has crossed the 20 periodMA of Close. To make this clear see the Fig below.

Fig 5.11 HighestSince()

The example formula returns a value of 8.2.

5.14 HighestSinceBars

Page 101: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

bars since highest value since condition met SyntaxHighestSinceBars( EXPRESSION, ARRAY, Nth = 1 ) This returns thenumber of bars since highest ARRAY value since EXPRESSIONwas true on the Nth most recent occurrence. If we apply this to thechart above, the return should be 3, the last three bars.

The functions described from 5.9 to 5.13 have their “Lowest”counterparts namely LLV, LLVBars, Lowest, LowestBars,LowestSince and LowestSinceBars. These functions are similar innature and are not discussed separately.

5.15 BarsSince

This function takes an array as argument and returns an array.

Syntax BarsSince( ARRAY )

This calculates the number of bars that have passed since ARRAYwas true. It counts how much time (in bars) has passed since anevent occurred.

BarsSince( Close > 150 ) returns the number of periods that havepassed since the closing price was greater than 150. If this happensto be currently true, it will return 0.

Take Fig. 5.12 for illustrating the idea of BarsSince. In the figure theblue line is the 20 period EMA. Looking at the figure we can see that

Page 102: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

last seven bars have passed since the Close was above the 20period EMA. AFL for getting number of bars since Close was above20 EMA can be written as: x = BarsSince( Close > EMA( Close, 20 )); Fig. 5.12 Illustration of BarsSince

This should return a value of 7.

In the same figure the Close has been below the 20 period EMA forthe past 7

days. But the following formula will not give the desired result. It willreturn a value of 0 since at the current bar the passed array is true.

y = BarsSince( Close < EMA( Close, 20 );

In the above, y will be 0. To determine how many bars the Array wasremaining true, another logic has to be applied.

As another example suppose it is desired to estimate the number ofbars that has passed since the 10 day MA is above the 20 day MAand the 20 day MA is above the 30 day MA and the condition is stillremaining. The code can be written as:

condition = (MA( Close, 10 ) > MA( Close, 20 ) ) AND (MA( Close,20) > MA( Close, 30 ))

To get the number of bars this can be negated and applied to theBarsSince Function.

Page 103: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

barsCount = BarsSince( !Condition );

Fig 5.13 shows an illustration of the condition specified. Note theperfect alignment of the moving averages shows the possibility of along entry.

Fig 5.13 BarsSince Function

Exercise 5.1

1. The King Keltner trading strategy is explained. Moving average of(H+L+C)/3 is found out. An upper band is drawn with movingaverage +

ATR(Average True Range). A lower band is drawn with movingaverage -

Page 104: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

ATR. A long position is initiated when today’s moving average isgreater than yesterday’s and market action >= upper band. The longposition will be liquidated when today’s market action <= movingaverage. Use a period of 10 for the moving average and ATR. Writea code for getting the

buy and sell signals for this condition.

Solution:

avgLength = Param(“Average Length”,10,5,50); atrLength = 10;

movAvg = MA( (H + L + C)/3, avgLength );

upBand = movAvg + ATR(atrLength ) ; //ATR() calculate the Average

//True Range

dnBand = movAvg – ATR(atrLength);

//Plot the upper band and lower band

Plot(upBand,”Upper Band”,colorGreen,styleLine);Plot(dnBand,”Down Band”,colorRed,styleLine); buySignal = (movAvg> Ref(movAvg,-1)) AND (High >= upBand); exitSignal = High <=movAvg;

2. Suppose in a situation we are required to determine the number ofrecent up days. Define an up day as the current Close is greater

Page 105: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

than or equal to the prior day Close. Write a code for determining thenumber of up days.

Solution:

//Determine number of up days

condition = Close >= Ref( Close, -1);

upDays = BarsSince( !condition );

The number of down days can be similarly determined.

5.16 GapDown

There are some basic price pattern detection functions in AFL. Oneamong them is the GapDown() Function. It returns an Array andgives a value of 1 or True on the day the security’s price gaps down,meaning that yesterday’s low is greater than today’s high. Otherwisethe result will be False.

Fig. 5.14 A gap down candle

Fig 5.14 shows an example of a gap down candle. In this case thefunction GapDown() returns a True value.

QUIZ:

If x = GapDown(), how many elements of the array x will have valuesof either 1 (True ) or 0 (False)?

a. Barcount number of elements

b. Barcount-1 number of elements

c. Barcount-2 number of elements

Page 106: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Solution:

The answer is c. Barcount-2 number of elements. The maximumnumber of elements an array can have is Barcount-1. Only the firstelement of x will be Null, leaving the rest Barcount-2 number ofelements.

5.17 GapUp

This function gives a True value when the security’s price gaps up,that is, when yesterday’s high is lower than today’s low.

x = GapUp()

Fig. 5.15 Example of a gap up candle

Page 107: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

5.18 Inside

The function Inside(), which returns an array, gives a value ofTrue(1) when today’s high is less than yesterday’s high and today’slow is greater than yesterday’s low. Such a candle is called an insideday candle.

Fig. 5.16 Example for inside day

5.19 Outside

Function Outside() detects an outside day, gives a return value ofTrue when an outside day occurs. Fig 5.17 shows an outside day.

Fig 5.17 Example for an outside day.

Exercise 5.2

1. Consider the formula x = Outside(). Write a program to count thetotal number of True elements and total number of False elements inthe array x. Use a for loop.

Solution:

The array x will have ( Barcount-1 ) number of elements. Arrayelement x[0] will be Null. All the other elements will either be True(1)

Page 108: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

or False(0) depending on the return of the OutSide function. Initializetwo counters before the loop starts.

countTrue = 0;

countFalse = 0;

//Generate the x array

x = OutSide();

for ( i = 1; i < barcount ; i++)

{

if (x[i] == True)

countTrue+=1;

else

countFalse+=1;

}

printf(“Total of Trues = %g\nTotal of Falses =

%g”,countTrue,countFalse);

Result in my system:

Total of ‘True’s = 240

Total of ‘False’s = 1778

2. Write a code to generate a buy signal for the strategy given below:

- The indicator ADX(14) is above 20

- Close price crosses above the 30 period EMA

Page 109: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

- Relative strength index is higher than 70 for at least 4 barsSolution:

We are given three conditions to satisfy a buy signal. The firstcondition can be written as:

condA = ADX(14) > 20;

We explicitly used the period 14, though it was not necessary. Thesecond condition can be written as:

condB = Cross( Close, EMA( 30) );

The third condition requires that the Relative Strength Index isgreater than 70 for atleast 4 bars. There is a function called RSI() todetermine the Relative Strength Index. Combine with BarsSincefunction we can frame the third condition.

condC = BarsSince( ! RSI() > 70 ) > 4; condC will be true only whenthe RSI() is greater than 70 for atleast 4 bars.

Combine all the three conditions to get the buy signal.

buyPoint = condA AND condB AND condC;

5.20 BarIndex

This returns an array of zero based bar indices. That is the array willhave values from 0 to barcount-1.

Syntax BarIndex()

QUIZ

If x = BarIndex(), which of the following statements are true: a. x willhave barcount-1 number of elements b. x and Barcount have thesame values

c. x[0] will be Null

Page 110: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Solution:

None of the statements are true.

5.21 BeginValue

This function accepts an Array as parameter and returns a number.The function returns the value of the Array at the beginning of theselected range.

If no range is selected then the value at the first bar is returned. Toselect a range double click on the chart at the beginning and againdouble click on the end of the range.

5.22 EndValue

Similar to the function BeginValue. The return value will be the endof the range or the last bar as the case may be.

Example:

Define a range by double clicking the start of the range and the endof the range. Write a program to compute the Close prices at thebegin and end of the range. Determine the percent price rise ordecrease as the case may be and print appropriate message. If theprices happen to be same, notify that also.

EndPrice = EndValue( Close );

BeginPrice = BeginValue( Close );

if ( EndPrice > BeginPrice )

{

percentRise = (( EndPrice – BeginPrice )/BeginPrice)*100; printf(“Percent rise in price = %4.2f%%”, percentRise );

}

Page 111: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

if ( EndPrice < BeginPrce )

{

percentDecrease = (( BeginPrice – EndPrice )/BeginPrice)*100;printf( “Percent decrease in price = %4.2f%%”,percentDecrease);

}

else

printf(“There is no change in price”);

Result obtained in my system:

Percent decrease in price = 19.54%

5.23 abs

There are a large number of math functions included in AFL toempower the math capabilities of the programs written in AFL. Theabs function accepts a

number or an Array as its parameter, and returns a number or Array.The function returns the absolute value of the number or the Array.

Abs(20) returns 20 Abs(-45) returns 45.

5.24 ceil

Accepts a number or Array and calculates the lowest integer that isgreater than the number or Array.

Ceil(6.2) returns 7 while Ceil(-6.2) return -6.

5.25 floor

This calculates the highest integer that is less than the number orArray passed as parameter.

Page 112: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Floor(23.8) returns 23 and floor(-12.6) returns -13.

5.26 int

After accepting a number or Array as parameter the functionremoves the fractional portion and returns the integer part.

Int(24.3) returns 24 and int(-71.9) returns -71.

5.27 frac

The frac eleminates the integer portion of the parameter passed andreturns the fractional part.

frac(5.36) returns 0.36 and frac(-4.21) returns -0.21. Note thenegative sign is retained.

5.28 Max and Min

These functions accepts two parameters numbers and/or arrays.They return the maximum or minimum of the two parameterspassed.

min(Close,10) returns the close price or 10 whichever is minimum.

Example:

If we want to ascertain whether the Close is greater than the 10 MAand also greater than 20 MA, a formula can be written as: C >MA(10) AND C> MA(20);

Page 113: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The same situation can be written using the Max() as: C > Max( MA(10 ), MA( 20 ) );

5.29 round

This rounds a number/Array to the nearest integer.

Round(12.6) returns 13 and round(-25.3) returns -25.

5.30 Sum

This function takes two parameters Array and periods. It calculatesthe cumulative sum of the Array for a specified number of look backperiods including today.

Example:

sum(Close,20) returns the sum of preceding 20 periods closingprices.

Since the first parameter is an Array, which can be any derivative ofarrays of price values, its moving averages or anything like that,many interesting and useful results can be derived. As a simple

Page 114: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

example, suppose it is desired to examine how many bars closedabove the 10 day simple moving average of Close within a period of40 days. We can use the sum function to retrieve the desired resultas shown below:

x = Sum( Close > MA ( Close, 10 ), 40 );

WriteVal( x, 6.0 );

For the chart in Fig. 5.18, the value of x is 16.

Fig. 5.18 Demo of Sum() function

5.31 Cum

Syntax: Cum ( Array )

Cum ( Value )

It returns an array and calculates the cumulative sum of the Arrayfrom the first period in the chart.

If Array is [ 1, 2, 3, 4, 5 ,….], then cum( Array ) will be [ 1, 3, 6, 10,15,…. ].

Cum( 1 ) keeps adding 1 to its previous value. The first value will be1 and it just keeps adding 1 to its prior value. So what will be the lastvalue of the array? It should be Barcount. Check it in the Gurucommentary.

QUIZ:

If you plot Cum( 1 ), how it will look like in the chart?

Solution:

It should be a straight line starting from 1 to the value of Barcount.

Page 115: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

[ Note: In recent versions of AmiBroker, the following directive will berequired to get the above result.

SetBarsRequired( sbrAll );

Plot( Cum( 1 ), “”, colorGold );

Check User Manual for details. ]

5.32 ROC

It may quite often required to find out the percentage change in theprice value or any other array over a specified period of time. Thefunction ROC

gives the percentage rate of change.

Syntax: roc ( array, [ periods = 12 ], [absmode = False] ) Thefunction returns an array. Note the last two parameters are optionalas indicated by the square brackets. If omitted the default values areassumed.

ROC (Close) returns the 12 period percentage rate of change in theClose price with absmode = False.

Example:

It is desired to enter a long trade if the current closing price is equalto or greater than 10% from the close price 4 days ago. Write aformula to achieve this task.

Solution:

This is simple. We have the ROC function to get the percentage rateof change.

The formula can be written as:

buySignal = ROC( Close, 4 ) >= 10:

Page 116: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The value of buySignal will be either True or False. If True long entrycan be initiated.

5.33 ValueWhen

This gives the value of an array when a condition is met.

Syntax:

ValueWhen( Expression, Array, n = 1 )

This function returns the value of the “Array” when the “Expression”was true on the nth most recent occurrence. The default value of n is1.

ValueWhen( cross( Close, MA( Close, 5 ) ), MACD( ), 1 ); In theabove formula, the return value will be the value of MACD() on thefirst occurrence of the crossing of the Close price above its 5 periodmoving average.

5.34 DayOfWeek

The returned array has values 0 to 6 representing the days of theweek.

0 – Sunday

1 – Monday

2 – Tuesday

3 – Wednesday

4 – Thursday

5 – Friday

6 – Saturday

Page 117: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Example:

x = DayOfWeek(); //x will be an array of numbers 0 to 6

if ( x[ Barcount -1 ] == 2 )//We check the current bar day printf(“Today is Tuesday”); // 2 represents Tuesday else

printf( “Today is not Tuesday”);

5.35 PlotShapes

This function plots arrows and shapes on any chart pane.

Syntax:

PlotShapes( shape, color, layer=0, yposition=graph0, offset=-12)Parameters:

• shape defines the type of the symbol to be plotted. Common shapeconstants are shown below.

shapeNone

shapeUpArrow

shapeDownArrow

shapeHollowUpArrow

shapeHollowDownArrow

shapeUpTriangle

shapeDownTriangle

shapeCircle

shapeSquare

Page 118: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

There are more constants available.

• Color defines the color of the shape symbol

• layer defines layer number on which shapes are plotted. Thisdefaults to layer 0

• yposition defines Y-position where shapes are plotted. By defaultthey are plotted around graph0, the first indicator.

• offset is the distance parameter, defaults to -12.

Example:

A buy signal occurs when the Close price crosses the 10 day movingaverage.

Plot a green arrow whenever a buy signal occurs.

Solution:

buySignal = Cross( Close, MA( Close, 10 ) ); shape = IIf( buySignal,shapeUpArrow, shapeNone ); PlotShapes( shape, colorGreen );

Fig 5.19 shows a sample plot.

Page 119: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 5.19 PlotShapes sample

Exercise 5.3

1. Write an AFL code to plot the 20 day moving average of Close.When the moving average rises the plot should be in green color andwhile the MA value decreases, plot in red.

Solution:

20 day moving average is easily found with the MA function. Let uscapture the moving average array into a variable called movAverage.

movAverage = MA( Close, 20 );

Increasing and decreasing of array movAverage can be determinedby comparing current value with the prior value using the Ref()function.

An IIF() function allows us to decide the color depending upon alogical condition.

Page 120: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

colorAverage = IIf( movAverage > Ref( movAverage, -1 ),colorGreen, colorRed );

In the plot function we can use colorAverage in the place of “color”.

The complete code is given below.

//Plot rising moving average in green, dropping average in redmovAverage = MA( Close, 20);

colorAverage = Iif( movAverge > Ref( movAverage, -1 ), colorGreen,colorRed );

Plot(movAverage,”Colourful MA”,colorAverage, styleLine|styleThick); Fig 5.20 Plot of Moving Average with different colors.

2. The Ichimoku Cloud Charts is a Japanese contribution to thetrading community. The system has five components:

• Tenkan Sen

• Kijun Sen

• Senkou Span A

Page 121: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

• Senkou Span B

• Chikou

We will try to plot each of the five components as part of ourexercise. First consider the Tenkan Sen. It is calculated by averagingthe highest high and the lowest low for the previous 9 periods.

Tenkan Sen = (Highest high of 9 periods + Lowest low of 9periods)/2

Write an AFL code to calculate and plot the Tenkan Sen Array. Alsoplot the 9 period Simple Moving Average and compare the plots.

Solution:

There should not be any difficulty in doing this. We have the HHVand LLV functions to calculate the highest high and lowest lowvalues over a specified period.

//Plot of Tenkan Sen

//Define the Tenkan Sen period

Page 122: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

tenkanSenPeriod = Param(“Tenkan Period”,9, 5, 50, 1 ); tenkanSen= ( HHV( High, tenkanSenPeriod ) +

LLV( Low, tenkanSenPeriod )) / 2;

Plot(tenkansen, “Tenkan Sen”,colorGreen,

styleLine | styleDashed | styleThick );

//Plot the simple moving averages

Plot( MA( Close,9 ),”MA-9”, colorLightOrange,styleLine ); Fig 5.21Plot of Tenkan Sen

Fig. 5.21 shows the plot of Tenkan Sen. While the 9 period Simplemoving average smooths the price, the Tenkan Sen shows periodsof flattening like at points A and B.

2. The Kijun Sen is also known as “Base Line”. It is calculated byaveraging the highest high and lowest low of the previous 26periods. So the difference in calculation is only the number ofperiods used.

Write an AFL to plot the Kijun Sen.

Solution:

KijunSen = (Highest High of 26 periods + Lowest Low of 26 periods)/2.

//Plot of Kijun Sen

kijunSenPeriod = Param(“Kijun Period”,26,10,100,1 ); kijunSen = (HHV(High, kijunSenPeriod) +

LLV( Low, kijunSenPeriod ))/2;

//Plot the Array

Page 123: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Plot( kijunSen, colorRed, styleLine );

Fig. 5.22 shows a plot of the Kijun Sen.

Fig 5.22 Plot of Kijun Sen

3. Senkou Span A and Senkou Span B are discussed together. TheSenkou Span A is the average of the Tenkan Sen and Kijun Sen andis projected 26 days in the future on the chart.

Senkou Span A = ( Tenkan Sen + Kijun Sen )/2

The Senkou Span B is calculated by averaging the highest high andlowest low of the prior 52 periods and projecting it 26 periods into thefuture.

Senkou Span B = (Highest high of prior 52 periods + Lowest low ofprior 52 periods ) /2.

Write an AFL program to calculate and plot Senkou Span A andSenkou Span B. The area between the two lines is called the KumoCloud. Plot the Cloud also.

Page 124: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Solution:

//Plot of Tenkan Sen

//Define the Tenkan Sen period

tenkanSenPeriod = Param(“Tenkan Period”,9, 5, 50, 1 ); tenkanSen= ( HHV( High, tenkanSenPeriod ) +

LLV( Low, tenkanSenPeriod )) / 2;

Plot(tenkansen, “Tenkan Sen”,colorGreen,

styleLine | styleDashed | styleThick );

//Plot of Kijun Sen

kijunSenPeriod = Param(“Kijun Period”,26,10,100,1 ); kijunSen = (HHV( High, kijunSenPeriod) +

LLV( Low, kijunSenPeriod ))/2;

//Plot the Array

Plot( kijunSen, colorRed, styleLine );

//Define a variable for the shifting parameter of Kumo shiftRight =Param(“Kumo Shift”,26,0,60,1);

//Senkou Span A

senkouSpanAColor = ParamColor(“Senkou Span A Color”,colorSeaGreen );

senkouSpanA = ( tenkanSen + kijunSen )/2;

//Last parameter of the Plot function projects the plot to 26

//default period to the future.

Page 125: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Plot( senkouSpanA, “Senkou Span A”, senkouSpanAColor,styleLine,Null,Null,shiftRight );

//Senkou Span B

senkouSpanBPeriod = Param(“Senkou Span B Period,52,20,200,1);senkouSpanBColor = ParamColor(“Senkou Span B Color”,colorPink);

senkouSpanB = ( HHV(High,senkouSpanBPeriod) +

LLV(Low,senkouSpanBPeriod))/2;

Plot(senkouSpanB,”Senkou Span B”,senkouSpanBColor,styleLine,Null,Null,shiftRight );

//Plot the Kumo

kumoColorUp = ParamColor( “Kumo Up Color”,colorSeaGreen);kumoColorDn = ParamColor(“Kumo Down Color,colorPink);PlotOHLC(senkouSpanA,senkouSpanA,senkouSpanB,senkouSpanB,

“”,IIf( senkouSpanA>senkouSpanB, kumoColorUp,kumoColorDn,styleCloud|styleNoLabel,Null,Null,shiftRight ); Fig 5.23 shows a plotof the Cloud.

Page 126: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 5.23 The Kumo Cloud

The above code used the PlotOHLC() function to plot the KumoCloud.

This function plots a customized chart with the open, high, low, closeparamer values appropriately modified.

4. The last component of Ichimoku system is the Chikou. It is nothingbut the current price shifted back 26 periods. Using the Ref()function, this can be plotted easily. (Exercise to the reader) 5. Aninvestor is curious to know whether the current closing price hasdropped by 10 percent (minimum) within 10 number of bars at themost. To help him take his further course of action, write a code togenerate a True/False signal to know whether the 10 percent dropcompleted within 10 bars.

Solution:

Page 127: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Here the ROC function will come to our rescue. Since the price drophas to happen within 10 bars, we can limit our ROC calculation up to10 bars.

We can write the code as given below:

bar = 0;

for ( i = 1; i <= 10; i++ )

{

drop = ROC( Close, i );

if ( drop[ Barcount – 1 ] <= -10 )

{

//Capture the bar count

bar = i;

break;

}

}

dropSignal = drop <= -10;

If the value of dropSignal is True, a 10 percentage drop completedwithin 10

bars. The ‘bar’ variable will hold the number of bars required to dropto 10

percent. Note the use of drop[Barcount-1] in the if() statement. Anarray cannot be used in the if() statement.

Page 128: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

6. It is to be determined whether the Close price has been above its5 day simple moving average for the past 5 periods. Write a formulato check this.

Solution:

One possible solution looks like this:

ma5 = MA( Close, 5 );

isOk = C > ma5 AND Ref( C,-1 ) > Ref( ma5, -1 ) AND

Ref( C,-2) > Ref( ma5, -2 ) AND

Ref( C,-3) > Ref( ma5, -3 ) AND Ref( C,-4) > Ref( ma5, -4 ); Whilethis works well, there is a condensed version to find out the sameresult. The Sum () function adds the values of an array for aspecified number of times. Using Sum() we can rewrite the formulaas: isOk = Sum( C > ma5 , 5 ) == 5;

Look, how simple the formula becomes. The isOk variable will beTrue only when the Sum() returns a 5, that is when the first 5 closesare above ma5. Fig. 5.21 shows a chart example of this. In this chartisOk will be True as the last 5 closes are above ma5, the 5 dayMoving Average.

Page 129: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 5.24 Sum( C > ma5, 5 ) = 5

7. Write a formula to find out whether the 5 day moving average hascrossed the 10 day moving average within past 5 days.

Solution:

The formula can be written using the Sum() function as shownbelow:

//5 day moving average

ma5 = MA( Close, 5 );

//10 day moving average

ma10 = MA( Close, 10);

crossedOk = Sum( Cross( ma5, ma10 ), 5 ) > 0; The flag crossedOkdetermines whether during the prior 5 days period, ma5 has crossedma10. A value of True confirms it has crossed. See Fig.5.25 for achart demo.

Fig 5.25 crossedOk = True

8. Write a formula that returns the value of the 14 day RSI on the2nd most recent occurrence of the closing price closing above its 10day simple moving average.

Solution:

Page 130: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

ValueWhen is the function to be used here. The “Array” will be RSI(14 ) and the “Expression” will be Cross( Close, MA( Close, 10 )) andthe value of n = 2. Hence the required formula is:

ValueWhen( Cross( Close, MA( Close, 10 ) ), RSI( 14 ), 2 ); 9. Plot aChandelier Exit graph for liquidating long positions.

Solution:

Chandelier Exit is a volatility based indicator that is used as an exitpoint

for long/short positions. For finding Chandelier Exit the ATR and the

Highest High Value of High or Close is used with appropriate inputparameters. Usually 22 period value is used. This is since there are22

trading days in a month. A multiplier of 3.0 is usually used for theATR, though these are all varied according to user requirements.

The formula for Chandelier Exit for long is: 22 day Highest Highvalue of High – ATR( 22 )*3.0

The formula can then be written as follows.

chandelierExit = HHV( High, 22 ) - ATR( 22 )*3.0; We have usedvalues of 22 and 3. This array can be plotted.

//Chandelier Exit plot

periods = 22;

multiplierATR = 3.0;

//Build the array

chandelierExit = HHV( High, periods) – ATR( periods )*multiplierATR;

Page 131: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

//Plot the graphic

Plot(chandelierExit,”ChandelierExit”,colorRed,styleLine|styleDashed);Fig. 5.26 shows a typical plot.

Fig. 5.26 Chandelier Plot

Chapter 6

Write Your Own Functions

6.1

AmiBroker allows user definable functions to be created and used asmany times like the built-in functions. If you find that a particular logicis not available in AFL, you can write a function yourself according tothe syntax of function definition and use it in the AFL program.Chapter 3 described how user defined functions can be created withfew examples. To recap the syntax, the definition of function follows:

Page 132: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

function function_name ( [parameter,…] )

{

Statements;

[ return result;]

}

The function definition begins with the keyword function, followed bythe function name. The parameter list is enclosed in parenthesesafter the function name. The body of the function is included withinthe braces. The keyword return returns the result to the callingprogram.

In this chapter we will practice writing many functions. Thesefunctions may not be useful for practical programming use in AFL.Our intention is to develop AFL writing skills.

1. We have already seen the built-in function BarsSince(ARRAY).This calculates the number of bars that have passed since theARRAY

was true. Write a function yourself, that performs the same task asthe built-in function BarsSince.

Solution:

Let’s name the function as myBarsSince. The function has oneparameter of type Array. Start with the function definition: functionmyBarsSince( array )

{

body of function

}

Page 133: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The passed parameter is “array”. We can name the parameteranything of our choice. The only matter concerned is that theparameter will be an ARRAY and is to be considered so within thebody of the function.

The idea is simple. Start from the last bar, traveling backwardscounting the bars each time the passed array remains False until itbecomes True. The counted value is returned from the function whena True value is detected in the array. Using a while loop, the functioncan be written as:

function myBarsSince( array )

{

//Initialize the counters

count = 0;

i = 1;

while ( array[BarCount – i] == False )

{

i++;

count++;

}

return count;

}

To test this function: Use the Guru Commentary.

x = myBarsSince( Close > 536.7 );

Page 134: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

y = BarsSince( Close > 536.7 );//Use the built-in functionWriteVal(x,2.0);

WriteVal(y,2.0);

Result in my system: ( See Figure 6.1 )

5

5

Fig 6.1

2. The HHV function returns the highest value of the array within therange prescribed. As an exercise, write a function yourself to givethe same functionality as the HHV.

Solution:

Name the function as myHHV with parameters array and range.Assume that the highest will be the last array element itself and logthis into a variable. Now using a for, loop travel backwards, until therange is reached, each time resetting the highest value. Thecomplete function is given below.

function myHHV( array, range )

{

myHighest = array;

for ( bar = 2; bar <= range; bar++ )

Page 135: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

{

myHighest = Max( myHighest, array[ Barcount – bar ] );

}

return myHighest;

}

Test the function:

x = myHHV( C, 60);//Our function

WriteVal( x, 5.2 );

y = HHV( C, 60 );//The built-in function

WriteVal( y, 5.2 );

Result :

59.10

59.10

3. Write a user defined function that is similar the the LLV built-infunction. Test the function and compare with the LLV. ( Not solved )

Page 136: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

4. Write a function to detect a pullback after the security reached ahigh.

This may be required to enter a trade. The function parameters arethe array (usually High) and the number of periods of pullbackrequired.

Solution:

See the figure 6.2 for the definition of a pullback. The figure shows a4

period pullback after reaching a peak.

Fig. 6.2 A pull back example

The function HHVBars return the number of bars that have passedsince the array reached its peak during the assigned period. We willuse this function to write our function.

function pullBack( array, period )

{

pbPeriods = HHVBars( array, period+1 );

return IIf( pbPeriods == period, True, False );

}

Note the use of period+1 in the parameter list of HHVBars. Thefunction returns True if the ‘period’ number of days are pulled back,otherwise a False is returned.

An example usage is given with reference to the chart in Fig. 6.3below.

Page 137: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 6.3 Use of pullBack function

x = pullBack( H, 3 );

In this case x will be true. We are actually checking whether therewas a three day pullback after reaching a peak.

5. Write an AFL function to check for a Bearish Engulfing Pattern.

Solution:

Fig. 6.4 shows a typical Bearish engulfing pattern.

Fig. 6.4 Bearish Engulfing Pattern

Page 138: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The pattern is a two candle pattern. The first candle must be a whitebody. The second candle, a black one, must open above the close ofthe first candle and should close below the open of the first whitebody.

Visually, the white body of the first candle appears fully covered bythe

black body of the second candle. There should have a prior uptrendbefore the engulfing formed. Though, a subjective matter, we definean uptrend when the prior four highs are higher than their respectiveprior highs.

function bearishEngulfing ()

{

//Define a white body and a black body

whiteBody = C > O;

blackBody = O > C;

//Define engulfing

Page 139: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

engulfing = Ref(whiteBody,-1) AND blackBody AND

O > Ref(C,-1) AND C < Ref(O,-1);

//Define uptrend

upTrend = BarsSince( !( Ref( H.-1 ) > Ref( H, -2))) >=4; returnupTrend AND engulfing;

}

The function returns an Array whose values are True(1) or False(0)depending upon a bearish engulfing pattern is detected or not. Totest see the chart portion in Fig. 6.5.

Fig. 6.5 BearishEngulfing ( )

x = bearishEngulfing();

WriteVal( x[Barcount – 71],2.0);

Result: 1 (Bearish engulfing pattern detected at (Barcount-71)thcandle.

Page 140: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

6. A function to detect a Bullish Engulfing Pattern can be written insimilar way. This is left as an exercise to the reader.

6.2

#include

The #include is a preprocessor include command. This commandhelps to include external AFL code into your formula. Those familiarwith the C

programming should be using the header files used with their Ccode. The

#include in AFL is for similar use.

How to use the #include command?

Write all our own functions in the Formula Editor and save with asuitable name into the “include” folder.File→SaveAs→AmiBroker→Formulas→Include.

See Fig. 6.6.

Fig. 6.6 Include Folder

Once saved in the “Include” folder, we need not specify the path for itbecause AmiBroker will search for the include files in the Includefolder, which is the default folder. Later when we desire to use thefunctions defined in the include statement, we can use the functionsdirectly without further defining them.

#include <myFunctionDefinitions.afl> x = bearishEngulfing();

WriteVal(x,2.0);

Page 141: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including
Page 142: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Chapter 7How To Make a WatchList?

7.1

What is a Watchlist?

The Fig. 7.1 shown on the right side is

displayed when AmiBroker opens first. The

bottom shows four tabs namely,Layouts,

Layers, Charts and Symbols.

When the Symbols tab is clicked all the

symbols in the opened database will be

displayed as shown in the Figure. The

vertical and horizontal scroll bars allow

us to navigate through the Symbols. The

Symbols displayed will be a huge list,

sometimes run into few thousands of

Stocks. An investor might not be

interested in all the listed Stocks. He will always have his ownpersonal choices.

He may be interested in stocks of certain

Page 143: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Sector or those included in a particular

Fig. 7.1

Index. Another person might be long in a number of Stocks, whichhe may wish to watch on a daily basis. While, it is possible to watchall the stocks desired from the Symbols List, it is sometimesinconvenient to go through a long list of stocks. Every one wouldwish to have a small list of his choice of stocks easily accessible andplaced conveniently under a Name of his preference. This is wherethe Watchlist of AmiBroker helps the user. A Watchlist is actually asubset of the Symbols in the Database placed under a user definedName. AmiBroker provides multiple ways of creating a Watchlist.

We can assign the same symbol to more than one Watchlist. Anynumber of Watchlists can be created and maintained.

7.2

Page 144: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Watchlist Creation

Follow these steps to create a WatchList.

1. Start AmiBroker

2. Click the Symbols Tab

3. Click on the > to the left of

Watch Lists

4. Predefined List names List 0

List 1, List 2 etc are displayed.

5. Place the cursor over List 0. A

message displays “List 0(0 symbols)

6. Place the cursor over List 0. Click

after few seconds. List 0 becomes

editable. Type in “myList”

Fig. 7.2

7. The name “myList” has replaced List 0. We have just created anew Watchlist, but no symbols have been added to it.

8. Right-click on myList. From the resultant Menu, Left-click on

“Type-in symbols….”

See Fig. 7.3

Fig. 7.3

Page 145: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Type the three symbols ABB,ACC,SUNTECK. Separate the symbolswith a comma. Any number of symbols can be entered, eachseparated by a comma. Click OK. Now the Watchlist myList iscreated with three symbols added into it. See Fig. 7.4. Keep in mindthat the typed names have to match exactly like the Symbolsavailable in the database.

Otherwise, though the symbols get added to the Watchlist, a chartcannot be displayed for the corresponding symbol.

Fig. 7.4 myList Watchlist

7.3

How to add symbols to an existing Watchlist?

Symbols can be added or removed from an existing Watchlist.Follow these steps.

1. Click the Symbols tab to bring the list of available Symbols.

2. Press the Ctrl key and click the desired Symbols to be added. Theselected symbols will be highlighted.

Page 146: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

3. Right-click on any of the highlighted Symbol and select Watchlistfrom the resulting Menu.

4. Select “Add Selected symbol(s)” from the next Menu options. Thisbrings up the following window.

Fig. 7.5

5. Select myList and click OK. The selected Symbols will be savedinto myList.

7.4

Create a Watchlist by importing from a text file.

Creating a Watchlist for the Symbols already in a text file (*.txt) isvery simple.

Page 147: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Open the Notepad editor and type in few Symbols, one in each lineas shown in the Fig. 7.6.

Fig. 7.6 Text file with 10 Symbols

Save the file as Portfolio.txt. Create a Watchlist with the namemyPortfolio.

Follow these steps to add the 10 symbols to myPortfolio.

1. Right-click on the myPortfolio and select Import… from theresulting menu.

2. Select myPortfolio and click OK. Ensure that the File radio buttonis selected.

3. Select the Portfolio.txt file we created and click Open. This will addthe 10 Symbols in the file into myPortfolio Watchlist. See Fig. 7.7.

Fig. 7.7 myPortfolio

Page 148: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

7.5

A practical Example

The Nifty 50 is a diversified 50 stock index accounting for 12 sectorsof the Indian economy. Many fund houses use this for bench markingtheir portfolios. It is decided to have a Watchlist of the Nifty 50shares, so that later we can back test our trading strategies on thisWatchlist. As an exercise we will make a Watchlist of the Nifty 50shares.

Solution:

If we know the names of the Ticker Symbols, we can easily make aWatchlist by any of the methods described earlier. Typing in 50symbols without making any error can be time consuming. We canlook for another method. The Symbols for Nifty 50 shares arealready listed in the Nse India website. We will make use of thisfeature. Follow these steps: 1. Use the following link to down loadthe list of the 50 shares in .csv format.https://www.nseindia.com/products/content/equities/indices/

nifty_50.htm

2. Save the file to the Desktop. It will look like the Fig. 7.8 below.

Fig. 7.8 Nifty 50 Shares

Page 149: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

3. We need only the Symbol column. Delete columns CompanyName, Industry, Series and ISIN Code. The Header row (row 1) isalso not required. Delete row 1 also. We will be left with the SymbolNames only. Save the resulting file as “Nifty-50List.csv”. CSV is forthe Comma Separated Value.

4. Create a Watchlist “Nifty50”. What remains is to add the Symbolsof the 50 shares into the Watchlist. Follow the steps described in 7.4to add the Symbols. You will open the Nifty-50List.csv file instead ofPortfolio.txt.

Exercise to the reader:

Create a Watchlist called NiftyFMCG. Add to this all the stock tickersin the Nifty FMCG Index. The following link lists all the names ofstocks required.

www.nseindia.com/products/content/equities/indices/sectoral_indices.htm

Chapter 8

Create Your own Exploration

8.1

Explore in AmiBroker

The Explore function in AmiBroker helps us to filter Stocks accordingto the criteria we specify. The criteria can be written in simple AFL.Having said filter the Stocks, the idea behind this goes to a reservedvariable filter. This variable controls which stocks are to be added tothe filtered list. The name filter is a reserved word and should not beused for any purpose other than this.

8.2

Customized Report Generation

Page 150: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

One good feature of Explore is that the report generated can becustomized as per our requirement. This is possible with theAddColumn() function.

AddColumn Function

The function in its simplest form takes two parameters an Array anda “name”

for the display heading of the Array.

AddColumn( Close, “Close”);

The above statement display a heading of “Close” and displays theClose value in the tabular statement. Any number of AddColum()statements can be given in the AFL.

Example 1:

Write an Exploration to filter all the stocks and to display the Closeprice, Open price and the Volume.

Filter = 1;//A filter with 1 will display all the stocks. It doesn’t filter anystock.

AddColumn( Close, “Close Price”);

AddColumn( Open, “Open Price”);

AddColumn( Volume, “Volume”);

Example 2:

Write an Exploration to filter all stocks that are traded above the 30period Exponential Moving Average. Display with Close price, andEMA(30).

Page 151: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Filter = Close > EMA( Close, 30 );

AddColumn( Close, “Close”);

AddColumn( EMA( Close, 30 ), “EMA – 30” );

Example 3:

Write an Exploration to filter stocks that have a price change of 2%or more.

Run the exploration on the Nifty50 watchlist created earlier anddisplay the results.

In this example we will describe the exploration process in detail.Open the Formula Editor and enter the following code.

//Calculate the change in price in percentage priceChange = ( Close- Ref( Close, -1) )/Ref( Close, -1)*100;

//The priceChange is an array containing %Change in prices.

//Compare this with 2 to get the filter

Filter = priceChange >= 2;

AddColumn( Close,”Close”);

AddColumn( Ref(Close,-1), “Prior Close”);

AddColumn(priceChange,”%Price Change”);

Page 152: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

When completed the Editor looks like the Fig. 8.1.

Fig 8.1 Filter for Exploration

We can save the file with a file name such as priceChange.afl. Nowclick the Toos Menu and from there click “Send to Analysis window”.The following screen is displayed.

Fig. 8.2 Analysis Window

Note the file name is displayed in the Formula edit box. At top fromleft to right we have options of Scan, Explore, Backtest andOptimize. Below there is an Apply to Dropbox. We can select fromthree options All symbols, current and filter. Click on the filter icon(green funnel). This opens the following window.

Fig. 8.3 Filter settings window

Page 153: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

From the Filter settings dialog box choose Market as Market 1 andWatchlist as Nifty50. Click Ok. From the Range Dropbox select 1recent bar(s). Now click on “Explore”. The result is now displayed.Fig 8.4 shows the result.

Fig. 8.4 Explored list

The result shows three tickers of Nifty50 shares had a price changeof 2%

or more on 20/12/2018.

QUIZ:

What will be the result of the following exploration: Filter = 0;

Solution:

This filters all the stocks. Nothing will be displayed.

Ex ercise 8.1

1. A trader thinks it is best to buy when the Close price is tradedabove the 100 day simple moving average. While keeping thiscondition, he wants to buy only when the 13 period moving averagecrosses the 40 period moving average. He wanted to short listpossible candidates from the Nifty LargeMidcap 250 Index. Write anExploration formula to find outthe results.

Solution:

Page 154: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The Nifty LargeMidcap 250 Index consists of a portfolio of 100 largecap and 150 mid cap companies listed on NSE. Referring to Chapter7, first make a Watchlist called “NiftyLargeMidcap250” containing theIndex Shares. The Ticker Symbols can be downloaded from the NSEwebsite.

The first condition is that the Close has to be above the 100 MA. Theformula for this can be written as:

above100MA = Close > MA( Close, 100 );

above100MA will be an array of True or False elements.

The next condition can be created using the Cross( ) function.

averageThirteen = MA( Close, 13 );

averageForty = MA( Close, 40);

crossThirteenForty = Cross( averageThirteen, averageForty ); ThecrossThirteenForty will be an array of True or False elements.

These two conditions have to be satisfied for a valid buy. Combinethese two using the AND. The final code will be:

above100MA = Close > MA( Close, 100 );

averageThirteen = MA( Close, 13 );

averageForty = MA( Close, 40 );

Page 155: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

crossThirteenForty = Cross( averageThirteen, averageForty ); Filter= above100MA AND crossThirteenForty;

AddColumn( Close,”Close”);

AddColumn( averageThirteen, “MA13”);

AddColumn( averageForty, “MA40”);

Type this code in the Formula Editor and Send to Analysis Window.

Choose the Filter watchlist to NiftyLargeMidcap250 and Explore for 1

recent bar. The result is shown in Fig. 8.5 below.

Fig. 8.5

Suppose we want to filter the entire stocks in the database, chooseAll Symbols in the Apply to DropBox. An Exploration gives thefollowing result as shown in Fig. 8.6.

Page 156: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Fig. 8.6 Exploration Entire database

Chapter 9

Back Testing Trading Strategies

9.1

Introducing Trading Strategies

A trading strategy is basically a set of rules that determine entry andexit points for a particular stock under consideration. The rulesframed should be objective in nature and there should not be anysubjectivity or ambiguity.

Example:

Buy when the Close price crosses above the 50 day SMA.

Sell when the Close price crosses below the 50 day SMA.

The above two rules are objective in nature and there is noambiguity in its definition and can be coded in AFL as:

Cross( Close, MA( Close, 50 );

Cross( MA( Close, 50 ), Close);

Trading strategies can be as simple as the one given above or muchcomplicated with a large number of lines of code. Our intention hereis not learning designing Trading strategies, but only limited to howto make a Back test of a strategy. Most trading strategies will have anumber of rules and will not be as simple as the one above. Backtesting is done on historical data over a period of time to test theprofitability of the strategy. This is very much necessary beforeactually putting real money in the market.

9.2

Page 157: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

AmiBroker environment for Back testing

The Analysis Window is the interface where you back test yourtrading strategy on historical data. This will give an insight into thestrengths and weaknesses of the strategy, before we put real moneyinto trading. You can reach the Analysis window by a couple of ways.From the Analysis main menu click New Analysis….This will bringyou to the Analysis window. Another quick option is by clicking thesecond icon (New Analysis window) on the Speed Bar Button ( Fig.0.3 ). Either way, it brings the following Analysis window as shown inFig. 9.1.

Fig. 9.1 Analysis window

This we have already seen while discussing the Explore function.We will be using the Backtest icon( red ellipse ) in the Analysiswindow. Though, a window is opened, note that no file is opened bythis procedure. You cannot edit a file directly in the Analysis window.There should be a file with buy and sell rules to make a back test. Ifa file is already saved, we can open it from the Analysis window forback testing. Click on the ‘Pick a file’ icon on the right extreme of theAnalysis window to open the desired file.

9.3

Reserved variables used in Back testing

The first step in Back testing is to have objective rules for entry andexit into the market. Once the rules are decided, write them as Buyand Sell rules in AFL. Suppose a person thinks the following rules: I

Page 158: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

will buy the stock when its Close price crosses above the 20 daymoving average.

I will sell the stock when its Close prices crosses below the 20 daymoving average.

He has decided the buy and sell rules. These can be converted intoAFL as given below.

Buy = Cross( Close, MA( Close, 20 );

Sell = Cross( MA( Close, 20 ), Close );

Here the Buy and Sell are special Reserved variables which areused for setting the buy and sell rules for the Back tester. The Backtester engine use the Buy and Sell array values to determine theback testing process.

A value of 1 in Buy opens a long trade.

A value of 1 in sell closes the long trade.

Similarly “Short” and “Cover” variables can be used.

A value of 1 in Short opens a short trade.

A value of 1 in Cover closes the short trade.

To Back test our system, just click the “Backtest” icon in the Analysiswindow.

The following are the reserved variable names applicable to theBack testing.

These names should not be used for user defined variables.

Variable

Description

Page 159: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Buy

Define a buy rule. Enter long position

Sell

Define the sell trading rule. Close the long position Short

Define a short sell rule. Enter a short position Cover

Define cover trading rule. Closes the short position Buyprice

Define buying price array

Sellprice

Define selling price array

Shortprice

Define short selling price array

Coverprice

Define buy to cover price array

Exclude

A true value of this excludes current symbol from processRoundlotsize

Define round lot sizes used by the back tester ticksize

Define ticksize used to align prices generated by built-in stops

Pointvalue

Allows to read and modify future contract point value Margindeposit

Allows to read and modify future contract margin positionsize

Page 160: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Allows control dollar amount of percentage of portfolio that isinvested into the trade

9.4

A Back testing example

Now let’s see a back testing example. The first step is to create Buyand Sell rules. For demonstration purposes, we will assume that agood buy will be when the Macd line crosses the Signal line and atthe same time the Adx is above 30. The long position thus acquiredwill be closed when the Signal line crosses the Macd line. The buyand sell conditions described above can easily be written in AFL veryeasily as given below: Buy = Cross( MACD( ), SIGNAL( ) ) ANDADX( ) > 30; Sell = Cross( SIGNAL( ), MACD( ) );

Page 161: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The above two lines completes the buy and sell rules. The MACD,SIGNAL and ADX functions are used with its default values. You canexperiment with different values of parameters. The SIGNAL line isthe 9 period Exponential Moving Average of MACD. A typical Buyand Sell signal generated is shown in Fig. 9.2.

Fig. 9.2 Buy/Sell signals

In the above buy and sell rules the Buy and Sell are arrays and holdeither a True (1) or False (0) value. There are chances that after abuy/sell signal generation and before closing sell/buy signals furtherbuy/sell signals are generated. These excessive signals have to beremoved. AFL provides a function for this purpose, the ExRem( )function. The ExRem function Removes Excessive signals. We willadd ExRem in our code.

Buy = ExRem( Buy, Sell );

Sell = ExRem( Sell, Buy );

Open the Formula Editor and enter the following statements into theeditor window.

//backTest.Afl

//Sample backtesting code

Buy = Cross( MACD( ), SIGNAL( ) ) AND ADX( ) > 30; Sell = Cross(SIGNAL( ), MACD( ) );

//Remove excessive signals

Buy = ExRem( Buy, Sell );

Sell = ExRem( Sell, Buy );

Save this as backTest.Afl, check syntax and send to the AnalysisWindow.

Page 162: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

To perform the back test, the back tester requires some otherparameters sch as the initial equity to start with, type of trades suchas long, short or both, maximum number of open positions etc.These can be set up on the Settings window which is available whenthe Settings tab ( a wrench like icon ) is clicked. Select the Generaltab of the Settings window as shown in Fig. 9.3.

Fig. 9.3 Back tester settings

Set the Initial equity as 100000. We will start with an initial capital of100000.

Set the Positions: to Long. We are testing for long only trades, noshorts.

Set the Periodicity: to Daily. Daily data is used for back testing.

Page 163: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

We can set up the Commissions & rates. Settings, if done in this willappropriately will be reflected in the profit & loss calculation in thetrade report. In our case, for simplicity we are not setting anything inthis. A 100 in the Account Margin: indicates that we are not usingany margin amount. Click on the Trades tab to set up the buy andsell price conditions and trade delays.

Set the Buy price: to Open. This directs to buy at the Open price.

Set the Buy delay: to 1. This ensures a trade delay of 1 day after thesignal generation.

The direction is to buy at the Open price of the next day.

Set the Sell Price: to Close. This directs to sell the Close price.

Page 164: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Set the Sell Delay: to 0. Make the sell on the same day of signalgeneration.

The selling of the security happens on the signal day at the Closeprice.

After completing the Trade set ups, we will proceed with the settingof Stops.

Stop losses are very important and the appropriate placementensures profit levels and prevent large draw downs. Click on theStops tab to bring the Stops Settings window as shown in Fig. 9.4.

Fig. 9.4 Stop settings

Set the Maximum loss stop at 6%.

Set the Profit target at 10%.

Disable the trailing stop. (Trailing stops can be placed at % level,point level or

% of profit level)

Set the N-bar stop at 12 bars. We are allowing the trade to exit after12 bars.

Now Click on the Report tab.

Set the Result list shows: as Trade list.

Click on the Portfolio tab.

Set Max. open positions: as 4. This means that at any time only fourlong positions will be held by the back tester.

Page 165: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Click Ok to close the Backtester settings.

We are almost ready to make the Back test. What remains is theselection of back testing duration and the portfolio of stocks to betested. See Fig. 9.5.

Fig. 9.5 Back testing

Click on Filter icon and choose the Nifty50 watchlist. We will test ourback test on the 50 shares of the Nifty50 portfolio. Click on Rangeand choose From-To dates. Select the from to dates as 01/01/2015to 12/31/2018. Now click the “Backtest” button. The back testingcompletes within seconds. To see the results of the back test click onthe “Reports” icon ( spread sheet like icon in Fig. 9.5 ). Part of thereport is shown in Fig. 9.6.

The report has 6 tabs namely Statistics, Charts, Trades, Formula,Settings and Symbols. The Statistics report shows the key metrics ofthe trade like:

• Initial capital

• Ending capital

• Net profit

• Net profit %

• Exposure %

• Annual return %

• Risk adjusted return %

• Max trade drawdown

• Sharpe ratio

• K-ratio

Page 166: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The above are but few of the metrics in the report. The profitability ofthe strategy is evident from the report.

Fig. 9.6 Back test results

The Charts tab shows the Portfolio equity curve and the Drawdowncurve.

The Trades tab gives complete details of the actual trades carriedout.

9.5

Backtester settings from within the AFL code While writing thestrategy for back testing, we used different settings in the Settingdialog box. However, we can set the desired settings from within thecode. The settings done in the code will override whatever given inthe Settings dialog box.

To define the maximum open positions, from within the code, we canuse the SetOption function.

Page 167: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

SetOption( “MaxOpenPositions”, 4 );

The above code sets maximum open positions to 4.

SetOption( “Initial Equity”, 100000 );

The above code allocates a 100000 as initial equity.

To control the trade delays the SetTradeDelays function can beused.

The syntax is:

SetTradeDelays( buydelay, selldelay, shortdelay, coverdelay ) Thissets trade delays applied by the backtester. The settings done fromthe Settings window will be overridden by these settings.

SetTradeDelays( 1, 0, 0, 0 );

A buy delay of 1 and sell delay of 0 is set.

Two variables control the price at which the trade is executed. Theyare the BuyPrice and SellPrice. Set them appropriately.

BuyPrice = Open;

SellPrice = Close;

To enable more than one security to be traded we have to addPositionSize variable in our formula, so that funds are appropriatelydistributed among all traded symbols.

PositionSize = -25;

The above code indicates 25% of the equity is invested into onetrade.

PositionSize = 10000;

Page 168: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The above code implies an amount of 10000 is invested in singletrade.

Let totalPosition be the maximum number of open positions.

totalPosition = 4;

SetOption( “MaxOpenPositions”, totalPosition ); PositionSize =-100/totalPosition;

The stoploss placement can be done using the ApplyStop function.The ApplyStop function instructs AFL to exit the trade when apredetermined stoploss or target condition is met. The syntax ofApplyStop follows: ApplyStop( type, mode, amount );

type can be:

stopTypeLoss - maximum stop loss stop

stopTypeProfit – profit target stop

stopTypeTrailing – trailing stop

stopTypeNBar – N – bar stop mode can be:

0 – disable stop ( stopModeDisable )

1 – amount in percent ( stopModePercent ) or stopModeBars 2 –amount in points ( stopModePoint )

3 – amount in percent of profit (risk)

amount =

percent/point loss/profit trigger/risk amount. This could be a number (static stop level ) or an array ( dynamic stop level ).

In our demo case the stop placements can be done as followed.

Page 169: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

ApplyStop( stopTypeLoss, stopModePercent, 6 ); //6% maximumstop loss set ApplyStop( stopTypeProfit, stopModePercent, 10);//10% profit target settings ApplyStop( stopTypeTrailing,stopModeDisable, 0 );//Trailing stop disabled ApplyStop(stopTypeNBar, stopModeBars, 12 );//12 bar exit settings The entireAFL for the back tested strategy is rewritten below:

//backTest.Afl

//Demo of back testing a strategy

//Set initial equity to 100000

SetOption( “Initial Equity”, 100000 );

//Set buy on next day open at open price and sell on same day closeat close

//price

SetTradeDelays( 1, 0, 0, 0 );

BuyPrice = Open;

SellPrice = Close;

//Set maximum open positions and equity allocation totalPosition = 4;

SetOption( “MaxOpenPositions”, totalPosition ); PositionSize =-100/totalPosition;

//Apply the stop settings

ApplyStop( stopTypeLoss, stopModePercent, 6 ); //6% maximumstop loss set ApplyStop( stopTypeProfit, stopModePercent, 10);//10% profit target settings ApplyStop( stopTypeTrailing,stopModeDisable, 0 );//Trailing stop disabled ApplyStop(stopTypeNBar, stopModeBars, 12 );//12 bar exit settings

Page 170: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

//Define buy and sell rules – the strategy

Buy = Cross( MACD( ), SIGNAL( ) ) AND ADX( ) > 30; Sell = Cross(SIGNAL( ), MACD( ) );

//Remove excessive signals

Buy = ExRem( Buy, Sell );

Sell = ExRem( Sell, Buy );

Save the file.

Exercise 9.1

1. Write buy and sell rules formula for the trading system describedbelow: Buy when the prior bar close is below the Bottom BollingerBand and the current bar closed above the Bottom Bollinger Band. Abuy is also initiated when the current high has exceeded 2% abovethe Top Bollinger Band.

Sell rules are exact reverse of the Buy rules.

Solution:

There are two functions in AFL to find the Bollinger Bottom and Topbands arrays. They are the BBandBot and BBandTop functions. Bothaccept an array, a period and a width for standard deviation, asparameters.

bottomBand = BBandBot( Close, 20, 2 );

topBand = BBandTop( Close, 20, 2 );

Buy = ( Ref( Close, -1 ) < Ref( bottomBand, -1 ) AND Close >bottomBand ) OR

Close > 1.02*topBand;

Page 171: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Sell = (Ref( Close, -1 ) > Ref( topBand, -1 ) AND Close < topBand )OR

Close < 0.98*bottomBand;

Buy and Sell signals generated for the above system for a particularstock is shown in the Figure 9.7 below.

Fig. 9.7 Buy/Sell Signals

2. Write Buy and Sell rules for a trading system described below:Buy: A 2% gap up in price on the previous day with at least twiceaverage 5

day volume.

Sell: A 2% gap down in price on the previous day with at least twiceaverage 5 day volume.

Solution:

volAverage = MA( Volume, 5 ); //5 day moving average of volumeBuy = Low > Ref( High, -1 )*1.02 AND Volume >= volAverage*2; Sell= High < Ref( Low, -1 ) * 0.98 AND Volume >= volAverage*2;

Chapter 10

Revision Exercises

Page 172: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

The primary intention of this book was to introduce to the reader themost basic aspects of AFL programming. It is expected that afterreading this book, a beginner in Amibroker will be able to attemptadvanced topics. Before concluding, I will present few moreexercises. Though it may look repetitive, I urge you to do all theexercises given and compare your results with the solutionsprovided. Programming is a task like swimming. To master it, youhave to actually do lot of exercises. This will only make a solidlaunching pad, from where you can make a take off with confidence.

1. What will be the output of the following printf statement?

printf( %% );

a) %%

b) %

c) An error will be reported

Solution:

Correct answer is c. The argument to printf statement should be aformatted string and should be enclosed in double quotes.

2. A number can be converted to a string using the Built-in functionNumToStr.

Several strings can be concatenated using the operator +. It isdesired to print the current closing price as “Current closing price isxxxx” (xxxx should replace the current closing price). Write a printfstatement to achieve this.

Solution:

Using the NumToStr function, we can convert the current closingprice to a string. Use + to concatenate with “Current closing price is“. The required statement is:

Page 173: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf( “Current closing price is “ + NumToStr( Close ) ); Typicalresult: Current closing price is 33.950

3. AFL has a function called WriteIf that will return different stringsdepending on the true/false value of an expression passed as aparameter. The syntax of the WriteIf is:

WriteIf( Expression, “True Text”, “False Text” ) This function can beused only within the Guru commentary. If Expression evaluates toTrue “True Text” is returned otherwise “False Text” is returned.

Write a formula to display a commentary “Bullish” when the MACD isgreater than zero and “Bearish” otherwise.

Solution:

WriteIf( MACD() > 0, “Bullish”, “Bearish” ); 4. In Exercise 3 above,there may be a possibility that the MACD( ) be equal to

zero which we wish to register as “Neutral”. Revise the statement toaccommodate this condition.

Solution:

It is possible to combine several WriteIf calls to handle multiplepossibilities.

WriteIf( MACD( ) > 0, “Bullish”, WriteIf( MACD( ) < 0, “Bearish”,“Neutral” )); 5. Which of the following printf statements is wrong?

a) printf( “%g %4.2f”,5,6);

b) printf(“The values are: %g and %3.4f”,23,12); c) printf(“%g +%f”,3.2,6);

d) printf(“%g %g,45,12,22);

Solution:

Page 174: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

None of the printf statements is wrong.

6. Which of the following identifier names are valid?

a) MonthlyMacdValue

b) _AboveAverage

c) ShortTime Average

d) 2ndMovingAverage

e) my_AtR-Value

f) shiftedValue65

g) Bill#

Solution:

a) Legally acceptable name

b) Invalid. The first character must be a letter c) Invalid name.Spaces are not allowed in identifier names d) Invalid. Must beginwith a letter

e) Illegal. A hyphen is used in the name. This is not allowed f)Acceptable name

g) Invalid. Special character is not allowed 7. What will be the outputof the following code fragment?

Item1 = 500;

Item2 = 200;

Item3 = 150;

billTotal = Item1 + Item2 + Item3;

Page 175: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

printf( “Total Cost = “ + NumToStr( BILLTOTAL ) ); a) 850

b) Total Cost = 850.000

c) An error will be reported with variable ‘BILLTOTAL’ used withouthaving been initialized.

Solution:

Correct answer is b). The three zeros after the decimal point in theresult is due to the default behavior of format specification in theNumToStr. This can be modified to our requirement.

Kindly note that variable names in AFL are case insensitive. billTotaland BILLTOTAL represent the same entity.

8. One of the following is a wrong way of commenting. Identify it.

a) shortMALength = 10; //Length of the fast moving average b)//Define the length of the slow

moving average//

fastMALength = 50;

c) /*Find the cross of moving averages

*/

crossArray = Cross( MA( shortMALength, fastMALength); Solution:

Answer is b).

9. Which of the following is not an AFL built-in function?

a) MACD( )

b) Typeof( )

Page 176: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

c) ATR( )

d) Plot( )

Solution:

Answer is b). Typeof( ) is an operator, though it looks like a function.

10. Write a program to display the days of the last five bars. Enterthe formula in the chart commentary window and show the results. (Hint: Use the DayOfWeek function and the switch..case statement ).

Solution:

Depending upon the return of DayOfWeek, we can find out whichday it was.

Since the days of the last five bars are to be displayed, we will usean outer for loop which loops five times. Inside this, a switch..casestatement will find out which day is represented and prints it out. Apossible solution is given below.

//Display days of last five bars

arrayDays = DayOfWeek( );

//Outer loop 5 times

for ( bar = 1; bar < 6; bar++ )

{

switch ( arrayDays[ Barcount – bar ] )

{

case 0:

printf( “Sunday\n” );

Page 177: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

break;

case 1:

printf( “Monday\n” );

break;

case 2:

printf( “Tuesday\n” );

break;

case 3:

printf( “Wednesday\n” );

break;

case 4:

printf( “Thursday\n” );

break;

case 5:

printf( “Friday\n” );

Page 178: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

break;

case 6:

printf( “Saturday\n” );

}

}

Sample output is shown in Fig 10.1 below. Saturday and Sunday willnot be displayed as these are trading holidays.

Fig. 10.1 Last five trading days

11.

A cross-over trading system is suggested. Initiate a buy signal whenthe 10

day exponential moving average line of the Typical Price crosses itsown 3

period exponential moving average line. A sell signal is generatedwhen the 3

period smoothed line crosses the 10 period moving average line.Write buy and sell signal formulas, plot the two average lines andbuy and sell shape arrows on the graph.

Solution:

Typical price is defined as ( High+Low+Close )/3. The Avg gives theTypical price directly. Avg is an array like the Open, Close etc.

//Cross-over trading system

emaLine = EMA( Avg, 10 ); //10 day EMA of typical priceemaSmoothed = EMA( emaLine, 3 );//Smooth the line - 3 period

Page 179: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

//Generate buy and sell arrays

Buy = Cross( emaLine, emaSmoothed );

Sell = Cross( emaSmoothed, emaLine );

//Define a shape parameter so that only one PlotShapes is neededshape = Buy*shapeUpArrow + Sell*shapeDownArrow;

//Plot the shapes on the graph with buy arrow below the low of the

//candle and sell arrow above the high of the candle. The lastparameter

//of the PlotShapes implements this.

PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low,High ) ); Fig. 10.2 shows a sample plot.

Fig. 10.2 Cross-over Trading

12.

Page 180: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Write a formula to detect whether today is a five day high and today’sClose is below the open.

Solution:

High > Ref( High, -4 ) AND High > Ref( High, -3 ) AND High > Ref(High, -2 ) AND High > Ref( High, -1 ) AND Close > Open ; There is acondensed version of writing the same.

High > Ref( HHV( High, 4 ), -1 ) AND Close > Open; 13.

We are looking for an overbought condition, when the 14 day RSI,has been remaining above 70 for at least 6 days during a span of 10days. Write an exploration formula and short list a portfolio of stockssatisfying this condition.

Solution:

Launch the Formula Editor and enter the following formula.

Filter = Sum( RSI( 14 ) > 70, 10 ) >= 6;

Page 181: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

Click “Filter” and select NiftyLargeMidcap250. In Range select 1recent bar and click Explore. Fig. 10.3 shows a short listed portfoliosatisfying the required condition.

Fig. 10.3 Overbought stock list

See Fig. 10.4 for a sample plot for BANKINDIA.

Fig. 10.4 RSI(14) > 70

14.

Write a function to calculate the Chaikin Money Flow Index. Write itwith a user variable parameter from within the chart. Use thisfunction to display the indicator in a lower pane of the chart.

Solution:

Chaikin Money Flow is an oscillator, that measures the buying andselling pressure over a set period of time. The indicator fluctuates

Page 182: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

above and below the zero line. The link below gives a description ofthe CMF indicator.

https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf

Calculation steps for a N-period CMF indicator is given below.

1. Money Flow Multiplier = [ ( Close – Low ) - ( High – Close ) ] / (High – Low ) 2. Money Flow Volume = Money Flow Multiplier *Volume for the period 3. N-period CMF = N-period sum of MFV / N-period sum of Volume When calculating the money flow multiplier, inthe event of High and Low becoming equal, a division by zero errorwill occur. We have to guard against this in our AFL code.

//Chaikin Money Flow

function ChaikinMF( period )

{

mfm = IIf( H != L, ( ( C – L) - ( H – C ) ) / ( H – L ), 0 ); mfv = mfm *Volume;

cmf = Sum( mfv, period ) / Sum ( Volume , period ); return cmf;

}

//Define period for Chaikin MF

cmfPeriod = Param( “CMFPeriod”,21,10,100 );

//Build the ChaikinMF indicator array by calling the function cmf =ChaikinMF( cmfPeriod );

//Define color of the plot. Green for above zero, Red for below zerocmfColor = IIf( cmf > 0, colorGreen, colorRed );

Page 183: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

//Plot the indicator

Plot( cmf, “Chaikin MF”, cmfColor, styleHistogram | styleThick ); Fig.10.5 shows a plot for Chaikin Money Flow.

Fig. 10.5 Chaikin Money Flow

15.

How can you override the Delay settings set in the Backtestersettings dialog box?

Solution:

By using the SetTradeDelays( ) in the AFL code.

SetTradeDelays( BuyDelay, SellDelay, ShortDelay, CoverDelay );Now we have come to the end of this short course. By this time youshould be in a position to write your own AFL code. If you have atrading idea in your mind, try converting it into AFL formula. Any

Page 184: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

quantifiable idea, without ambiguity, can be converted to a formula.Wish you good luck.

Page 185: Contents AmiBroker is a Trademark of Amibroker.Com AmiBroker · 2021. 3. 14. · What is AmiBroker? AmiBroker is a complete and advanced trading solution. It has many tools including

ADX-PPO PINCH TRADING By the same author is available fordownload from Amazon.

https://www.amazon.com/ADX-PPO-PINCH-TRADING-AJAN-K-ebook/dp/B07HRLJ

RNX/ref=sr_1_1?ie=UTF8&qid=1549517031&sr=8-1&keywords=ajan+k+k

https://www.amazon.in/ADX-PPO-PINCH-TRADING-AJAN-K-ebook/dp/

B07HRLJRNX/ref=sr_1_1?ie=UTF8&qid=1549517122&sr=8-1&keywords=ajan+k+k