amibroker logo amibroker buy argumentsUsing Amibroker it is possible to build sophisticated trading systems with just a few lines of code. Complexity is not an important ingredient for a good trading system. The most important thing is to build a system that is based on an edge, some identifiable pattern that you have found in the data itself which you believe results in profitable trades.

Following are 20 simple Amibroker buy arguments to use as part of a trading system or not at all. They are basic and won’t make a trader any money on their own.

Make sure to test the codes before using them. I have written them up from memory on my way back from a trip so I can make no guarantees. It’s been a busy day, much work and a little play.

For more Amibroker ideas see my post on Amibroker collections.

20 Amibroker buy arguments

Buy when open crosses EMA 25
FastEMA = EMA (C,25);
Buy = Cross(O, FastEMA);

Buy when open is higher than yesterday’s close
Buy = O > Ref(C,-1);

Buy when open higher than yesterday’s high
Buy = O > Ref(H,-1);

Buy when close is higher than yesterday’s low
Buy = C > Ref(L,-1);

Buy when open higher than EMA 25
Buy = O > EMA(O,25);

Buy when close higher than EMA 50
Buy = C > EMA(C,50);

Buy on golden cross (moving average crossover)
Buy = Cross (EMA(C,50),EMA(C,200));

Buy when RSI lower than 30
Buy = RSI(14) < 30;

Buy when open is above top Bollinger Band
Buy = O > BBandTop(O,15,2);

Buy when close is below bottom Bollinger Band
Buy = C < BBandBot(C,15,2);

Buy on a Monday
buy = dayofweek() == 1;

Buy on a Tuesday
buy = dayofweek() == 2;

Buy on a Wednesday
buy = dayofweek() == 3;

Buy on a Thursday
buy = dayofweek() == 4;

Buy on a Friday 
buy = dayofweek() == 5;

Buy when ADX is over 20
Buy = ADX(14) > 20;

Buy on 100 bar high
Buy = H > Ref(HHV(H,100),-1)

Buy when EMA crosses over and high is highest for 200 days
Buy = Cross(EMA(C,50), EMA(C,200))AND H > Ref(HHV(H,200),-1)

Buy after third higher open in a row
Buy = O>Ref(O,-1)AND Ref(O,-1)>Ref(O,-2)AND Ref(O,-2)>Ref(O,-3);

Buy when RSI crosses 70
VRSI = RSI(14);
Buy = Cross( 70, VRSI );


In this post I will show how to build a quick trading system for the Nifty, the Indian stock exchange, using Amibroker. The purpose of this isn’t to provide a working trading system but to illustrate how easily it can be done. The video here proves just how quick the process can be.

Building a Nifty positional trading system

Position trading is all about taking relatively long-term, directional trades in the market. Therefore, to build this system I first considered what type of strategies would fit the bill. Since the Nifty is the main index for the Indian stock market it’s highly liquid and tends to exhibit strong trending properties. I decided that a moving average strategy might be a good one to use.

Step 1

The first step is to download Amibroker and Amiquote to the computer and both can be downloaded on a free trial. While Amibroker is the software used to test strategies, Amiquote is used to import free historical data into the program.

Step 2

When Amibroker first opens, the default database and template is pre-loaded. (A new database can be setup but in this instance I will just keep open the preloaded one – this contains financial information for the 30 stocks in the Dow Jones Industrial Average.)

What we want to do is upload historical data for the Nifty so that we can test various strategies and this is easily done with Amiquote.

Simply open up Amiquote and click the yellow cross ‘Add tickers’ button. Then type in the Yahoo! ticker symbol for the Nifty which is ^NSEI.

Set the dates for the download, make sure the source is set to Yahoo Historical and then click the green ‘play’ button to download the data.

Step 3

So long as Amibroker is open in the background historical data for the Nifty will be automatically imported into the program. Look over to the symbol panel on the left and you’ll find ^NSEI at the top. Click on it and the data will be displayed in the main chart. (You can drag any indicators such as moving averages over from the technical indicators panel straight onto the chart and it will display it.)

Step 4

I want this Nifty positional trading system to find profitable trends using moving averages so now I will test my ideas using the back-tester.

I still prefer to use the old back-tester so I click over to Analysis > Old Automatic Analysis. This brings up the analysis window. Here, I click Edit in order to open up the example trading code that comes pre-loaded.

Step 5

To create a new system I simply delete what’s already there and start writing in my own code.

I have decided that this positional trading system will buy the Nifty when the 100 day EMA crosses over the 250 day EMA and sell when it crosses back under. The system will use the close to calculate values and use the open to enter and close trades. The exact code is shown here:

