//+------------------------------------------------------------------+
//| This MQL is generated by Expert Advisor Builder                  |
//|                http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/ |
//|                                                                  |
//|  In no event will author be liable for any damages whatsoever.   |
//|                      Use at your own risk.                       |
//|                                                                  |
//+------------------- DO NOT REMOVE THIS HEADER --------------------+

#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Expert Advisor Builder"
#property link      "http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/"

extern int MagicNumber = 0;
extern bool SignalMail = False;
extern bool EachTickMode = False;
extern double Lots = 0.1;
extern int Slippage = 3;
extern bool UseStopLoss = False;
extern int StopLoss = 60;
extern bool UseTakeProfit = False;
extern int TakeProfit = 60;
extern bool UseTrailingStop = False;
extern int TrailingStop = 60;

//---- inputs
extern string NFP_Start_Last3 = "8:30AM EST 1st Friday of the month, when NFP released";
extern datetime NFP_Start_HiLo_Last3 = D'2008.07.04 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern string NFP_End_Last3 = "00:00 EST Monday (11:00 PM Sunday Central time)";
extern datetime NFP_End_HiLo_Last3 = D'2008.07.07 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)

extern string NFP_Start_Last2 = "8:30AM EST 1st Friday of the month, when NFP released";
extern datetime NFP_Start_HiLo_Last2 = D'2008.08.01 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern string NFP_End_Last2 = "00:00 EST Monday (11:00 PM Sunday Central time)";
extern datetime NFP_End_HiLo_Last2 = D'2008.08.04 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)

extern string NFP_Start_Last = "8:30AM EST 1st Friday of the month, when NFP released";
extern datetime NFP_Start_HiLo_Last = D'2008.09.05 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern string NFP_End_Last = "00:00 EST Monday (11:00 PM Sunday Central time)";
extern datetime NFP_End_HiLo_Last = D'2008.09.08 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)

extern string NFP_Start = "8:30AM EST 1st Friday of the month, when NFP released";
extern datetime NFP_Start_HiLo = D'2008.10.03 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern string NFP_End = "00:00 EST Monday (11:00 PM Sunday Central time)";
extern datetime NFP_End_HiLo = D'2008.10.06 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)

extern string NFP_Start_Next = "8:30AM EST 1st Friday of the month, when NFP released";
extern datetime NFP_Start_HiLo_Next = D'2008.11.07 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern string NFP_End_Next = "00:00 EST Monday (11:00 PM Sunday Central time)";
extern datetime NFP_End_HiLo_Next = D'2008.11.10 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)

extern double	EUR = 1.0,	// weights
					JPY = 1.0,
					GBP = 1.0,
					CHF = 1.0,
					CAD = 1.0,
					AUD = 1.0;
extern bool AverageGains = True;
extern bool PipsAsWholeNumbers = False;
extern int MA_Value = 100;//<-- Moving average value set to 336 by default
extern int MA_Shift = 0;//<-- Shift for the MA. Set to 0 by default.
extern int MA_Method = 0;//<-- MA Method (0 is SMA, 1 is EMA, 2 is SMMA, 3 is LWMA). Anything above/below these values is set to SMA (0) automatically.
extern bool Use_2nd_MA = False;
extern int MA2_Value = 3;//<-- 2nd Moving average value
extern int MA2_Shift = 0;//<-- Shift for the MA2. Set to 0 by default.
extern int MA2_Method = 0;//<-- MA2 Method (0 is SMA, 1 is EMA, 2 is SMMA, 3 is LWMA). Anything above/below these values is set to SMA (0) automatically.
extern bool Use_3rd_MA = False;
extern int MA3_Value = 0;//<-- 3rd Moving average value
extern int MA3_Shift = 0;//<-- Shift for the MA3. Set to 0 by default.
extern int MA3_Method = 0;//<-- MA3 Method (0 is SMA, 1 is EMA, 2 is SMMA, 3 is LWMA). Anything above/below these values is set to SMA (0) automatically.

//Don's Money Management input parameters
extern bool  UseDonsMM = True;
extern string  cs="Micro=1000;Mini=10000;Standard=100000";
extern double  ContractSize = 100000;//Micro=1000;Mini=10000;Standard=100000
extern double  MaximumRisk = 2;//2%

int TradeCount = 0;

int BarCount;
int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;
   
   //----------------------- ADJUST LOTS IF USING MONEY MANAGEMENT
   if (UseDonsMM == True) {
   Lots = LotSize();
   }

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {
   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() {
   int Order = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;



   if (EachTickMode && Bars != BarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+

double NFP_Start_ThisMonth = ObjectGet("NFP_Start_ThisMonth",OBJPROP_TIME1);
double NFP_End_ThisMonth = ObjectGet("NFP_End_ThisMonth",OBJPROP_TIME1);
double NFP_High_ThisMonth = ObjectGet("NFP_High_ThisMonth",OBJPROP_PRICE1);
double NFP_Low_ThisMonth = ObjectGet("NFP_Low_ThisMonth",OBJPROP_PRICE1);
double NFP_Sentinel_MA = iCustom(NULL, PERIOD_M30, "NFP_Sentinel_Don",NFP_Start_Last3,NFP_Start_HiLo_Last3,NFP_End_Last3,NFP_End_HiLo_Last3,NFP_Start_Last2,NFP_Start_HiLo_Last2,NFP_End_Last2,NFP_End_HiLo_Last2,NFP_Start_Last,NFP_Start_HiLo_Last,NFP_End_Last,NFP_End_HiLo_Last,NFP_Start,NFP_Start_HiLo,NFP_End,NFP_End_HiLo,NFP_Start_Next,NFP_Start_HiLo_Next,NFP_End_Next,NFP_End_HiLo_Next,0, Current + 0);
double Sentinel_Revised2 = iCustom(NULL, PERIOD_M30, "Sentinel_Revised2",EUR,JPY,GBP,CHF,CAD,AUD,AverageGains,PipsAsWholeNumbers,MA_Value,MA_Shift,MA_Method,Use_2nd_MA,MA2_Value,MA2_Shift,MA2_Method,Use_3rd_MA,MA3_Value,MA3_Shift,MA3_Method,0, Current + 0);
double Sentinel_Revised2_MA = iCustom(NULL, PERIOD_M30, "Sentinel_Revised2",EUR,JPY,GBP,CHF,CAD,AUD,AverageGains,PipsAsWholeNumbers,MA_Value,MA_Shift,MA_Method,Use_2nd_MA,MA2_Value,MA2_Shift,MA2_Method,Use_3rd_MA,MA3_Value,MA3_Shift,MA3_Method,1, Current + 0);
double CurrWeek_High = iHigh(NULL,PERIOD_W1,Current +0);
double CurrWeek_Low = iLow(NULL,PERIOD_W1,Current +0);
double PrevWeek_High = iHigh(NULL,PERIOD_W1,Current +1);
double PrevWeek_Low = iLow(NULL,PERIOD_W1,Current +1);

   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol()) {
         IsTrade = True;
         if(OrderType() == OP_BUY) {
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+

                     //if ( Var2 < Var1 ) Order = SIGNAL_CLOSEBUY;


            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {                 
               if(Bid - OrderOpenPrice() > Point * TrailingStop) {
                  if(OrderStopLoss() < Bid - Point * TrailingStop) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
                     if (!EachTickMode) BarCount = Bars;
                     continue;
                  }
               }
            }
         } else {
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+

                     //if ( Var2 > Var1 ) Order = SIGNAL_CLOSESELL;


            //+------------------------------------------------------------------+
            //| Signal End(Exit Sell)                                            |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, DarkOrange);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {                 
               if((OrderOpenPrice() - Ask) > (Point * TrailingStop)) {
                  if((OrderStopLoss() > (Ask + Point * TrailingStop)) || (OrderStopLoss() == 0)) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0, DarkOrange);
                     if (!EachTickMode) BarCount = Bars;
                     continue;
                  }
               }
            }
         }
      }
   }

   //+------------------------------------------------------------------+
   //| Signal Begin(Entry)                                              |
   //+------------------------------------------------------------------+
   if(TradeCount == 0) {
   if ( Time[0] > NFP_End_ThisMonth && Ask > NFP_High_ThisMonth && Sentinel_Revised2 > Sentinel_Revised2_MA ) Order = SIGNAL_BUY;
   } else if (TradeCount > 0) {
   if ( Time[0] > NFP_End_ThisMonth && Ask > NFP_High_ThisMonth && Sentinel_Revised2 > Sentinel_Revised2_MA && Ask > NFP_Sentinel_MA && Bid > CurrWeek_High && Bid > PrevWeek_High ) Order = SIGNAL_BUY;
   }
   
   if(TradeCount == 0) {
   if ( Time[0] > NFP_End_ThisMonth && Bid < NFP_Low_ThisMonth && Sentinel_Revised2 < Sentinel_Revised2_MA ) Order = SIGNAL_SELL;
   } else if (TradeCount > 0) {
   if ( Time[0] > NFP_End_ThisMonth && Bid > NFP_High_ThisMonth && Sentinel_Revised2 > Sentinel_Revised2_MA && Bid > NFP_Sentinel_MA && Bid < CurrWeek_Low && Bid < PrevWeek_Low ) Order = SIGNAL_BUY;
   }
   
   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+

   //Buy
   if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Ask - StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Ask + TakeProfit * Point; else TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, StopLossLevel, TakeProfitLevel, "Buy(#" + MagicNumber + ")", MagicNumber, 0, DodgerBlue);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("BUY order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
			} else {
				Print("Error opening BUY order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   //Sell
   if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lots)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

         Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, StopLossLevel, TakeProfitLevel, "Sell(#" + MagicNumber + ")", MagicNumber, 0, DeepPink);
         if(Ticket > 0) {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES)) {
				Print("SELL order opened : ", OrderOpenPrice());
                if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
			} else {
				Print("Error opening SELL order : ", GetLastError());
			}
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   if (!EachTickMode) BarCount = Bars;

   return(0);
}
//+------------------------------------------------------------------+
	//----------------------- MONEY MANAGEMENT FUNCTION  
   //----------------------- SOURCE : DON ISBELL
double lot;
double LotSize()
{
     if (Symbol() == "EURUSD" || Symbol() == "GBPUSD" || Symbol() == "AUDUSD") {
     lot=NormalizeDouble((AccountBalance()*(MaximumRisk/100))/(StopLoss*((ContractSize*0.0001))),2);
	  }
	  else if (Symbol() == "USDCHF") {
     lot = NormalizeDouble((AccountBalance()*(MaximumRisk/100))/(StopLoss*((ContractSize/(MarketInfo("USDCHF", MODE_ASK))*0.0001))),2);
	  }
	  else if (Symbol() == "USDCAD") {
     lot = NormalizeDouble((AccountBalance()*(MaximumRisk/100))/(StopLoss*((ContractSize/(MarketInfo("USDCAD", MODE_ASK))*0.0001))),2);
	  }
	  else if (Symbol() == "USDJPY") {
     lot = NormalizeDouble((AccountBalance()*(MaximumRisk/100))/(StopLoss*((ContractSize/(MarketInfo("USDJPY", MODE_ASK))*0.01))),2);
	  } 
	  return (lot);
}