The best resources for Amibroker AFL can be found via the Amibroker AFL library or one of the Amibroker user forums. Here there are usually plenty of generous traders who are happy to share some of their code and give assistance if needed.
I also provide plenty of free AFL code here so make sure to come back regularly.
New to Amibroker?
Luckily writing AFL for Amibroker is fairly straightforward even for someone with no background in programming. If you are new to Amibroker I will recommend a piece of advice that I first received when on the Amibroker forum:
Start off with end of the day data for US stocks and look for simple, robust systems.
Everything you need from a good trading system can be found with EOD data and from here it should be possible to reach returns of 30% CAR a year with a little bit of work. From there you can start to work on even greater returns but remember higher returns will inherently mean higher risk.
By end of day data I mean data that shows the high, low, open, and close from the trading day. It’s far better to concentrate on daily or weekly systems and ignore day trading if you are new to the markets.
And remember, no trading system can be created without good quality data. I recommend Norgate Premium Data and you can get a free trial of the service here.
Writing AFL for Amibroker
When you start writing Amibroker AFL it’s a good idea to begin with a kind of template that you can then use as the basis of several trading systems. I usually start off with something like this, (the set options can also be set in the Amibroker panel but it’s better to write them into the code):
SetOption( “InitialEquity”, 10000);
This one sets how much capital you have to trade e.g. $10,000
SetOption( “UsePrevBarEquityForPosSizing”, True );
Allows position size to be calculated using % of previous bar’s funds. Can be turned on or off
SetTradeDelays( 1, 1, 1, 1 );
It’s usually not possible to trade on the exact moment that a signal occurs. So you can delay the buy, sell, short and cover entries by 1 (or more) bars.
SetOption( “MaxOpenpositions”, 10);
Sets the Maximum open positions you want at any one time. I’ve set mine at 10 as I trade a portfolio of 10 stocks.
SetOption(“SeparateLongShortRank”, True );
Amibroker enters trades based on the signal rank also known as positionscore. If you hold short and long positions this variable allows them to be ranked separately so you dont end up favoring one direction over the other.
MOL = 10;
MOS = 5:
This code allows a maximum of 10 long positions and 5 short positions at any one time.
SetOption( “AllowSameBarExit”, True );
Allows trades to be closed on the same bar that the exit signal or stop signal occurs
Numberpositions = 10;
SetPositionSize( 1, spsShares );
This is the segment of code I use to set my positionsize or risk. -20 / 10 means my position size per trade is 20% of my account divided by 10.
In other words, if I start with $10,000, my first trade will have a stock value of $200. To get the number of shares, you simply divide this number by the stock price. Eg, for a stock that is $12, I will buy 16 shares.
Once that’s in place it’s a good idea to define positionscore metrics and enter the formulas for any indicators you plan to use. Remember, positionscore determines the rank. If you have more than one trade signal, Amibroker will take the trade that is scored the highest. This is quite important, particularly if your system generates lots of signals on the same day/ bar. You can use any calculation you like. Here are some ideas:
PositionScore = RSI(14) – 100; Prefers long positions with lower RSI values and short positions with high RSI
PositionScore = ATR(10) – 100; Prefers long positions with smaller ATR (average true range) values
PositionScore = ROC(C,1) * -1; Prefers long positions with lower ROC (rate of change) values
Then you can enter your buy and sell conditions. When you write AFL for Amibroker it’s a good idea to keep everything organised so that you dont make any mistakes and you can easily understand it in the future. Here’s a very simple moving average crossover example:
fastema = EMA(C,50);
slowema = MA(C,200);
Buy = Cross(fastEMA,slowEMA); Buys when the 50 period EMA crosses over the 200 period EMA.
Sell = Cross(slowEMA,fastEMA); Sells when the 200 period EMA crosses under the 50 period EMA.
Once you have tried this, you can set about optimising some of your parameters like below:
fastema = Optimise(“fastEMA”,50,25,200,25);
slowema = Optimise(“slowEMA”,200,180,300,20);
When run, the optimiser will cycle through these values and present them in a table showing which ones performed the best. The numbers in brackets stand for (default setting, first iteration, final iteration, step). In other words the optimizer will first test the fastema with using the ’25’ setting, it will then keep testing at intervals of 25 until it gets to 200 where it stops. If you run the backtest without the optimiser, Amibroker uses the default (50) setting.
After your buy and sell conditions you can enter code that plots your various indicators on the chart and any calculations that you may have with the equity curve.
For more code be sure to check back here regularly as I plan to post several trading systems – analysed and presented with the AFL for Amibroker.
Thank You For Reading
Joe Marwood is an independent trader and the founder of Decoding Markets. He worked as a professional futures trader and has a passion for investing and building mechanical trading strategies. If you are interested in more quantitative trading strategies, investing ideas and tutorials make sure to check out our program Marwood Research.
This post expresses the opinions of the writer and is for information, entertainment purposes only. Joe Marwood is not a registered financial advisor or certified analyst. The reader agrees to assume all risk resulting from the application of any of the information provided. Past performance is not a reliable indicator of future returns and financial trading is full of risk. Please read the Full disclaimer.