EMAfast = EMA(C,100);
EMAslow = EMA(C,250);
Buy = Cross(EMAfast,EMAslow);
Sell = Cross(EMAslow,EMAfast);
BuyPrice = O; SellPrice = O;

Note: the system uses trade delays to ensure signals are entered on the next open and not the previous open. The system also uses 100% cash available to take positions and commissions (refined using the settings tab in the Analysis window) are set to 0.05% per trade.

Next it is important to verify the syntax is correct by clicking on the red tick. I then give the system a name and close the window making sure to save changes.

Step 6

Now that the code has been written, I simply re-pick the formula file which has been saved into the Amibroker folder on my computer.

Under ‘Apply to’ I tick current symbol (^NSEI) and under dates I choose the 1/1/2007 to the 1/1/2011. I then click back test and Amibroker gets to work.

Step 7

It takes Amibroker less than a second to perform the back test and the system’s results are clearly indicated on the bottom of the analysis window. Clicking on Report allows a much more in depth view of the systems results.

Nifty positional trading system results

As you will see by the results, only one trade was placed producing a compound annual return of 11.90% with a maximum system drawdown of -11.25%.

I then re-run the system on forward data, from 2011 to the present day and see whether the system performed was able to replicate those results.


As you can see, building a Nifty positional trading system is incredibly simple with Amibroker and the free data from Yahoo. While these results on the Nifty may not sound that great, they are actually not bad. Considering that the system produced just one trade in both periods, the risk per trade is OK and the CAR/MDD metric is decent too.

Using this strategy on a number of other markets together and incorporating some more rules could lead to a worthwhile trend system.


As a trader, most of my strategies have focussed on the philosophy of trend following. However, over time I have realised that mean reversion trading systems can also be profitable if implemented correctly. Sometimes they may need to be slightly longer in duration and involve some discretionary element in order to work well.

The fact is, financial markets move in cycles. At times they will trend, and trend following strategies will perform best, and at other times they will range and revert back to the mean. Range-bound markets are actually more common than trending markets which means mean reversion strategies usually have higher winning percentages than trend following.

How to build profitable mean reversion trading systems

The first step in building a successful mean reversion strategy is to first agree on what mean reversion is. While trend followers look for trending markets that go on for long periods, mean reversion traders look for markets that are unusually low or high, which will eventually return back to their normal level. Thus mean reversion is about looking for markets that have deviated significantly from their average, which will likely return to the average at some point in the future.

Many types of mean reversion strategies therefore rely on technical indicators to indicate when a market is away from it’s mean. Moving averages, Bollinger Bands, RSI, MACD and other oscillators can all be used in this way.

The idea of mean reversion can also be applied to fundamentals. For example, stocks generally move in correlation with earnings so if a company’s earnings come out substantially above the recent average, it’s a good bet that next quarter earnings will come back down more in line with the long term average.

It’s a similar story for economic concepts such as inflation and economic growth which will often return to the long-term average over time.

Step One – Look for patterns in the data

The first step to building a mean reversion trading system then, is to scan price charts looking for ideas or patterns you might be able to profit from. If you are trading a particular market do you notice any interesting behaviour? Does the market spring back whenever RSI touches an oversold level of ’20’? Does the market usually come back after it’s moved 2 standard deviations in the opposite direction?

Step Two – Distill into code

The next step is to get your idea down on to paper in the form of mathematical code. By doing so, you will be able to use a trading program like Amibroker to test that idea on real price data. You could do this by hand but it would be a very lengthy and inefficient use of time.

Step Three – Back-test the code thoroughly

In order to test the code properly you’ll need to learn a bit about proper system design. In essence, you will want to test the strategy as thoroughly as possible; on different time frames and on different markets. Always make sure to keep a big chunk of data reserved for out of sample testing. You then do your testing on the in-sample data and confirm your system once with the out-of-sample data. If it fails using the out-of-sample data then the system is not robust enough and you’ll have to start again. Walk-forward analysis is something that you should get to grips with in order to make sure the system will hold up in different market conditions.

Step Four – Paper trade the system

If you go through the steps of proper system design and you end up with a mean reversion strategy you believe to be robust, it’s important not to rush into the market and start trading it straight away. Take some time to validate on fresh, live data first so that you can be confident that the strategy will work. Because at the end of the day, the only true out-of-sample data is future data. Once you have traded the system on paper for a while and it still works, then you can start applying it with real money.

Step Five – Review the system

If you have a profitable and robust mean reversion strategy, then it should perform in a similar fashion to your previous back-tests. You can use this information to keep an eye on the system and make sure it is behaving as it should be. Keep an eye on the system metrics such as the win to loss ratio, the expectancy, or the drawdown levels. If you experience a drawdown that is significantly larger than any you experienced in back-testing mode, it’s a sign that the system has broken down.

