#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Don Isbell"
#property link      "disbellj@gmail.com"

extern int MagicNumber = 0;
extern bool SignalMail = False;
extern bool EachTickMode = False;
extern double Lots = 0.1;
extern int Slippage = 3;
extern bool UseStopLoss = True;
extern int StopLoss = 100;
extern bool UseTakeProfit = False;
extern int TakeProfit = 60;
extern bool UseTrailingStop = False;
extern int TrailingStop = 60;

//---- inputs
extern string indicator_1 = "NFP_Sentinel_Don_Revised";

extern bool ShowLastMonth = false;
extern double MonthOffset = 0;
extern string OA = "Override Automatic NFP Start/End Dates";
extern bool OA.Override_AutoDates = false;
extern string OA.NFP_Start = "Default: 8:30AM EST 1st Friday of the month, when NFP released";
extern datetime OA.NFP_StartTime = D'2008.12.05 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern string OA.NFP_End = "Default: 00:00 EST Monday Midnight (11:00 PM Sunday Central time)";
extern datetime OA.NFP_EndTime = D'2008.12.08 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)
extern datetime OA.NFP_LastStartTime = D'2008.11.07 15:30:00';//8:30 AM EST 1st Friday of the month, when NFP released
extern datetime OA.NFP_LastEndTime = D'2008.11.10 07:00:00';//00:00 EST Monday (Midnight? which would be 11:00 PM Sunday Central time?)

extern string indicator_2 = "Sentinel_Revised3";

extern double	EUR = 1.0,	// weights
					JPY = 1.0,
					GBP = 1.0,
					CHF = 1.0,
					CAD = 1.0,
					AUD = 1.0,
					NZD = 1.0;
extern bool AverageGains = False;
extern bool PipsAsWholeNumbers = True;
extern bool Reverse_Sentinal_On_NonUSDBased = True;
extern int MA_Value = 336;//<-- 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 = 12;//<-- 2nd Moving average value
extern int MA2_Shift = 0;//<-- Shift for the MA2. Set to 0 by default.
extern int MA2_Method = 2;//<-- 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 = 18;//<-- 3rd Moving average value
extern int MA3_Shift = 0;//<-- Shift for the MA3. Set to 0 by default.
extern int MA3_Method = 2;//<-- 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.

extern bool Alerts_On = True;

//---- Don's Money Management input parameters
extern bool  UseDonsMM = True;
extern bool USE_MT4_ACCOUNT_BALANCE = True ;
extern double MY_ACCOUNT_BALANCE  = 500 ;
extern double PIP_STOP_LOSS = 20 ;
extern double RISK_PERCENT  = 2  ;

double lot,MODETICKVALUE,myAccountBalance,myRiskPercent;

int TradeCount = 0;

int BarCount;
int Current;
bool TickCheck = False;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;
   
   myRiskPercent=RISK_PERCENT*0.01;//had to use instead of RISK_PERCENT/100, but still needs rounded down
   MODETICKVALUE=MarketInfo(Symbol(),MODE_TICKVALUE) ;
   if( USE_MT4_ACCOUNT_BALANCE == False ) { myAccountBalance = MY_ACCOUNT_BALANCE  ; } else {myAccountBalance = AccountBalance() ;}
   
   //----------------------- ADJUST LOTS IF USING MONEY MANAGEMENT
   if (UseDonsMM == True) {
   lot = NormalizeDouble(((myAccountBalance*myRiskPercent)/(PIP_STOP_LOSS*MODETICKVALUE)),2) ;
   } else {
   lot = Lots;
   }

   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 = ObjectGet("NFP_StartTime",OBJPROP_TIME1);
double NFP_End = ObjectGet("NFP_EndTime",OBJPROP_TIME1);
double NFP_High = ObjectGet("NFP_HighestHigh",OBJPROP_PRICE1);
double NFP_Low = ObjectGet("NFP_LowestLow",OBJPROP_PRICE1);
double NFP_MA = iCustom(NULL, 0, "NFP_Sentinel_Don_Revised",ShowLastMonth,MonthOffset,OA.Override_AutoDates,OA.NFP_Start,OA.NFP_StartTime,OA.NFP_End,OA.NFP_EndTime,OA.NFP_LastStartTime,OA.NFP_LastEndTime,0, 0);

