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