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);
   }
//+------------------------------------------------------------------+



Sample





Analysis



Market Information Used:

Series array that contains the highest prices of each bar
Series array that contains the lowest prices of each bar


Indicator Curves created:


Indicators Used:



Custom Indicators Used:

Order Management characteristics:
Checks for the total of open orders
It Closes Orders by itself
It automatically opens orders when conditions are reached

Other Features:


BackTest : USDJPY on H1

From 2009-11-01 to 2009-11-30 Profit Factor:0.00 Total Net Profit:0.00

BackTest : USDCHF on H1

From 2009-12-01 to 2010-01-01 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2009-12-01 to 2010-01-17 Profit Factor:1.76 Total Net Profit:17.50

BackTest : USDCAD on H1

From 2009-12-01 to 2010-01-01 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2009-08-01 to 2009-10-01 Profit Factor:0.02 Total Net Profit:-25.50

BackTest : GBPUSD on H1

From 2010-01-01 to 2010-02-27 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-04-01 to 2010-04-30 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-05-01 to 2010-05-31 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-06-01 to 2010-06-30 Profit Factor:0.00 Total Net Profit:0.00

Request Backtest for Average Daily Range


From : (yyyy/mm/dd) To: (yyyy/mm/dd)

Pair: Period: