Create Your Trading Algorithm in 15 Minutes (FREE)

Dec 16, 2020

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:

  1. 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.
  2. Stop loss is 3*ATR from the entry price.
  3. Profit target is 5*ATR from the entry price.
  4. 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.

  1. Click on the text beside Variables to open the above window.
  2. Click on Add new to add each variable.
  3. Check the Config. option, which makes the variable visible when configuring the algorithm during MT4 backtesting. Rename the variables.
  4. Since the lookback period is an integer, set the type to int.
  5. 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.

  1. Click on the right side of the price level field to edit the entry condition.
  2. Click on the ‘Price‘ menu and select ‘High‘.
  3. 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.
  4. 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.

  1. 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.
  2. 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.

  1. Toggle the Stop Loss and click on the input field to edit it.
  2. 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.

  1. Click on Source code at the top of the screen to view your algorithm in several programming languages.
  2. 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.

Powered By

Development Platform

Forex VPS

FXVM Forex VPS

Popular Posts

Laguerre RSI Trend Following Strategy

The Laguerre RSI attempts to improve the responsiveness of the regular RSI, whilst keeping whipsaw trades to a minimum. Let’s see how well it detects short-term pullbacks for a trend following strategy!

read more

What is Fixed Ratio Money Management?

Have you heard of fixed ratio money management? How does it compare to the popular fixed fractional approach? Here I’ll explain how fixed ratio works, and see how it stacks up against fixed fractional money management.

read more

Build a Diversified Portfolio With QuantAnalyzer

The ability to efficiently trade a diversified portfolio of strategies is one of the biggest advantages of algorithmic trading. Here we will use QuantAnalyzer’s Portfolio Master to build a portfolio consisting of high performing, uncorrelated strategies.

read more

What Is the QQE Indicator?

The QQE is a mysterious indicator that sometimes pops up in trading forums. Does it deserve a place alongside the more traditional momentum indicators like the RSI and CCI? Let’s add it to a trend following strategy to find out!

read more

Make your money work for you!

Get promotions, trading ideas and strategy development tips delivered to your inbox!

Comments

1 Comment

  1. elgo strategies

    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.

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Trading Strategies

What’s the Best Time to Trade Forex?

What’s the Best Time to Trade Forex?

The forex markets are open 24/5, but not all hours are created equal. Here I dissect my broker data to determine the best time to trade forex.

Forex Weekend Gaps: Can You Exploit Them?

Forex Weekend Gaps: Can You Exploit Them?

Have you noticed that forex weekend gaps usually reverse within 3 days? Here I’ll program a mean reversion strategy to exploit gaps over the last 18 years!

Money Flow Index: An Improved RSI?

Money Flow Index: An Improved RSI?

The Money Flow Index is sometimes called the volume-weighted RSI. Can it outperform the RSI in this trend following strategy?

Automated Bollinger Bands Squeeze Forex Strategy

Automated Bollinger Bands Squeeze Forex Strategy

StrategyQuant’s BBWR indicator is the perfect tool to detect a Bollinger Bands squeeze. Here I explain how it’s calculated, and use it to program a breakout strategy for the AUDJPY!

Should You Use the Kelly Criterion for Forex Trading?

Should You Use the Kelly Criterion for Forex Trading?

The Kelly criterion is a famous mathematical formula that attempts to maximize your long-term capital growth. In this post, I’ll apply it to a EURUSD breakout strategy and explain some of its potential shortcomings when applied to forex trading.

Can a Trading Pause Improve Your Trend Following Results?

Can a Trading Pause Improve Your Trend Following Results?

A temporary trading pause can improve your win rate if you’re trend following a volatile market. Here I’ll program a trading pause into a simple breakout strategy, and test its effectiveness on the Widow Maker – the GBPJPY.

Laguerre RSI Trend Following Strategy

Laguerre RSI Trend Following Strategy

The Laguerre RSI attempts to improve the responsiveness of the regular RSI, whilst keeping whipsaw trades to a minimum. Let’s see how well it detects short-term pullbacks for a trend following strategy!

How to Use the Supertrend Indicator

How to Use the Supertrend Indicator

Despite its cool name, the Supertrend indicator often seems to slip under the radar. Here I explain how it’s calculated, and combine it with moving averages to produce a simple trend following strategy.