double Sentinel = iCustom(NULL, PERIOD_M30, "Sentinel_Revised3",EUR,JPY,GBP,CHF,CAD,AUD,NZD,AverageGains,PipsAsWholeNumbers,Reverse_Sentinal_On_NonUSDBased,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, 0);
double Sentinel_MA = iCustom(NULL, PERIOD_M30, "Sentinel_Revised3",EUR,JPY,GBP,CHF,CAD,AUD,NZD,AverageGains,PipsAsWholeNumbers,Reverse_Sentinal_On_NonUSDBased,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, 0);
double CurrWeek_High = iHigh(NULL,PERIOD_W1,0);
double CurrWeek_Low = iLow(NULL,PERIOD_W1,0);
double PrevWeek_High = iHigh(NULL,PERIOD_W1,+1);
double PrevWeek_Low = iLow(NULL,PERIOD_W1,+1);
double ThisBarClose = Close[0];

   //+------------------------------------------------------------------+
   //| 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 ( /*Sentinel < Sentinel_MA*/ThisBarClose < NFP_MA || ThisBarClose < NFP_High ) 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 ( /*Sentinel > Sentinel_MA*/ThisBarClose > NFP_MA || ThisBarClose > NFP_Low ) 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 && ThisBarClose > NFP_High && Sentinel > Sentinel_MA && ThisBarClose > NFP_MA ) Order = SIGNAL_BUY;
   } else if (TradeCount > 0) {
   if ( Time[0] > NFP_End && ThisBarClose > NFP_High && Sentinel > Sentinel_MA && ThisBarClose > NFP_MA && ThisBarClose > CurrWeek_High && ThisBarClose > PrevWeek_High ) Order = SIGNAL_BUY;
   }
   
   if(TradeCount == 0) {
   if ( Time[0] > NFP_End && ThisBarClose < NFP_Low && Sentinel < Sentinel_MA && ThisBarClose < NFP_MA ) Order = SIGNAL_SELL;
   } else if (TradeCount > 0) {
   if ( Time[0] > NFP_End && ThisBarClose < NFP_Low && Sentinel < Sentinel_MA && ThisBarClose < NFP_MA && ThisBarClose < CurrWeek_Low && ThisBarClose < PrevWeek_Low ) Order = SIGNAL_SELL;
   }
   
   //+------------------------------------------------------------------+
   //| 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;
   
   if (Alerts_On == True) {
   if(TradeCount == 0) {
   if ( Time[0] > NFP_End && ThisBarClose > NFP_High && Sentinel > Sentinel_MA && ThisBarClose > NFP_MA ) Alert("Buy ", Symbol(),Close[0],"!!!");
   } else if (TradeCount > 0) {
   if ( Time[0] > NFP_End && ThisBarClose > NFP_High && Sentinel > Sentinel_MA && ThisBarClose > NFP_MA && ThisBarClose > CurrWeek_High && ThisBarClose > PrevWeek_High )  Alert("Buy Again ", Symbol(),Close[0],"!!!");
   }
   }
   
   if (Alerts_On == True) {
   if(TradeCount == 0) {
   if ( Time[0] > NFP_End && ThisBarClose < NFP_Low && Sentinel < Sentinel_MA && ThisBarClose < NFP_MA ) Alert("Sell ", Symbol(),Close[0],"!!!");
   } else if (TradeCount > 0) {
   if ( Time[0] > NFP_End && ThisBarClose < NFP_Low && Sentinel < Sentinel_MA && ThisBarClose < NFP_MA && ThisBarClose < CurrWeek_Low && ThisBarClose < PrevWeek_Low ) Alert("Sell Again ", Symbol(),Close[0],"!!!");
   }
   }
   
   string value1=TimeToStr(NFP_Start,TIME_DATE|TIME_MINUTES);
   string value2=TimeToStr(NFP_End,TIME_DATE|TIME_MINUTES);
   
   if (Symbol() == "USDJPY") {
   string value3=DoubleToStr(NFP_High, 2);
   string value4=DoubleToStr(NFP_Low, 2);
   string value5=DoubleToStr(NFP_MA, 2);
   } else {
   value3=DoubleToStr(NFP_High, 4);
   value4=DoubleToStr(NFP_Low, 4);
   value5=DoubleToStr(NFP_MA, 4);
   }
   
   if (Symbol() == "USDJPY") {
   string value6=DoubleToStr(CurrWeek_High, 2);
   string value7=DoubleToStr(CurrWeek_Low, 2);
   string value8=DoubleToStr(PrevWeek_High, 2);
   string value9=DoubleToStr(PrevWeek_Low, 2);
   string value10=DoubleToStr(ThisBarClose, 2);
   } else {
   value6=DoubleToStr(CurrWeek_High, 4);
   value7=DoubleToStr(CurrWeek_Low, 4);
   value8=DoubleToStr(PrevWeek_High, 4);
   value9=DoubleToStr(PrevWeek_Low, 4);
   value10=DoubleToStr(ThisBarClose, 4);
   }
   
   string value11=DoubleToStr(Sentinel, 0);
   string value12=DoubleToStr(Sentinel_MA, 0);
   
   string value13=DoubleToStr(lot, 2);
   
   Comment(
"NFP_Start = " + value1 + "\n" +
"NFP_End = " + value2 + "\n" +
"NFP_High = " + value3 + "\n" +
"NFP_Low = " + value4 + "\n" +
"NFP_MA = " + value5 + "\n" +
"CurrWeek_High = " + value6 + "\n" +
"CurrWeek_Low = " + value7 + "\n" +
"PrevWeek_High = " + value8 + "\n" +
"PrevWeek_Low = " + value9 + "\n" +
"ThisBarClose = " + value10 + "\n" +
"Sentinel = " + value11 + "\n" +
"Sentinel_MA = " + value12 + "\n" +
"Number of Lots to Trade Per Pair = " + value13 );


   return(0);
}
//+------------------------------------------------------------------+

