Average Daily Range

Author: Copyright � 2007, GwadaTradeBoy Corp.
Profit factor:
0.44

Here's a breakdown of what this MetaTrader script does, explained in simple terms for someone who doesn't code:

This script is designed to automatically trade on the Forex market based on a specific strategy called "Average Daily Range" or ADR. It essentially looks at how much the price of a currency pair has moved, on average, over the last 14 days and uses that information to decide when and how to place buy and sell orders.

Here's the sequence of events:

  1. Initialization: When the script starts, it gathers basic information. This includes things like the minimum trade size allowed by the broker, the account balance, and the pip value (which is how much a small price movement affects your profit/loss).

  2. Time Check: It checks if the current time matches a specific hour and minute (5 PM EST), using a time zone configuration. The script adjusts for different time zones to ensure it's running at the intended time relative to the market.

  3. Closing and Canceling: At the pre-defined time, the script first closes any existing open trades and cancels any pending orders that are associated with this specific script and currency pair. This is like clearing the deck before starting a new trading cycle.

  4. ADR Calculation: It calculates the Average Daily Range. It looks back at the daily high and low prices for the last 14 days, determines the difference between the high and low for each day (the daily range), adds up all those ranges, and then divides by 14 to get the average. This tells the script how volatile the currency pair has been recently.

  5. Determining Profit and Stop Loss: Based on the calculated ADR, the script decides on the size of potential profit and acceptable loss per trade:

    • If the ADR is very low (below 100 pips), the script does nothing.
    • If the ADR is between certain values (100-174, 175-199, 200+), the script sets different profit targets and stop-loss levels. Higher ADR values usually mean higher potential profit but also higher risk, so the script adjusts the profit and loss targets accordingly.
  6. Setting Entry Orders: Based on the previous day's high and low, the script calculates where to place "buy stop" and "sell stop" orders. A buy stop order is an order to buy the currency if the price goes above the previous day's high (plus a small buffer of 1 pip). A sell stop order is the opposite: an order to sell the currency if the price goes below the previous day's low (minus a small buffer of 1 pip).

  7. Placing Orders: The script then places these buy stop and sell stop orders with the broker. It specifies the volume (lot size) for each trade (calculated automatically), the entry price, the stop-loss price (the price at which the trade will automatically close to limit losses), and the take-profit price (the price at which the trade will automatically close to secure profits).

In essence, the script follows this logic:

  • At a specific time, clear existing trades and orders.
  • Calculate how much the currency pair has been moving recently (ADR).
  • If the movement is sufficient (ADR is high enough), place pending buy and sell orders based on the previous day's price range, with profit and loss targets determined by the ADR.
Price Data Components
Series array that contains the highest prices of each barSeries array that contains the lowest prices of each bar
Orders Execution
Checks for the total of open ordersIt Closes Orders by itself It automatically opens orders when conditions are reached
22 Views
0 Downloads
1 Favorites
Average Daily Range
//+------------------------------------------------------------------+
//|                                          Average Daily Range.mq4 |
//|                            Copyright © 2007, GwadaTradeBoy Corp. |
//|                                            racooni_1975@yahoo.fr |
//+------------------------------------------------------------------+
//|                                           AKA : Deepender Natak  |
//|                                         deependernatak@gmail.com |
//+------------------------------------------------------------------+
//|                                       Corrected by Ronald Verwer |
//|                  of Forex MetaSoft; the home of custom build EAs |
//|                                     http://www.forexmetasoft.com |
//+------------------------------------------------------------------+
//| At 5PM EST: 
//| 1- Close out any open positions 
//| 2- Cancel any unexecuted orders 
//| 3- Set an Entry Buy order 1 pip above previous high 
//| 4- Set an Entry Sell order 1 pip below previous low 
//| 5- Set stops and limits using the following guidelines: 
//| 
//| 50 pip profit target, 25  pip stoploss if ADR ABOVE 200 
//| 40 pip profit target, 20 stoploss if ADR BETWEEN 175 and 199 
//| 30 pip profit target, 15  stoploss if ADR BELOW 175 
//| 
//| Do no trade if ADR is below 100 
//| 
//| How to calculate ADR (Average Daily Range)
//| It may be easiest to use an excel spread sheet for this.
//| Take the H/L for each day, for the past 14 days.
//| For each day list the amount of pip's between the H and L
//| Example. H = 1.5623    L = 1.5586
//| 5623 - 5486 =  137
//| Add the total amount of pip's for all 14 days and divide it by 14.
//| This will give you the average daily range
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, GwadaTradeBoy Corp."
#property link      "racooni_1975@yahoo.fr"

//---- Include
#include <stderror.mqh>
#include <stdlib.mqh>

//---- Money Management
//extern bool    MoneyManagement   = False;
//extern bool    StrictManagement  = False;
//extern bool    AcountIsMini      = False;
//extern int     TradePercent      = 1;
//extern int     SumTradePercent   = 10;
double         Margin, PF, PipValue, SumTrade, LotSize, Balance;
bool           TradeAllowed      = False;
bool           Allowed           = False;
int            StopLossValue;

//---- Optimisation des Lots
//extern double  Lots              = 0.1;
extern double  PercentPerTrade   = 2;
extern double  DecreaseFactor    = 3;
double         Lots, lot;
int            orders, losses, Spread;

//----- Identification
extern int     MagicEA           = 210507;
extern string  NameEA            = "Average Daily Range";

//---- Strategie
extern int     ADR_Preriod       = 14;
extern bool    UseGMT            = False; //à voir, devrait etre automatique
extern int     BrokerTZ          = 2;
extern int     USAGMTEST         = 2;
extern int     CloseHour         = 17;
extern int     CloseMinute       = 0;
//extern string  OpenTime = "10:00-10:05; 12:20-12:31; 13:40-13:55";

//---- Variables
int            cnt, ticket, total, i, j;
double         SumAV;
int            ADR, TakeProfit, StopLoss;
double         PriceBuy, StopLossBuy, TakeProfitBuy, PriceSell, StopLossSell, TakeProfitSell;
datetime       BrokerTime, GMT, GMTEST;
int            Years, Months, Days, Hours, Minutes, Secondes;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
   {
//---- Optimisation des Lots
      Spread = MarketInfo(Symbol(),MODE_SPREAD);
      Lots = MarketInfo(Symbol(),MODE_MINLOT);
//---- Money Management
      Margin = AccountMargin();
      Balance = AccountBalance();
      PipValue = MarketInfo(Symbol(),MODE_TICKVALUE);
      LotSize = MarketInfo(Symbol(),MODE_LOTSIZE);
//----
      return(0);
   }

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
   {
//----
   
//----
      return(0);
   }

//+------------------------------------------------------------------+
//| Calculs preliminaires de l'expert                                |
//+------------------------------------------------------------------+
//******* Calcul de la posibilité de trade en fonction du MM *******//
/*
bool MMTradeAllowed()
   {
   if (StrictManagement)
      {
      PF = (Balance - Margin);
      SumTrade = (Balance * SumTradePercent * 0.01);
      StopLossValue = ((PF  * TradePercent * 0.01) / PipValue);
      Lots = ((PF * TradePercent * 0.01) / LotSize);
      if (Margin < SumTrade)
         return(True);
      else
         return(False);
      }
   else
      {
      if((AccountEquity() > ( PF + (SumTradePercent * 0.01 * PF)))
         || ( AccountBalance() - AccountEquity() > (TradePercent * 0.01 * PF)))
         return(True);
      else
         return(False);
      }   
   }
*/
//************** Calcul de la taille optimale du lot ***************//

double LotsOptimized()
   {
   lot = Lots;
   orders = HistoryTotal();     // Historique des ordres
   losses = 0;                  // Nombre de trade perdants consécutif
// Selection de la taille du lot //
   lot = NormalizeDouble((AccountFreeMargin()* PercentPerTrade * 0.01)/1000,1);
// Calcul du nombre de perte consecutive //
   if(DecreaseFactor>0)
      {
      for(i = orders - 1; i >= 0; i--)
         {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==False) 
            { 
            Print("Erreur dans l\'historique!"); 
            break; 
            }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
//----
         if(OrderProfit()>0) 
            break;
         if(OrderProfit()<0) 
            losses++;
         if(losses>1) 
            lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
         }
// Retour de la taille du lot //
      if(lot < Lots) 
         lot = Lots;
//----
      }
   return(lot);
   }

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
   {

//----

//---- GMT Calculation
   BrokerTime = TimeCurrent();
   GMT = BrokerTime - (BrokerTZ)*3600;
   GMTEST = GMT + (USAGMTEST)*3600;
//---- Test UseGMT
   //if (UseGMT)
   //{
   Years = TimeYear(GMTEST);
   Months = TimeMonth(GMTEST);
   Days = TimeDay(GMTEST);
   Hours = TimeHour(GMTEST);
   Minutes = TimeMinute(GMTEST);
   Secondes = TimeSeconds(GMTEST);
   //}
//---- Test de l'heure
   if(Hours == 17 && Minutes == 0)
      {
      for(j = 0; j < OrdersTotal(); j++)
         {
         OrderSelect(j,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()== Symbol() && OrderMagicNumber()== MagicEA)
            {
            //Mnemonic :
            //OrderClose( int ticket, double lots, double price, int slippage, color Color=CLR_NONE)
            if(OrderType()==OP_BUY)
               OrderClose(OrderTicket(),OrderLots(),Bid,5,Violet);
            if(OrderType()==OP_SELL) 
               OrderClose(OrderTicket(),OrderLots(),Ask,5,Violet);
            if(OrderType()>OP_SELL) //pending orders
               OrderDelete(OrderTicket());
            }
         }
//---- ADR Calculation
      for(i = 0; i <= ADR_Preriod; i++)
         {
         SumAV = SumAV + (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i));
         }
      ADR = (SumAV / ADR_Preriod) / Point;
//---- akeProfit en fonction de l'ADR
      if (ADR < 100)
         return(0);
      if (ADR >= 100 && ADR < 175)
         {
         TakeProfit = 30;
         StopLoss = TakeProfit / 2;
         }
      if (ADR >= 175 && ADR < 199)
         {
         TakeProfit = 40;
         StopLoss = TakeProfit / 2;
         }
      if (ADR >= 200)
         {
         TakeProfit = 50;
         StopLoss = TakeProfit / 2;
         }
//---- Calcul des Variables de passage d'ordre
      PriceBuy = (iHigh(NULL,PERIOD_D1,1) + (1 * Point));
      StopLossBuy = PriceBuy - StopLoss * Point;
      TakeProfitBuy = PriceBuy + TakeProfit * Point;
      PriceSell = (iLow(NULL,PERIOD_D1,1) - (1 * Point));
      StopLossSell = PriceSell + StopLoss * Point;
      TakeProfitSell = PriceSell - TakeProfit * Point;
            // Mnemonic :
            //OrderSend( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)
//---- BUY Order
      ticket=OrderSend(NameEA,OP_BUYSTOP, LotsOptimized(), PriceBuy, 3, StopLossBuy, TakeProfitBuy, NameEA + " BUY " + Symbol(), MagicEA, 0, Green);
      if(ticket < 0)
         {
         Print("OrderSend failed with error #",GetLastError());
         }
//---- SELL Order
      ticket=OrderSend(Symbol(),OP_SELLSTOP, LotsOptimized(), PriceSell, 3, StopLossSell, TakeProfitSell, NameEA + " SELL " + Symbol(), MagicEA, 0, Red);
      if(ticket < 0)
         {
         Print("OrderSend failed with error #",GetLastError());
         }
//----
      }
   return(0);
   }
