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 talk about two high quality courses where you can learn how to use the immensely powerful trading simulator Amibroker.

* If you intend to take either of the two courses below (or both), use the discount code ‘Marwood’ at checkout to receive 15% off the usual price. *


Regular readers of this blog will know that my back testing and trading software of choice is Amibroker. It is an incredibly quick and flexible platform, easy to use and comes with awesome support. In fact, when you purchase Amibroker you are entitled to 24 months support from the developers – something that I’ve really benefitted from.

Regular readers will also know that every now and then I talk about a product or two that I believe is worthy of recommendation. And sometimes I earn a small commission from doing that and sometimes I don’t. The main point being that I never recommend a product that is a scam or offers little value to my readers.

Learn Amibroker at Trading Markets

Now, as I said already, Amibroker is my favourite tool for analysing the markets and I have found it superior to the vast majority of much more expensive programs.

However, Amibroker is still just a tool. It is immensely powerful but only if you are able to learn Amibroker in the right way.

Previously, in order to learn Amibroker, Amibroker users have had to pretty much teach themselves. When I was learning the program, I basically had to make do with Amibroker forums and Dr. Howard Bandy’s books (which isn’t to criticise any of those because they are excellent).

It just would have been a lot easier and quicker if there had been some way to sit down and learn everything in one go.

And that’s why these 2 new courses from TradingMarkets.com are so valuable. They allow beginners to learn Amibroker from the ground up, doing it the right way.

Right now, there are couple of places still available I believe, which will have you fully up to speed, ready to build high performing trading strategies in just a couple of days.

About TradingMarkets.com

Before I go into more detail about the two courses it’s worth saying a word or two about TradingMarkets.com because they’ve been involved in the financial markets for quite a while. In fact, TradingMarkets were founded back in 1999 by Larry Connors and Kevin Haggerty, and if you think you’ve heard those names somewhere before it’s probably because you have:

Larry is the author of a number of bestselling finance books including Short Term Trading Strategies That Work, High Probability ETF Trading and Trading Stocks and Options With Moving Averages. He’s also famous for developing the ConnorsRSI technical indicator and is regularly featured on CNBC and Bloomberg TV.

learn amibroker trading markets teamTrading Markets TeamWhilst Kevin was a former head of trading at Fidelity Capital Markets in Boston where he was responsible for all U.S. institutional Listed, OTC and Options trading. It’s fair to say that the team at TradingMarkets have a wealth of knowledge at their disposal, and in Matt Radke, they also have a teacher with a huge amount of technical experience.

Introducing Programming in Amibroker – Learn How to Backtest Your Best Trading Ideas in One Day

The first course from TradingMarkets, taught by Matt Radke, starts on the 5th June and is your introduction to using Amibroker. It’s taught over the course of one day and consists of 6 hours of interactive online learning. It includes the ability to talk with Matt directly, download a number of AFL code templates and involves several hands-on sessions where you can get to grip with the software.

During the course you’ll learn:

• How to import data correctly
• How to use the automatic analysis window
• How to code in AFL (Amibroker Formula Language)
• How to scan
• How to run an exploration
• How to code and add custom indicators
• How to perform back tests

You also receive free:
Quantitative Trading Systems by Dr Howard Bandy (book).

What else?

The best thing about this course (and the one below) is that they are taught by experts in Amibroker. Connors Research and Trading Markets use Amibroker daily to build their own high performance trading strategies so they know exactly what it takes to teach others.

The introduction to Amibroker will leave you with real confidence in your ability to program indicators, run scans and create profitable trading systems. At $1000, it’s not cheap, but it’s not that expensive either. Especially when you consider the potential rewards from running your own systems.
For more information about the course, and to book your place, click on the banner below and you’ll be taken through to the course booking page.
Learn Amibroker Introduction to Amibroker course

Advanced Amibroker Coding – 2 day course

If you are already fairly experienced in Amibroker, or if you have taken the Introduction to Amibroker course, and you want to advance your knowledge to expert level then the 2 day course of Advanced Amibroker Coding is going to be your best bet to learn Amibroker.

This course runs over two days and covers everything you will need to run your high grade strategies and harness the full working power of Amibroker.

Specifically, you’ll learn how to use the often misunderstood Custom Backtester (CBT) interface which will allow you to create complex backtests, optimizations and portfolio simulations.

During the course you’ll learn:

• When to use the three levels of Custom Backtester (CBT)
• How to add custom metrics to the CBT
• How to utilise multiple time frames
• How to design for a portfolio
• How to perform optimisations correctly

