Automated trading Range Breakout

Getting Started with Automated Trading: Building a Range Breakout Strategy in MetaTrader 5

Imagine creating a system that quietly works behind the scenes, catching market movements while you go about your day.

Are you ready to take the plunge into the exciting world of automated trading? Imagine creating a system that quietly works behind the scenes, catching market movements while you go about your day. Today, we’ll dive into building a script that trades for you—catching price breakouts in the early hours, then managing your risk with stop-losses, and closing your trades by the end of the trading day.

We’ll go step by step through how to write a range breakout strategy in MetaTrader 5 (MT5) using MQL5. The strategy involves placing buy stop and sell stop orders early in the day and letting the market decide which direction it wants to break out. The safety net? A stop-loss to limit potential losses if the market turns against you.

But first, let’s set up your environment.


Step 1: Download MetaTrader 5 from IC Markets

Before we jump into the code, let’s make sure you’ve got all the tools in place. IC Markets is a popular broker offering MetaTrader 5 with tight spreads, making it ideal for automated trading. Here’s how to get everything up and running:

  1. Go to the IC Markets Website: Head over to IC Markets and create a free demo account if you haven’t already.
  2. Download MetaTrader 5: Once you’re logged in, navigate to their Downloads section and download the MetaTrader 5 (MT5) platform.
  3. Install and Log In: Follow the prompts to install MT5 on your computer and log in with the credentials provided by IC Markets.
  4. When MetaTrader has loaded, click on:
Automated trading click on IDE

Great, now that MetaTrader 5 is ready, let’s get into the coding!


Step 2: The Range Breakout Strategy Explained

Before we start coding, let’s briefly explain what this range breakout strategy is all about.

This strategy places buy stop and sell stop orders early in the trading day, hoping that as the price moves during the day, it will break out in one direction (either up or down). Here’s how it works:

  1. Early Setup: At the start of the day, we place a buy stop order above the current price and a sell stop order below the current price.
  2. Breakout: As the day progresses, if the price breaks above the buy stop level, a buy order is triggered, or if it drops below the sell stop level, a sell order is triggered.
  3. Stop-Loss Protection: To limit risk, we place a stop-loss order so that if the price reverses, the trade is closed automatically to minimize losses.
  4. End of Day Close: By a specific time in the day (let’s say late afternoon), we close all open positions regardless of profit or loss, ready to start again the next day.

To visualize this strategy, here’s a simple diagram:


Range Breakout Diagram:

Imagine this chart represents a trading day:

At the beginning of the day, the price is moving within a range (between the two dashed lines). You set a buy stop just above the range and a sell stop just below it. The price can break out in either direction during the day. When it does, the relevant order (buy or sell) is triggered, and with the help of a stop-loss, your risk is managed.

Now, let’s start coding!


Step 3: Writing the MetaTrader Script

Open MetaEditor (included with MetaTrader) and create a new Expert Advisor (EA). Name it ConfigurableRangeBreakout.mq5.

Below is the step-by-step guide to writing the EA code. Follow along carefully, and by the end, you’ll have a functional strategy catching breakouts!

Step 4: Script Setup

The first step is to include some basic details and a few settings for our Expert Advisor.

cppCopy code//+------------------------------------------------------------------+
//|                                    ConfigurableRangeBreakout.mq5 |
//|                                                                  |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Your Name"
#property link      "http://www.yourwebsite.com"
#property version   "1.11"
#property strict

#include <Trade\Trade.mqh>

This section defines the EA name and loads the necessary trading library so we can place orders.

Step 5: Defining the Input Parameters

Next, we define some parameters that will control how our EA behaves. These parameters allow us to configure when to place the orders, the size of the orders, and the stop-loss.

cppCopy code// Input parameters
input int BuyFromHour = 1;     // Start hour to set buy/sell stops (0-23)
input int BuyFromMinute = 0;   // Start minute to set buy/sell stops (0-59)
input int BuyToHour = 5;       // End hour to set buy/sell stops (0-23)
input int BuyToMinute = 0;     // End minute to set buy/sell stops (0-59)
input int SellHour = 13;       // Hour to close all positions (0-23)
input int SellMinute = 0;      // Minute to close all positions (0-59)
input double RangePercent = 0.5; // Range size as percentage of current price
input double LotSize = 0.01;   // Fixed lot size for orders
input int StopLossType = 0;    // 0 for percentage-based, 1 for pip-based
input double StopLossValue = 1.0; // Stop Loss value (percentage or pips)

These inputs allow you to control the exact time when buy and sell stops are placed, and they also allow you to adjust the lot size and stop-loss settings.

Step 6: Initialization and Timer Setup

Next, we initialize the EA and set up a timer to ensure the program checks the market regularly.

cppCopy codeint OnInit()
{
   Print("EA initialized. BuyFrom: ", BuyFromHour, ":", BuyFromMinute, 
         ", BuyTo: ", BuyToHour, ":", BuyToMinute, 
         ", Sell: ", SellHour, ":", SellMinute);
   
   // Set up a timer to check every minute
   EventSetTimer(60);
   
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   EventKillTimer();
}

This code runs when the EA is first loaded onto a chart, printing out the key parameters and setting a timer to check every minute.

Step 7: Monitoring the Market (OnTick Function)

The OnTick function is triggered every time the price changes. It will decide whether it’s time to place a new buy or sell stop order.

cppCopy codevoid OnTick()
{
   datetime currentTime = TimeCurrent();
   MqlDateTime str_time;
   TimeToStruct(currentTime, str_time);
   
   // Check if it's time to set new levels
   if((str_time.hour > BuyFromHour || (str_time.hour == BuyFromHour && str_time.min >= BuyFromMinute)) &&
      (str_time.hour < BuyToHour || (str_time.hour == BuyToHour && str_time.min <= BuyToMinute)) &&
      !g_LevelsSet)
   {
      SetNewLevels();
   }
   
   CheckCloseConditions();
}

Here, we determine the correct time for placing buy and sell stop orders and ensure everything runs smoothly by checking every minute.

Step 8: Placing the Orders

Now we move on to the function that actually places the buy and sell stop orders at the right levels:

cppCopy codevoid SetNewLevels()
{
   double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double range = currentPrice * RangePercent / 100;
   double stopLoss;
   
   if(StopLossType == 0) // Percentage-based
   {
      stopLoss = currentPrice * StopLossValue / 100;
   }
   else // Pip-based
   {
      stopLoss = StopLossValue * SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   }
   
   g_BuyStopPrice = NormalizeDouble(currentPrice + range, _Digits);
   g_SellStopPrice = NormalizeDouble(currentPrice - range, _Digits);
   
   double buyStopLoss = NormalizeDouble(g_BuyStopPrice - stopLoss, _Digits);
   double sellStopLoss = NormalizeDouble(g_SellStopPrice + stopLoss, _Digits);
   
   // Place buy stop order
   if(trade.BuyStop(LotSize, g_BuyStopPrice, _Symbol, buyStopLoss))
   {
      g_BuyStopTicket = trade.ResultOrder();
      Print("Buy Stop order placed: ", g_BuyStopTicket);
   }
   
   // Place sell stop order
   if(trade.SellStop(LotSize, g_SellStopPrice, _Symbol, sellStopLoss))
   {
      g_SellStopTicket = trade.ResultOrder();
      Print("Sell Stop order placed: ", g_SellStopTicket);
   }
   
   g_LevelsSet = true;
   g_LastActionTime = TimeCurrent();
}

This is where the magic happens. We calculate the stop-losses, place the orders, and record them for later management.

Final Step: Closing the Orders

To complete the strategy, we need to close all positions by a specific time. Here’s how we manage that:

cppCopy codevoid CheckCloseConditions()
{
   datetime currentTime = TimeCurrent();
   MqlDateTime str_time;
   TimeToStruct(currentTime, str_time);
   
   datetime sellTime = StringToTime(StringFormat("%04d.%02d.%02d %02d:%02d:00", 
                                    str_time.year, str_time.mon, str_time.day, 
                                    SellHour, SellMinute));
   
   if(currentTime >= sellTime)
   {
      CloseAllPositions();
   }
}

This function monitors the time and ensures that all open positions are closed at the specified time, no matter what the outcome of the trades has been.


Wrapping It Up

Congratulations! You’ve just built a range breakout strategy from scratch. This strategy automatically sets buy and sell stop orders early in the day, manages risk with a stop-loss, and closes positions by the end of the trading session.

Here is the performance over 2 years. However let me disclaim right here that you might not be able to repeat the same performance, due to other commission structure, software and trading platforms you might have.

Automated trading can feel like having a team of tireless robots working for you around the clock. Test this strategy on a demo account, and tweak the parameters to suit your trading style.

Attribution

Rene Balke came up with the idea of this breakout strategy, to buy at a specified time, sell at a later time with no other indicators than just a stoploss to protect capital.

Mark Cannon
Mark Cannon
Articles: 318