//+------------------------------------------------------------------+

Profitability Reports

GBP/CAD Jul 2025 - Sep 2025
0.00
Total Trades 26
Won Trades 0
Lost trades 26
Win Rate 0.00 %
Expected payoff -0.53
Gross Profit 0.00
Gross Loss -13.77
Total Net Profit -13.77
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.01
Total Trades 95
Won Trades 1
Lost trades 94
Win Rate 1.05 %
Expected payoff -0.43
Gross Profit 0.33
Gross Loss -40.75
Total Net Profit -40.42
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
1.34
Total Trades 30
Won Trades 9
Lost trades 21
Win Rate 30.00 %
Expected payoff 0.47
Gross Profit 56.50
Gross Loss -42.27
Total Net Profit 14.23
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.99
Total Trades 84
Won Trades 4
Lost trades 80
Win Rate 4.76 %
Expected payoff 0.00
Gross Profit 30.50
Gross Loss -30.73
Total Net Profit -0.23
-100%
-50%
0%
50%
100%
USD/JPY Jan 2025 - Jul 2025
1.89
Total Trades 49
Won Trades 22
Lost trades 27
Win Rate 44.90 %
Expected payoff 1.18
Gross Profit 123.12
Gross Loss -65.12
Total Net Profit 58.00
-100%
-50%
0%
50%
100%
USD/CHF Jan 2025 - Jul 2025
0.02
Total Trades 59
Won Trades 2
Lost trades 57
Win Rate 3.39 %
Expected payoff -0.88
Gross Profit 1.22
Gross Loss -53.07
Total Net Profit -51.85
-100%
-50%
0%
50%
100%
USD/CAD Jan 2025 - Jul 2025
0.03
Total Trades 40
Won Trades 5
Lost trades 35
Win Rate 12.50 %
Expected payoff -1.29
Gross Profit 1.77
Gross Loss -53.17
Total Net Profit -51.40
-100%
-50%
0%
50%
100%
NZD/USD Jan 2025 - Jul 2025
0.03
Total Trades 35
Won Trades 2
Lost trades 33
Win Rate 5.71 %
Expected payoff -0.88
Gross Profit 1.00
Gross Loss -31.75
Total Net Profit -30.75
-100%
-50%
0%
50%
100%
GBP/USD Jan 2025 - Jul 2025
0.01
Total Trades 44
Won Trades 1
Lost trades 43
Win Rate 2.27 %
Expected payoff -0.85
Gross Profit 0.50
Gross Loss -38.09
Total Net Profit -37.59
-100%
-50%
0%
50%
100%
GBP/CAD Jan 2025 - Jul 2025
0.00
Total Trades 49
Won Trades 0
Lost trades 49
Win Rate 0.00 %
Expected payoff -0.38
Gross Profit 0.00
Gross Loss -18.61
Total Net Profit -18.61
-100%
-50%
0%
50%
100%

Comments