Strategy Development

Do You Know Your System Quality Number?

Do You Know Your System Quality Number?

The System Quality Number measures the profitability & consistency of your trading system. Here’s how to calculate your SQN and use it to improve your trading!

How to Get a Realistic Backtest Spread

How to Get a Realistic Backtest Spread

Your choice of backtest spread can certainly make or break a strategy. This post will show you how to study the intraday spread variations of your market, and suggest several ways to avoid paying ridiculous spreads.

Do You Know Your Strategy’s Optimization Profile?

Do You Know Your Strategy’s Optimization Profile?

Your strategy’s optimization profile often reveals its robustness, helping you select strategies that will remain profitable in live trading. Here I explain why an optimization profile is important, and how you can easily obtain one using StrategyQuant’s optimizer.

Which MT4 Backtest Report Metrics Should You Use?

Which MT4 Backtest Report Metrics Should You Use?

Understanding your backtest report is an essential part of being a successful strategy developer. Here I explain what the numbers mean, and how you can make use of each metric during strategy development.

Out-of-sample Testing Using Monte Carlo Simulations

Out-of-sample Testing Using Monte Carlo Simulations

Traders often use Monte Carlo simulations to estimate worst-case drawdowns, but did you know they can be used for out-of-sample testing too? This post demonstrates the use of StrategyQuant’s Monte Carlo simulator to randomize historical prices and strategy parameters, helping you select robust strategies for live trading.

How Many Trades Should Your Backtest Have?

How Many Trades Should Your Backtest Have?

We all want a large sample of trades in our backtests, but practical limitations such as data availability often get in the way. Here I’ll explain why 30 trades is insufficient, and how you can use standard error to quantify the uncertainty arising from a small sample size.

Build a Diversified Portfolio With QuantAnalyzer

Build a Diversified Portfolio With QuantAnalyzer

The ability to efficiently trade a diversified portfolio of strategies is one of the biggest advantages of algorithmic trading. Here we will use QuantAnalyzer’s Portfolio Master to build a portfolio consisting of high performing, uncorrelated strategies.

Strategy Optimization Using MT4

Strategy Optimization Using MT4

How do you improve your trading strategy in MT4? This post will show you how to optimize the entry and exit parameters for a moving average crossover strategy. Finally, an intraday time filter will be added to help avoid false breakouts.

Debugging & Backtesting Using MT4

Debugging & Backtesting Using MT4

With a fresh algorithm at your fingertips, how do you verify that it has been programmed correctly? This guide will show you how to use Metatrader 4’s visual backtester to debug and backtest your strategy.

What Is Drawdown in Trading?

What Is Drawdown in Trading?

Are you getting a comprehensive assessment of your strategy’s downside? This post will discuss several methods to measure drawdowns, helping you build and select strategies that better suit your risk appetite.

How to Select the Best Trading Strategy Entry

How to Select the Best Trading Strategy Entry

With an abundance of technical indicators available, selecting your strategy’s entry conditions can be overwhelming. This post will illustrate a method to graphically compare the profitability of different entries.

Live Trading

What’s the Best Time to Trade Forex?

What’s the Best Time to Trade Forex?

The forex markets are open 24/5, but not all hours are created equal. Here I dissect my broker data to determine the best time to trade forex.

How to Find a Real Trading Guru

How to Find a Real Trading Guru

Every day I come across a trading guru offering educational content on the internet. Many of them speak of huge returns with minimal effort. Should these be trusted? Here’s some tips on how to separate the wheat from the chaff.

How to Enjoy Stress-Free Trading

How to Enjoy Stress-Free Trading

Trading is a great way to make some additional income, but not if you’re constantly pulling your hair out. Here I offer 7 tips to help make your trading profitable and stress-free.

How to Select the Best Forex VPS

How to Select the Best Forex VPS

A virtual private server (VPS) is a virtual computer that you can rent and access remotely. It provides a reliable platform on which to execute your forex strategies. This post will help you decide whether you need a VPS, and show you how to select an optimal VPS.

Make your money work for you!

Make your money work for you!

 

Get trading ideas and strategy development tips delivered to your inbox!

Thanks for subscribing!

Pin It on Pinterest

Share This