You are on page 1of 7

APPENDIX A

AmiBroker

H ere is a brief list of token names (keywords and identifiers) that are used
internally in AmiBroker.

■ Keywords
The following is a subset of keywords: 293

■ buy—Defines ‘‘buy’’ (enter long position) trading rule.


■ sell—Defines ‘‘sell’’ (close long position) trading rule.
■ short—Defines ‘‘short’’ (enter short position – short sell) trading rule.
■ cover—Defines ‘‘cover’’ (close short position – buy to cover) trading rule.
■ buyprice—Defines buying price array (this array is filled in with the default
values according to the Automatic Analyser settings).
■ sellprice—Defines selling price array (this array is filled in with the default
values according to the Automatic Analyser settings).
■ shortprice—Defines short selling price array (this array is filled in with the
default values according to the Automatic Analyser settings).
■ coverprice—Defines buy to cover price array (this array is filled in with the
default values according to the Automatic Analyser settings).
■ exclude—If defined, a true (or 1) value of this variable excludes current symbol
from scan/exploration/backtest. They are also not considered in buy-and-hold
calculations. Useful when you want to narrow your analysis to certain set of
symbols.

The Ultimate Algorithmic Trading System Toolbox + Website: Using Today’s Technology to Help You Become a Better Trader. George Pruitt
© 2016 by George Pruitt. Published by John Wiley & Sons, Inc.
■ roundlotsize—Defines round lot sizes used by backtester (see explanations
below). Automatic Analysis (new in 4.10).
■ ticksize—Defines tick size used to align prices generated by built-in stops (see
explanations below). (Note: It does not affect entry/exit prices specified by
buyprice / sellprice / shortprice / coverprice.)
■ pointvalue—Allows to read and modify future contract point value (see
backtesting futures). CAVEAT: this AFL variable is by default set to 1 (one)
regardless of contents of Information window UNLESS you turn ON futures
mode (SetOption(‘‘FuturesMode’’, True )).
■ margindeposit—Allows to read and modify future contract margin (see
backtesting futures).
■ positionsize—Allows control dollar amount or percentage of portfolio that is
invested into the trade (more information available in the ‘‘Tutorial: Backtesting
Your Trading Ideas’’).
■ positionscore—Defines the score of the position. (More details: ‘‘Tutorial:
Portfolio Backtesting.’’) Automatic analysis.
■ numcolumns—Exploration only: defines the number of your own columns
(excluding predefined ticker and date columns) and assigns the column value to
294
the variable.
AMIBROKER

■ filter—Exploration only: controls which symbols/quotes are accepted. If ‘‘true’’


(or 1) is assigned to that variable for given symbol/quote, it will be displayed in
the report. So, for example, the following formula will accept all symbols with
closing prices greater than 50: filter = close > 50;.

■ Flow Control Structures


Here are some identifiers to help you control program flow:
Loops:
do (part of do-while statement)
while
for

Conditional execution / Flow control:

if (part of if-else statement)


else (part of if-else statement)
switch
break (part of the switch statement or for/while statements)
case (part of the switch statement)
continue (part of for/while statements)
default (part of switch statement)

■ Functions
The following programming constructs are available for the creation of subprograms:
function
procedure
return
local (variable scope)
global (variable scope)

■ Utilizing Exploration for Debugging


295
AmiBroker provides a very easy to use form of program output to help with analysis

AMIBROKER
and as a tool for debugging. You have probably already seen the Explore button right
beside the Backtest button. Explore allows you to output various values created
by your AFL code in an easy to read spreadsheet format. This output is displayed
in the Results tab—the same place where a backtest outputs its information. Here
is an example of an exploration that prints out various indicator values:

/* Sample Exploration
Print out some indicator values */

Filter= 1;

myMACD = MACD(12,26);
myRSI = RSI(14);
myStoch = StochD(14,3,3);
myMovAvg = MA(C,19);
myClose = C;
AddColumn(myRSI,"RSI");
AddColumn(myStoch,"StochD");
AddColumn(C,"Close");
AddColumn(C>myMovAvg,"C>MAV(19)");
AddColumn(C,"Close",format= 1.4);

The code snippet starts out by assigning MACD, RSI, StochD, and MAV values
to four user-defined variables: myMACD, myRSI, myStoch, and myAvg. These
variables are then used in the AddColumn function along with a descriptive name.
AddColumn can take a variable number of parameters, but most of the time you
will only need to pass two or three. The first parameter is the name of the array that
you want to print and the second parameter is a string that will be printed as the
column heading. The third and optional parameter is the format the array will be
printed out in. Figure A.1 shows the printout of this particular exploration.
Notice how the first ‘‘Close’’ column only shows two decimal places, whereas
the second ‘‘Close’’ column has been formatted to show four. The AddColumn
capability is very powerful because it is so easy to print out the internal workings
of your algorithm. This tool comes in really handy when a trading algorithm isn’t
performing the way you intended—just print out the values that make up the criteria
296 of your buy / sell / short / cover logic. Remember to include Filter = 1 at the
top of your code listing. This informs AmiBroker to go ahead and allow values to be
AMIBROKER

