Converting your trading idea into an algorithm is the first step towards reaping the benefits of automated trading. This guide will cover the creation of a simple moving average crossover algorithm using AlgoWizard, without any actual programming.
The complete algorithm can be downloaded here.
Central to your success as a trader is the ability to verify a strategy’s profitability. With countless trading ideas on the horizon, how do you determine which ones have merit?
You could manually trade each strategy and record your results. If you’re a part-time retail trader on the higher timeframes, you’ll probably take a few months to get a decent sample size. But why wait a few months, when you get can the answers in minutes?
By converting your trading idea into a testable algorithm, you can quickly use its historical performance to determine whether its worth your consideration. This is the first of a 3-part guide addressing strategy development using Metatrader 4 (MT4), and will illustrate the process of programming a simple algorithm using AlgoWizard. Part 2 will describe the process of debugging and backtesting the algorithm in MT4, while Part 3 will guide you through the parameter optimization process.
But first, let’s come up with a trading idea.
Developing Your Idea
Let’s have a go at the 30-minute USDJPY. JPY pairs usually trend quite well, so let’s try a simple moving average crossover strategy. Rules will be symmetrical on the long/short sides.
1. Entry Conditions
When the fast moving average crosses over the slow one, it is an indication of upside momentum, and may signal the start of a trend. We will go long when this happens.
Unfortunately, markets do not trend very often, and moving average crossover systems often struggle when the markets move sideways. During such conditions, crossovers occur in rapid succession, producing a string of losing trades.
We can reduce these ‘whipsaw’ trades by implementing a basic breakout filter. We will only go long when the price penetrates the high of the most recently completed candle. A stop (instead of market) order will thus be used for entry, and this order will be valid for 3 bars.
2. Stop Losses
I’m a big fan of using catastrophic stop losses in my strategies. They rarely increase net profit, but they are great for risk control (and a good night’s sleep). Let’s try a simple ATR-based stop loss. Your stop loss distance has to take market noise into consideration, so let’s give the trades some breathing room and place the stop loss 3*ATR from the entry price.
3. Profit Targets
Using profit targets may not be a good idea for trend strategies, since there is no telling how long a trend will last. Lower timeframes tend to contain more noise though; let’s take advantage of the noise and use a 5*ATR profit target. A reward-to-risk ratio that is larger than 1 (5/3 in this case) is crucial for the profitability of trend strategies.
4. Time Stop
Sometimes it’s a good idea to limit your market exposure. A time stop of 150 bars, corresponding to about 3 trading days, will be tested.
To summarize, our strategy’s pseudocode is below:
- If the fast moving average crosses over the slow moving average, place a stop entry order at the high of the previous candle. Order is valid for 3 bars.
- Stop loss is 3*ATR from the entry price.
- Profit target is 5*ATR from the entry price.
- Regardless of trade performance, close the trade after 150 bars have elapsed.
Here’s the strategy in action, shown using MT4’s visual tester.
Programming Your Algorithm in AlgoWizard
Step 1: Get AlgoWizard’s Free Plan
With our trading rules in place, we will now create our algorithm using AlgoWizard. Head over to the AlgoWizard site and sign up for the FREE plan.
Step 2: Input Variables
After completing the signup process, you will arrive AlgoWizard’s user interface.
The Simple Wizard will suffice for our purposes. Before we input the strategy’s logic, let’s look at the Money management and Variables fields at the top right.
During the early stages of strategy development, I prefer to test my algorithms with a fixed lot size. This isolates the compounding effects of variable position sizing. I only apply position sizing later on during portfolio composition. If you instead prefer to implement position sizing here, a few popular options such as fixed fractional sizing are available.
Next, we need to add our indicator variables. Since we will be using a fast and slow moving average, we need to add the lookback periods for each of them.
- Click on the text beside Variables to open the above window.
- Click on Add new to add each variable.
- Check the Config. option, which makes the variable visible when configuring the algorithm during MT4 backtesting. Rename the variables.
- Since the lookback period is an integer, set the type to int.
- Let’s input initial values of 20 and 50 for the fast and slow averages, respectively. We can later change/optimize these values in MT4.
Step 3: Input Entry Type
Head over to the Buy/Sell short boxes. Since we have a breakout filter, we will select stop orders for our entries. Two additional fields will appear: the stop price level and order validity fields.
For longs, the entry price level will be the high of the most recently completed candle. Likewise, the low price will be used for short entries.
- Click on the right side of the price level field to edit the entry condition.
- Click on the ‘Price‘ menu and select ‘High‘.
- A shift of 1 means the most recently completed candle will be evaluated. The candle immediately prior has a shift of 2, and so on.
- Finally, set the order validity at 3 bars.
Step 4: Input Entry Conditions
AlgoWizard has numerous options for entry conditions, including price action, indicators, candlestick patterns, and signals. Signals are predefined combinations of indicators and/or price action conditions. Click Add new entry conditions and the following dialog will appear.
- Select the Indicators menu and the Simple Moving Average option. By default, the average will be computed from the closing prices, and the shift will be 1.
- At the Period field, select the Fast_Period variable added earlier.
After selecting Confirm, click on the default ‘>‘ symbol back in the main window to input the Cross Above condition.
Finally, click on the right side of the entry condition field to input the slowing moving average. The procedure is similar to that for the fast moving average, except that the Period should be Slow_Period this time. Our entry conditions are complete. You should now have the following:
Step 5: Input Exit Conditions
Here we’ll input the stop loss, profit target and time stop.
- Toggle the Stop Loss and click on the input field to edit it.
- Select the ATR-based option and enter the ATR multiple and lookback period. Like the moving averages above, you can use a configurable variable for the ATR lookback, but we’ll stick to the default 14-period lookback here.
If you opt to use the Full Wizard instead of the Simple Wizard, you can input custom formulae for your stop loss/take profit levels.
Repeat the above for the profit target, except that we will use 5*ATR instead. Finally, activate the time stop and input 150 bars.
Notice that we haven’t input conditions for short trades. If you check the ‘Short is symmetric to long‘ option, the logic for the strategy’s short side will be automatically generated.
That’s it! You now have a fully-functioning algorithm!
Exporting Your Algorithm to MT4
AlgoWizard’s free plan lets you run backtests using only one year of historical data. A short backtest period is unlikely to cover enough market conditions, nor will it produce sufficient trades. Let’s export the algorithm to MT4 and run the backtests there instead.
- Click on Source code at the top of the screen to view your algorithm in several programming languages.
- Since we will backtest in MT4, change the Source code type to Expert Advisor for MetaTrader4. You can also view your algorithm in Pseudocode. This is a great way to verify your algorithm’s logic.
If you trade on other platforms such as Tradestation, MultiCharts or JForex, you can export your algorithm in EasyLanguage or Java.
At the right of the screen, click on Parameter variables and choose Recommended parameters. This ensures that only meaningful parameters, such as the moving average lookback periods and ATR multiples, will be optimizable when opening the algorithm in MT4. To minimize the risk of curve fitting, trivial parameters are best left unoptimized.
Finally, click on Save to file (beside step 2 above) to download the algorithm! Alternatively, you can download the complete algorithm (in .mq4 format) here. If you’re using Chrome, right click and ‘Save link as’.
Wrapping Up
We have used AlgoWizard’s Free plan to create a simple algorithm that is ready for MT4 backtesting. With its intuitive user interface, you can now quickly create strategies without any programming knowledge.
Feel free to use the Full Wizard option (top right of your screen) if you’d like more flexibility in configuring your trading logic. The Pro version of AlgoWizard allows you to backtest at 1-minute precision using up to 17 years of data. You can access these at only $14/month.
For a 20% discount off AlgoWizard Pro, use coupon TACT-AW at checkout here! If you make a purchase, I may get a small commission, at no additional cost to you.
In Part 2, we will backtest this strategy in MT4 to determine whether it’s up to snuff.
Hey There. I discovered your blog using msn. That is a very well written article.
I’ll be sure to bookmark it and return to learn more of your useful info.
Thank you for the post. I’ll definitely comeback.