In addition you’ll learn:

• Advanced functions such as LOOP, LOOKUP & _TRACE()
• Using the Switch function
• TimeFrame Compress/Expand and Set/Restore
• Scaling and position size array
• High level and low level CBT
• How to implement a portfolio test

As well as this, the course goes over the mistakes traders make when designing systems and how to best avoid them. By the end you should be able to produce historical results for a system that mimics exactly the way you want to trade and thereby gain insight into how the system will stand up in the future.

The course, again, is taught by experienced Amibroker programmer Matt Radtke and is an intensive, hands-on couple of days with lots of examples and exercises. As I said before, if this was around when I was first learning Amibroker I would have snapped it up, it probably would have saved me several years of trial and error learning.

For more information, check out the full Amibroker courses below:

Remember to use the code ‘MARWOOD’ to get a 15% discount at checkout.



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:

SetTradeDelays(1,1,1,1);
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.

Conclusion

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.

See how these 15 experts trade the markets using a variety of strategies.

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.

By the way, you can find lots more useful information about trading systems, including the tools and books I use to help build them in the Resources tab.

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 my book and course, I cover more than 30 trading systems, both mean reversion and trend following.

This one 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%, with a maximum drawdown of -47% and 59% winner ratio.

Here is the equity curve:

GRA mean reversion trading systems



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

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

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

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.

Algo-trader

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.

 


 


My trading courses now come with complete Amibroker system code for over 20 strategies. Check them out here.

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

Whether you’re interested in building trading systems, trading long term trends, investing in blue-chip companies, or picking penny stocks, you’ll be able to do that and lots more with Amibroker.

amibroker afl collection postIf you are just starting out with AFL, make sure to take a look at the user manuals on the Amibroker site and the post I did about writing AFL for Amibroker.

Best Amibroker AFL Collection

There are two places I go to look for free Amibroker AFL. One is the Amibroker online library and the other is the Yahoo Amibroker forum.

I recently came across this collection of 129 Amibroker systems too. I haven’t delved into it too deeply yet but the systems look simple and easy to use.

These are all great places to start learning about Amibroker but as with most sources of free material some hunting is often required in order to get to the good stuff.

The other 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 one that works, or at least works well. Nevertheless, 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 the services at Norgate Premium Data and am very happy, especially with the new historical constituents database which comes with the Alpha program. You can get a free trial of the service here.

AFL in my courses

If you are looking for Amibroker AFL, my courses contain a collection of over 20 trading systems, some trend following and some mean reverting. These are tested on at least ten years of historical stock data, and in the case of my new Trend Following For Stocks course, the system and code has been back-tested over 30 years.

The trading systems shown on my courses are the best trading systems I’ve found from years of back-testing and research. They produce returns ranging from 13% CAR (compound annual return) to over 50% CAR. And they are all simple, straightforward systems that can be easily implemented on a daily or weekly basis.

Trading the Noise AFL

For example, trading system 4 in my HTBWS course is called ‘Trading the Noise Plus Shorts’. It uses a very simple indicator to measure the level of noise in a stock in order to determine when it is trending. It returned  23.93% CAR over 10 years and had only one down year which was 2002. You can get the free Amibroker AFL for the strategy here.

Amibroker Afl collection noise

RSI with the VIX AFL

Likewise, trading system 15, is called ‘RSI with the Vix’ and returned 25.73% in backtesting. It uses a simple trend following strategy using the RSI indicator and the VIX volatility index as a filter. Get the free Code Here

Amibroker AFL Collection RSI

Cherry Picking Penny Stocks

Trading system 18, called ‘Cherry Picking Penny Stocks’, delivers 30.45% CAR over 10 years of stock market data and has a maximum system drawdown of -30.18%. The system picks penny stocks that are moving in strong upward trends using a filter based on the ATR (average true range function). It also has a price filter though to avoid the really illiquid penny stocks.

Amibroker afl collection cherry

And these trading systems are also mentioned in my book which is available on Amazon. The book, however, does not include any of the new strategies that I have since added to the courses. Such as Trend Following For Stocks, Market Timing with the VIX and the Unusual Volume system.



afl for amibrokerThe best resources for Amibroker AFL can be found via the Amibroker AFL library or one of the Amibroker yahoo 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 code for 20 trading systems written in AFL with every purchase of my book or course and will be posting plenty of free AFL code here in the future 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;
SetOption(“Maxopenpositions”,numberpositions);
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.