Considerations for mean reversion trading systems

Risk Control

One of the major problems with mean reversion trading systems is risk control. A mean reversion trader sees a market that has dropped from the average as cheap; the problem is that if the market continues to drop, it becomes even cheaper. The appropriate response from a mean reversion trader is therefore to continue to buy the market as it falls.

This goes against most principles of risk control since it is not wise to add to a losing position or to try and catch a falling knife.

The response from mean reversion traders is to use different types of exits to trend followers. Time based exits are often used and mean reversion traders usually have rules in place to stop them from adding too many times to an already losing trade.

Clean data

Of course, another key consideration is the data that’s used to test the trading system. It goes without saying that a trading system is only as good as the data it’s tested on so without good data you can’t build a good system. I use Norgate Premium Data which works with a number of different platforms. You can get a free trial of the service here.

Market conditions

Another key consideration for mean reversion traders is the condition in the market. As already mentioned, mean reversion strategies work best in range-bound markets and overall, markets tend to be range-bound around 60% of the time. However, mean reversion systems can fail spectacularly during big trends. It therefore makes sense to have a strategy for when the market is not ranging.

For example, you might want to operate a trend following strategy as well as a mean reversion system or you might have a filter to stop you entering mean reversion trades when the market is trending.

mean reversion trading systems by howard bandyThis book by Dr Howard Bandy is good for mean reversion traders. I will say that some of the ideas are pretty complex, and overall the book is geared towards Amibroker users. Nevertheless, it’s a good addition to the library for serious traders.


Ideas for mean reversion trading systems

• When the market price is greater than the upper Bollinger Band, sell the market
• When the market price is lower than the lower Bollinger Band, buy the market

• When RSI is less than 20, buy the market
• When RSI is more than 80, sell the market

• When the commodity channel index (CCI) is above 120, sell the market
• When the commodity channel index (CCI) is less than -120, buy the market

• When the market is 10% higher than the 50 EMA, sell the market
• When the market is 10% lower than the 50 EMA, buy the market

• When the VIX is 20% higher than it’s two year average, buy the market

• When 5 year EPS of a stock drops 20% below the average, buy the stock

An example from the course

Mean reversion strategies tend to work better on shorter time frames and are thus ideal for swing traders. In Marwood Research, several mean reversion strategies are revealed such as Bar Strength.

This following idea is designed using a very simple formula that measures the slope between two recent points on a 24 period exponential moving average (EMA). The Amibroker formula for the indicator is as follows:

GRA = EMA(Open,24) / (EMA (Open,24),-1)

The GRA (gradient) formula therefore measures the steepness of the EMA curve.

A buy position is entered whenever GRA drops below 0.98 as this indicates a significantly oversold condition. Whenever GRA moves back past 1.02 the position is closed.

I tested the system on daily data on S&P 500 stocks between 2000 and 2010 and received a compound annual return of 16.73%.


Unsurprisingly, a lot of share market software free downloads are available as free trials for more expensive subscription based products such as charting or back-testing solutions. Some of these may even be white label products.

I’ve come across a handful of decent software downloads in my time and I’ve scoured the Internet looking for the best open source downloads as well as trial products.

Share market software free downloads:

intelicharts share market software free downloadIntelicharts

Intelicharts provides free historical and intraday data for over 20 countries, charting software technical indicators and pattern recognition software.

The key feature from Intelicharts is the predictive software. It uses both time series forecasting and neural networks to predict where the market’s going next.


Statmetrics is a free app for stock traders and investors. It needs Java but will run on most systems. The software has lots of charting methods and can get quite deep in terms of quantitative measures.

Stock Spy

Stock Spy has a cool idea in that it monitors several stocks at a time utilising RSS. It can then suggest possible buys straight to your computer and also send alerts when it might be time to sell. You can’t rely on Stock Spy (some of the news can be unreliable) but it is a great free tool.

jstock share market software free downloadJ Stock

J Stock is a free, open source program that allows you to track your investments with ease. It has charts, technical indicators and data that goes back around 10 years.

You can set up watch-lists over several different countries, track your net worth and follow exchange rates too.


NinjaTrader is an award winning trading and charting platform. I’ve never actually used it but I know a lot of people swear by NinjaTrader. The software can be download for free but for the more advanced features you will have to pay.


ChartNexus is another stock tracker, portfolio manager and charting application. The share market software free download is quick to install and another good feature is the ability to see how others are trading.


Open-source algo trading platform with a robust architecture that allows quantitative trading systems.

Eclipse Trader

Again, I haven’t used Eclipse Trader yet but it promises level II market/depth so that should be worth exploring. It’s an exchange analysis system with news and quotes.

Premium Markets

