Levels Trading AFL
Now let us have a look at some different types of strategies which can be automated in Amibroker.
We will start with a discretionary strategy. This is a Level based trading strategy to trade on support/resistance levels with SL, TSL and target. You can input the levels for trading at your discretion. The signals generated as per pre-defined levels will be traded automatically.
In this example, I am using 7920 level to trigger Long position. The 7920 could be expected breakout level above a channel. If the Long position is taken, I want Amibroker to put an initial stop loss of 7910. If the market moves in my favor, I want Amibroker to put a trail stop loss of 15 points. Note that initial stop loss is tighter than trail stop loss.
The target set for this trade is 7945, which is based on resistance level.
Also, I want any trades to be triggered only after 9:20 when the market stabilizes. Trades should be entered only upto 3 pm. If there is any trade position at end of day, Amibroker should exit it at 3:15pm.
So, you see, algo trading does not has to be rocket science. It can be extremely simple.
You can make a combination of the best you can do, and the best computer can do.
Even in this simple strategy, you can input parameters only once in the morning. Once the strategy is setup, you can get back to work or your business. Amibroker will automatically generate signals as per the logic. Your broker API will execute trades automatically based on the logic. You can also setup system so that you get automatic email alerts while you are in office. Algo trading can be applied to many situations, and it saves both time and money.
Indicator Based AFL
Now have a look at this 100 % discretion-free strategy based on indicators. It is based on RSI Indicator and also uses position size scalouts.
This strategy takes Long position when RSI shows upward momentum. It takes a short position when RSI shows downward momentum.
When it takes a long position, it sets up both a trail stop loss and a profit target. If the profit target is achieved, 50% of the position will be exited at profit target. The remain 50% of the position will remain in market using the trail stop loss. This concept is basically used to capture long trends using trail stop loss. But at the same time, the strategy secures some profit by booking at the profit target.
Also note, that ATR multiples are used for defining profit target as well as trail stop loss. I am using ATR multiples instead of fixed points or percentage values. Every stock has different volatility. ATR levels help me to adjust automatically to a stock’s volatility. If I use fixed point or % values, the strategy will not be able to dynamically adapt to volatility.
The AFL code of this strategy is less than 100 lines. This AFL uses scaleins and scaleouts which are considered relatively advanced topics. To code scaleins and scaleouts, you should have a very good command on for loops in AFL. To have a good command on for loops, you should have a good understand of arrays and flags.
Also note the difference between AFL and other scripts. What do you think? How many lines of code will be required in Python or MQL to code the same strategy?
Option Trading AFL
This is an AFL code which I will use to test bank nifty options. I have options data for over 13,00 option instruments. Each morning, Amibroker picks up automatically the appropriate strike price. This is done by rounding off the Bank Nifty price at sharp 9:30 to the nearest 100. The AFL then selects the strike price which is at a distance of 200 points from the Bank Nifty future price.
Waiting for the backtest to complete
Take note of this again. Amibroer is able to backtest more than 13000 instruments within 30 seconds. Which other script matches this speed?
Now let us have a look at the AFL code. This is not a very smart AFL code. What I have done, is, that I defined expiry for each month over the backtesting period. Even though AFL is not coded smartly, it takes hardly 100 lines of code.
The smart way to implement this would have been to calculate automatically the last Thursday of each month. And then, AFL should have picked correctly the appropriate near month strike prices.
If I want to trade this strategy live, I do not need to make and significant change in the AFL code. I can just run scanner on all active option strike prices, and AFL code will trigger the trades for me.
Pair Trading AFL
Now have a look at this pair trading strategy.
The graph in top most pane shows Nifty prices. The graph in the middle pane shows bank nifty prices. At the bottom, we have graph which plots statistical arbitrage opportunity between nifty and bank nifty.
Signals are triggered at the same time from the Nifty and Bank nifty to execute a pair trade. You can see the small red and green arrows which indicate trade signals for this pair.
Such multi-leg strategies can also be deployed in Amibroker. This is an example of a 2-leg strategy, but you can also deploy a 3-leg or 4-leg strategy in Amibroker.
The code of this AFL is pretty straight forward. What I have done is, basically, taken standard deviation of the yields of the two instruments. Buy and Sell are triggered based on the spread between the two yields.
Chart Pattern AFL
This is a chart pattern based strategy. The AFL code identifies triangles, channels, double tops and other chart patterns.
A lot of you may have asked, should I chose indicators, or just price action for trading? Which is the best approach in strategy design? Using indicators or price action?
In theory, chart patterns tend to “work better” than indicators. Actually, it also makes intuitive sense. . A chart pattern is formed over several bars of data. So, a quantified chart pattern has greater context with a large number of data points.
Comparatively, indicators are in black & white. An indicator either gives crossover or it doesn’t. Most indicators are one-dimensional and provide very less information. Common indicators, like single-output oscillator indicators, hardly give you any context.
However, this being said, it is very hard to code price patterns. Discretionary traders look at 100s of data points to find a chart pattern or trading pivot. You can see this AFL code. It has more than 300 lines, but hardly anything useful.
That is why I discussed with you earlier a discretionary strategy using buy and sell levels. It is a good practice to leave only that task to computers, which can be done by computers.
Candlestick Patterns AFL
This is a candlestick pattern strategy. It identifies candle patterns, like
And Bullish Engulfing
This AFL suffers from the same problems we discussed about the chart pattern strategy. A half-baked code does not give you anything. If you try to code price patterns without the proper approach, it does not lead you anywhere.
So far we have discussed automation of many strategies. We discussed Discretionary strategy which was also systematic,
100% Automated, Quantitative, Bad examples
Now let us look at another interesting mix- using a discretionary layer on top of indicator based strategy.
This AFL strategy generates buy and sell signals based on an adaptive indicator. However, we have added many discretion inputs. An input value of 0 means that discretion is not being used for that particular input.
First, you can select a level above which it buys. Often stock show bullishness only above a certain level. The strategy takes entry based on custom indicator, but only above a discretionary level.
Similar to the buy above option, we have the Short below option. It means that Short entries can be taken only below a level which signifies bearishness.
Next are the custom Stop and custom Target. Even though strategy has its own exit mechanism based on the indicators, you can also specify custom exit rules. This can be very helpful sometimes. Suppose you are in a Long Trade, and there is a Support level immediately below the entry price. In such situation, you may like to use the custom stop loss, rather than an indicator based stop loss
There is also a mechanism for defensive exit versus an aggressive exit depending on market conditions.
There is an option for intraday mode, which you can turn off, if you want to trade positional.
There are also options for disabling long and disabling short. You can use these options in conjunction with the higher time frame.
Finally, there are inputs for defining trade entry timings and trade exit timings. These are very useful for intraday trading. During the first few minute after market open, you may not want to enter a trade. You can wait till market stabilizes.
Similarly, for intraday trading, it is a good option to define trade exit time also.
Rotational Backtesting AFL
Have a look at this portfolio rotation strategy.
I am running it on a portfolio of about 45 scrips, which are mostly Nifty scrips.
This strategy rotates best and worst performers on an hourly time frame. You can also use same version of strategy on a longer time frame. For example, same strategy can be used for monthly or quarterly rotation of stocks in a portfolio,
On every interval of 60-minute, this strategy finds the best and worst performers. It buys the worst performers and sells the best performers. You can see Amibroker taking positions as per the relative rank of the stock in portfolio.
At 3:15, this strategy liquidates all positions, since it is intraday trading strategy. Next day it will start with a fresh portfolio.
Do you want to see the AFL code for this strategy? Here you go:
It has only 10 lines of AFL code. Only amibroker allows this type of rotational portfolio level backtesting. Other popular retail software, like NinjaTrader, MultiCharts or MT4 do not have this facility.
Exploration Trading AFL
Strategy executed on watchlist of 100 stocks through exploration
Real-time trading does not always need to be done from the charts. It is always possible to trade from Amibroker without using charts at all.
See this example. I have made a watchlist of about 20 stocks to trade. Similarly, you can also create a watch list of 100 stocks to trade.
To trade intraday, I am setting periodicity of 1-minute.’
The range on which Amibroker should scan, is set to only 1 recent bars. Since I am trading using the scanner, I do not need Amibroker to scan every time the entire data history.
Next, I set an Auto Repeat interval of 1-second. This means that Amibroker will scan all the 20 or 100 stocks in the watchlist at an interval of 1-second to find a trading signal.
Now just press the scan button.
Amibroker is now repeating the scan automatically every 1-second to find trade signals. You can see that trades are being triggered in Arvind HDIL.
Trading through scanner is one of the most useful feature. If you are trading through charts, you need to make sure that the charts are open all of the time. You can use the scanner for trading and charts for analysis.
Trading Dashboard AFL
In this example, I have coded an entire trading panel, right on the charts. This trading panel has,
Usual Buy/Sell buttons
Bracket Orders with predefined stop loss and target
Buttons to square-off half the position size
Put TSL and Target buttons
Button to cancel last open order, as well as cancel all open orders
There is also a button to refresh connection with API, useful in case the connectivity to API is lost
Button to set trail stop loss
And lastly an information button which shows the price at which currently orders are being pushed.
The input parameters to this trading panel allow a lot of control on trade execution.
You can choose to trade using Market order or limit order
The limit price for order can be at bid-ask, or a small difference from bid-ask. You can also chose the last price as bid-ask price.
You can pre-define trail stop loss and target in terms of ATR multiples
You can also enable either of email, push or sound alerts
All this being done from Amibroker itself, turning Amibroker into a complete trading terminal.