printed out in a spreadsheet format in the Results window.

FIGURE A.1 Results of an exploration with three parameters.


Here is the source code from Chapter 4 that included some interesting topics that
is discussed here.

//Chapter 2 MACD utilizing AMIBROKERS


//Exploration Feature

Filter = 1;

PositionSize = MarginDeposit = 1;

Setting Filter = 1 turns on the Exploration tool. PositionSize = Margin-


Deposit = 1 facilitates futures trading mode.

myMACD = MACD(fast=12,slow =26);


myMACDAvg = MA(myMACD,9);

myMACDDiff = myMACD - MYMACDAvg;

leftBar2 = Ref(myMACDDiff,-4);
leftBar1 = Ref(myMACDDiff,-3);
centerBar = Ref(myMACDDiff,-2); 297
rightBar1 = Ref(myMACDDiff,-1);

AMIBROKER
rightBar2 = Ref(myMACDDiff,0);

Call the MACD function and calculate the difference between it and its nine-period
smoothing average. Utilize Ref to get historic values in the myMACDDiff array.
Visualize the MACD difference plotted as a histogram. This bit of code is gathering
information to determine if pivot point of the histogram has occurred. CenterBar is
two bars back and leftBar1, leftBar2, rightBar1, and rightBar2 are self-explanatory.

COND3 = C > MA(C,100);

COND1 = centerBar < 0 AND centerBar < Min(leftBar2,


leftBar1) AND centerBar < min(rightBar1,rightBar2);

COND2 = centerBar > 0 AND centerBar > Max(leftBar2,


leftBar1) AND centerBar > Max(rightBar1,rightBar2);

COND3 is set to true when the close is above the 100-day moving average.
COND1 is set to true when the center bar forms a pivot low and is below 0.
COND2 is set to true when the center bar forms a pivot high and is above 0.
Buy = COND1 AND COND3;
Short = COND2 AND NOT(COND3);

BuyPrice = C;
ShortPrice = C;

longEntryPrice = ValueWhen(Buy,BuyPrice,1);
shortEntryPrice = ValueWhen(Short,ShortPrice,1);

Buy = ExRem(Buy,Short);
Short = ExRem(Short,Buy);

The Buy array is filled with 1’s when a pivot low has formed below zero in the
histogram and the current price is below the 100-day moving average. The Short
array is filled with 1’s when a pivot high has formed and the current price is below
the 100-day moving average. The longEntryPrice is captured when Buy is set
to 1. The ValueWhen function returns the second array value when the first array
is set to 1. You must use the ExRem function to remove redundant Buys and
Shorts. In other words, only turn subsequent Buys on or Shorts on when the existing
long/short positions are either liquidated or reversed.

298 Sell = Cross(C, longEntryPrice - 3 * ATR(10));


AMIBROKER

Cover = Cross(ShortEntryPrice + 3 *ATR(10),C);

Buy = ExRem(Buy,Sell);
Short = ExRem(Short,Cover);

AddColumn(longEntryPrice,"BuyPrice");
AddColumn(longEntryPrice - 3 * ATR(10),"longStop");
AddColumn(Sell,"Sell ?");

Sell array (long liquidation) is turned on when the close crosses 3 ATR below the
longEntryPrice.

■ Position Sizing in Futures Mode


Here is the exact formula used to apply an ATR Risk-Based Fixed Fractional money
management scheme to a trading algorithm.

RiskPerContract = 2 * ATR(10);

PositionRisk = 1;
PctSize = PositionRisk * MarginDeposit / ( RiskPerContract
* PointValue );

SetPositionSize( PctSize, spsPercentOfEquity );

At first, the formula might look confusing, but plugging in some values will help
explain things. Assume you are working with the emini-SP and the MarginDeposit
is $5,600, PointValue is $50, InitialEquity = $500, 000, and 𝟐 𝐗 𝐀𝐓𝐑(𝟏𝟎) =
40.00.
PctSize = .01 × $5, 600 ∕ (40 × $50) = $560∕ $2, 000 = 0.028, or 2.8%
PctSize then can be used to calculate PositionSize:
$500, 000 × 0.028∕5600 = 2.5 contracts
Compare this to the Fixed Fractional calculation without using the margin-
Deposit:
$500, 000 × 0.01 ∕ (40 × 50) = 2.5 contracts
You get the exact same number of contracts, and since you can’t have a partial
contract, the number of contracts is rounded down to 2.
299

AMIBROKER

You might also like