Another free open-source program, this one allows you to create your own technical indicators and combine more than 100 popular indicators together.

QT Bitcoin Trader

If you are into bitcoins, this free software can be downloaded and connects to some of the main bitcoin exchanges.

More share market software free download resources:

As you can see, a lot of the best free stock market software is open source. Take a look here for more financial open source software from Sourceforge and see this forum post too.

And to see an extensive list of my favourite tools and books make sure to check out the resources page.

All the best.



The Amibroker trading platform is extremely fast, flexible and is excellent value for money. I’ve been using the software since 2011 and my Amibroker AFL collection has grown considerably in that time.

Whether you’re interested in building trading systems, trading long term trends, or simply doing technical analysis, you’ll be able to do that and lots more with Amibroker.

amibroker afl collection postIf you are just starting out, make sure to take a look at all of the tutorials that are available on the Amibroker website and also in the Amibroker Help files.

If you are looking for specific AFL or examples of AFL then read on to see where I go searching.

Best Amibroker AFL Collection

There are several places that I go to look for Amibroker AFL, however, it can be difficult to find well produced codes at a reasonable cost. There are also places you can find free AFL. But as you can imagine, the quality varies a lot when you’re getting something for nothing.

Amibroker Members Area

One of the best resources is the Amibroker AFL library and the Amibroker members area which is available to paid users only. You can find lots of good codes there, some submitted by fellow users and some by Amibroker staff.

Developer of Amibroker, Tomasz Janeczko also regularly codes up trading strategies that have been published in the industry magazine, Technical Analysis For Stocks & Commodities. Some really great ideas can be found by going through the archives:

Amibroker Forum

Another good source for Amibroker code is the Amiboker Yahoo! forum. This forum was in operation for many years although it has now been replaced by a new Discourse forum.

There are plenty of code snippets and examples posted in the Yahoo forum as well as the new forum so those places are always worth a visit. Keep them bookmarked and visit them regularly.

Codes On This Website

If you hadn’t already noticed I also regularly post some ready to use Amibroker codes on this very website. Sometimes I post full AFL codes and other times I just post short snippets.

Following are some examples. If you scroll down the page on each of these posts, you should be able to see the code I have written:

Other Sources

There are also many other websites and places that you can go to pick up some Amibroker AFL. As mentioned, the quality varies so always be careful when implementing any system. But the following places are often a good place to start:

Problems With Free Systems

Unfortunately, as with most free resources, finding the good stuff is like looking for a needle in a haystack. Free Amibroker AFL can often have coding mistakes and compiling errors.

Another problem with any Amibroker AFL collection, is that any trading system you find online is available for anyone to use. Because of this, you’re pretty unlikely to find a system that works well.

However, good trading systems can be found amongst the rubble if you look for long enough, I have found some in the past.

Even if it does contain errors, Amibroker AFL that you find online can always be adjusted, altered and learnt from for your own means.

Don’t Forget The Data

Another important thing to remember when using Amibroker is that a trading system is only as good as the data you’re using.

It is essential to use high quality, clean stock data. Otherwise you will end up with a flawed trading system that will lose money in real trading.

I use Norgate Premium Data and am very happy, especially with the new historical constituents database which comes with the new NDU program. You can get a free trial to demo the service:

Premium AFL

If you are looking for more premium Amibroker AFL, our program Marwood Research contains numerous trading systems and all of the Amibroker formulas are provided.

The trading systems shown on my courses are the best trading systems I’ve found from years of back-testing and research. They are all simple, straightforward systems that can be easily implemented on a daily or weekly basis.

We provide the full Amibroker formulas for all of our strategies so as to remain transparent and help you build trading strategies of your own:

Bonus Trading System AFL

I have also developed a free Amibroker trading system that is a long only, trend following strategy for US stocks.

This particular system is based on very simple rules and made a 56% return in 2013. It is a simple and robust system that can act as a useful template for your future trading strategy. And it can be downloaded for free below:

Howard Bandy’s Books

The only other source I can think of right now if you are looking for Amibroker AFL is to buy one of Howard Bandy’s books. Bandy knows his way around the software like the back of his hand and once you have purchased a book you’ll be able to download the code.

I particularly recommend the books Quantitative Technical Analysis and Mean Reversion Trading Systems. (They are all reasonably priced in my view considering you also get to download the code).

So that’s about all of the places I can think of right now that you can find Amibroker codes. If you have any resources that you know of please leave them in the comments.

Thank You For Reading


afl for amibrokerThe 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.

SetOption (“Maxopenlong”,MOL);
SetOption (“Maxopenshort”,MOS);
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 );
PositionSize= -20/10;

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.

Ranking trades

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.

It’s also a good idea to check out the resources from Amibroker for back-testing and portfolio testing here.