//+------------------------------------------------------------------+
//|       This MQL is generated by Expert Advisor Builder            |
//|     http://sufx.core.t3-ism.net/ExpertAdvisorBuilder/            |
//|         Trading Methodology Devised by TradeForex           
//|    
//|               
//|               
//|                                                                  |
//|  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 "Copyright © 2008, AKA TradeForexFX"
#property link      "http://www./"

extern string  Expert_Name    = "---- MACD Moving Av EA by TF ----";


//***********************


extern string EA_Comment = "MACD MA" ;
extern int MagicNumber = 9219;
extern bool PlaySound_OnTrade_Open = False;
extern string SoundFile = "abc.wav" ;
extern bool ShowComments  = True;
extern bool SignalMail = False;



extern int Maximum_Spread = 8;
bool EachTickMode = True;


extern double TickMultiplier = 1.00;
extern string TickMultiplier1 = "TickMultiplier is the value of each Tick Move" ;
extern string TickMultiplier2 = "e.g. One tick move from 1665.25 to 1665.50= 25" ;
extern string TickMultiplier3 = "therefore TickMultiplierwill be = 25" ;
extern string TickMultiplier4 = "eg. Move from 1.9005 to 1.9006  = 1" ;
extern string TickMultiplier5 = "eg. Move from 5000 to 5001 = 1 " ;

extern string TradingParameters = "------Trading Parameters -------" ;
extern double Lots = 1.00;
bool StopLossMode = false;
extern int HardStopLoss = 300;
bool TakeProfitMode = false;
extern int TakeProfit = 250;
extern int Slippage = 3;

double MATrendPeriod = 8;
double MATrendPeriod_2 = 15; 

extern bool Close_Lots_Mode = True;
extern string DistributeAbove_Traded_Lots = "Fully distribute above Lots quantity " ;

extern double First_Close = 0.99 ;
extern double Second_Close = 0.01 ;
extern double Third_Close = 0.00 ;

//extern string REMINDER_Use_Multiples = "Use Multiples of One Tick Move as expalined above" ;
extern int First_Close_TP = 30 ;
extern int Second_Close_TP = 250 ;
extern int Third_Close_TP = 350 ;


extern bool StealthStopLossMode = True;
extern int StealthStopLoss = 125;
bool TrailingStopMode = false;
int TrailingStop = 250;

bool MoveStopOnce = True;
extern int MoveStopWhenProfit = 20;
extern int MoveStopToProfitOf = 1;
bool CloseExcept = True;
extern double QtyForStopExcept = 0.01;
extern int StopWhenProfit = 12;
extern int SlippageForAbove = 3;
extern string IMPORTANT = "Above Slippage should ATLEAST be 1 ";
extern bool MoveStopOnceWhenQty = True;
extern double MoveStopWhenQty = 0.01;
extern int MoveStopBy = 500;

//******************************************
// Inputs for trading hours
extern string  Trading_Hour_Parameters="--Trading Hour Parameters--";
extern string  Trading_Hour_Parameters_="Use Hours according to your own Broker";
//extern string  Trading_Hours="UseTradingHours - Enter 1 for YES, 0 for NO";
int    UseTradingHours = 1;
extern string  Session1="Trade Session 1";
// - Enter 1 for YES, 0 for NO
int    TradeSession1 = 1;
extern int     Session1Start = 230;       // Start trades after time
extern int     Session1Stop = 0930;      // Stop trading after time
extern string  Session2="Trade Session 2";
// - Enter 1 for YES, 0 for NO
int    TradeSession2 = 1;
extern int     Session2Start = 0930;       // Start trades after time
extern int     Session2Stop = 1400;      // Stop trading after time
extern string  Session3="Trade Session 3";
// - Enter 1 for YES, 0 for NO
int    TradeSession3 = 1;
extern int     Session3Start = 1400;       // Start trades after time
extern int     Session3Stop = 1900;      // Stop trading after time
extern string  Session4="Trade Session 4";
// - Enter 1 for YES, 0 for NO
int    TradeSession4 = 0;
extern int     Session4Start = 1900;       // Start trades after time
extern int     Session4Stop = 2000;      // Stop trading after time
extern string  Session5="Trade Session 5";
// - Enter 1 for YES, 0 for NO
int    TradeSession5 = 1;
extern int     Session5Start = 2000;       // Start trades after time
extern int     Session5Stop = 2359;      // Stop trading after time

bool     YesStop;
double   myPoint;



// Trading Hours variables end here
//************************************

int BarCount;
int Current;
bool TickCheck = False;


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;
//  myPoint = SetPoint(Symbol());
  
   

   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;
   
    if (Close_Lots_Mode) ClosePartialLots();

   if (MoveStopOnce)  MoveStopOnceMode();
   
    if (ShowComments) ShowCommentsMode();
    if (MoveStopOnceWhenQty)  MoveStopOnceWhenQtyMode();
    if (StealthStopLossMode)  DoStealthStopLoss();    
    if (CloseExcept) DoCloseExcept();
    if (HardStopLoss > 0) DoHardStopLoss();

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+

   

   
   double MacdCurrent_M5_H,MacdCurrent,MacdPrevious, MacdCurrent_M15,MacdPrevious_M15, MacdCurrent_M5,MacdPrevious_M5, MacdCurrent_M30,MacdPrevious_M30 ;
   double SignalCurrent, SignalPrevious, SignalPrevious_M5, SignalPrevious_M5_H;
   double MaCurrent, MaPrevious,MaCurrent_H1_P15,MaCurrent_M15, MaPrevious_M15;
   double MaCurrent_4_H1, MaCurrent_8_H1;

   double  _TakeProfit_ = TakeProfit*TickMultiplier;
   double  _HardStopLoss_ =  HardStopLoss*TickMultiplier;
   double  _Slippage_ =  Slippage*TickMultiplier;
   double  _TrailingStop_  =  TrailingStop*TickMultiplier;


   MacdCurrent_M5=iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious_M5=iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_MAIN,1); 
   SignalPrevious_M5=iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); 
   MacdCurrent_M5_H=iMACD(NULL,PERIOD_M5,144,312,108,PRICE_CLOSE,MODE_MAIN,0);
   SignalPrevious_M5_H=iMACD(NULL,PERIOD_M5,144,312,108,PRICE_CLOSE,MODE_SIGNAL,1); 
   MacdCurrent=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   MacdCurrent_M15=iMACD(NULL,PERIOD_M15,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious_M15=iMACD(NULL,PERIOD_M15,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   MacdCurrent_M30=iMACD(NULL,PERIOD_M30,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious_M30=iMACD(NULL,PERIOD_M30,12,26,9,PRICE_CLOSE,MODE_MAIN,1); 
   MaCurrent_M15=iMA(NULL,PERIOD_M15,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   SignalCurrent=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
   MaPrevious_M15=iMA(NULL,PERIOD_M15,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   MaCurrent=iMA(NULL,PERIOD_H1,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   MaPrevious=iMA(NULL,PERIOD_H1,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   MaCurrent_H1_P15=iMA(NULL,PERIOD_H1,MATrendPeriod_2,0,MODE_EMA,PRICE_CLOSE,0);

   MaCurrent_4_H1=iMA(NULL,PERIOD_H1,4,0,MODE_EMA,PRICE_CLOSE,0);
   MaCurrent_8_H1=iMA(NULL,PERIOD_H1,8,0,MODE_EMA,PRICE_CLOSE,0);





string MacdDirection = "None";
      if( MacdCurrent > MacdPrevious &&
          MacdCurrent_M15 > MacdPrevious_M15 &&
          MacdCurrent_M30 > MacdPrevious_M30 &&
          MacdCurrent_M5 > MacdPrevious_M5 &&
          MacdCurrent_M5 > SignalPrevious_M5 && 
          MacdCurrent_M5 > MacdPrevious_M5 &&
          MacdCurrent_M5 > SignalPrevious_M5 &&
          MacdCurrent_M5_H > SignalPrevious_M5_H &&
          MacdCurrent>SignalCurrent 
      )
      MacdDirection = "Long";
   
      if( MacdCurrent < MacdPrevious &&
          MacdCurrent_M15 < MacdPrevious_M15 &&
          MacdCurrent_M30 < MacdPrevious_M30 &&
          MacdCurrent_M5 < MacdPrevious_M5 &&
          MacdCurrent_M5 < SignalPrevious_M5 && 
          MacdCurrent_M5 < MacdPrevious_M5 &&
          MacdCurrent_M5 < SignalPrevious_M5 &&
          MacdCurrent_M5_H < SignalPrevious_M5_H &&
          MacdCurrent<SignalCurrent 
      )
        MacdDirection = "Short";
     
string MADirection = "None";
      if(
      MaCurrent_4_H1>MaCurrent_8_H1 &&
      MaCurrent>MaPrevious &&
      MaCurrent_M15>MaPrevious_M15 &&
      Bid > MaCurrent_H1_P15  )
      MADirection = "Long";
   
      if(
      MaCurrent_4_H1<MaCurrent_8_H1 &&      
      MaCurrent<MaPrevious &&
      MaCurrent_M15<MaPrevious_M15 &&
      Ask < MaCurrent_H1_P15
      )
      MADirection = "Short";
   
    
string TradeDirection = "None";
if(MADirection == "Short"
&& MacdDirection == "Short"  
   ) TradeDirection = "Short";

if(MADirection == "Long"  
&& MacdDirection == "Long"  
   ) TradeDirection = "Long";



string CloseDirection = "None";
if(MADirection == "Long"
&& MacdDirection == "Long"
   )

CloseDirection = "CloseSell";
   
if(MADirection == "Short"
&& MacdDirection == "Short"
  )

CloseDirection = "CloseBuy";



double Spread = (Ask - Bid) / Point ;

double Trade_0_1 = Maximum_Spread + 1 - Spread ;

   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

     
   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() <= OP_SELL) {
         IsTrade = True;
       if(OrderType() == OP_BUY) {


            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+

       if (       CloseDirection == "CloseBuy" 
       
             )  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(TrailingStopMode && _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;
                  }
               }
            }
            
 //Close_Lots - Buy        
   
       
            
      
         } else {
         
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+

       if (        
               CloseDirection == "CloseSell" 
                   
            ) 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(TrailingStopMode && _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;
                  }
               }
               
   //Close_Lots - Sell
    
                  
               
            } // Trailing Stop
         } // Close
      } // OrderType
   }// for

//*******************************************






// Check trading sessions

   int NumOrders = 0;
   
   NumOrders = CalculateCurrentOrders();
   if(NumOrders == 0) {
     YesStop = false;
      
     if (UseTradingHours == 1) {
        YesStop = CheckTradingTimes();
   //Check position  
   
     
 
     }

     if (YesStop == false) {




   //+------------------------------------------------------------------+
   //| Signal Begin(Entry)  && Buy3_1 > Buy3_2 && Sell3_1 < Sell3_2  && Buy6_1 > Buy6_2  && Sell6_1 < Sell6_2                                                | && Sell9_1 > Sell9_2 && Buy9_1 > Buy9_2 
   //+------------------------------------------------------------------+
if     (  
         Trade_0_1 > 0 &&
         
         TradeDirection == "Long" 
       
          ) Order = SIGNAL_BUY;
 
      if   (
         Trade_0_1 > 0 &&
         TradeDirection == "Short"  
           
           ) Order = SIGNAL_SELL;



   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+


   //Buy
       if (Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
          if(!IsTrade) {
         //Check free margin
            if (AccountFreeMargin() < (500 * Lots)) {
              Print("We have no money. Free Margin = ", AccountFreeMargin());
              return(0);
            }

            if (StopLossMode) StopLossLevel = Ask - _HardStopLoss_ * Point; else StopLossLevel = 0.0;
            if (TakeProfitMode) TakeProfitLevel = Ask + _TakeProfit_ * Point; else TakeProfitLevel = 0.0;

            Ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, _Slippage_, StopLossLevel, TakeProfitLevel, EA_Comment + 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() < (500 * Lots)) {
                Print("We have no money. Free Margin = ", AccountFreeMargin());
                return(0);
             }

             if (StopLossMode) StopLossLevel = Bid + _HardStopLoss_ * Point; else StopLossLevel = 0.0;
             if (TakeProfitMode) TakeProfitLevel = Bid - _TakeProfit_ * Point; else TakeProfitLevel = 0.0;

             Ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, _Slippage_, StopLossLevel, TakeProfitLevel,  EA_Comment + 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);
          }
       }

     } // YesStop
   } // NumOrders

   if (!EachTickMode) BarCount = Bars;

   return(0);
}

//+------------------------------------------------------------------+
// Return true if time is not in session for trading
bool CheckOutsideSession(int SessionStart, int SessionStop, int ct)
{

   if (SessionStart < SessionStop)
   {
     if (ct >= SessionStart && ct <= SessionStop) return (false); else return(true);
   }
   else
   {
      if (ct > SessionStop && ct < SessionStart) return (true); else return(false);
   }
}

bool CheckTradingTimes()
{
   bool StopTrading;
   int ct;
   ct = Hour() * 100 + Minute();
   
     StopTrading = true;

     if (TradeSession1 == 1)
     {
        StopTrading = CheckOutsideSession(Session1Start, Session1Stop, ct);
     }
     if (StopTrading == true)
     {

       if (TradeSession2 == 1)
       {
         StopTrading = CheckOutsideSession(Session2Start, Session2Stop, ct);
       }
     }
     if (StopTrading == true)
     {

       if (TradeSession3 == 1)
       {
         StopTrading = CheckOutsideSession(Session3Start, Session3Stop, ct);
       }
     }
     if (StopTrading == true)
     {

       if (TradeSession4 == 1)
       {
         StopTrading = CheckOutsideSession(Session4Start, Session4Stop, ct);
       }
     }
     if (StopTrading == true)
     {

       if (TradeSession5 == 1)
       {
         StopTrading = CheckOutsideSession(Session5Start, Session5Stop, ct);
       }
     }
     
     return(StopTrading);
}

int CalculateCurrentOrders()
  {
   int buys = 0, sells = 0, num = 0;
   for(int i=0;i<OrdersTotal();i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!= Symbol()) continue;
      if (OrderMagicNumber()!= MagicNumber) continue;
      if(OrderType() == OP_BUY)  buys++;
      if(OrderType() == OP_SELL) sells++;
     }
     
   num = buys + sells;
   return(num);
  }


// Modified to use a function for easier use in an EA
void ClosePartialLots()
{
   int Total;
   double QtyOrders = 0.00;
   double QtyOrderSells = 0.00;
   
   double  _First_Close_TP_ =  First_Close_TP*TickMultiplier;
   double  _Second_Close_TP_  = Second_Close_TP*TickMultiplier;
   double  _Third_Close_TP_  =  Third_Close_TP*TickMultiplier;
   double  _Slippage_ =  Slippage*TickMultiplier;


   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() <= OP_SELL)
      {
         IsTrade = True;
         
         if(OrderType() == OP_BUY) QtyOrders = OrderLots();
       
         if(OrderType() == OP_SELL) QtyOrderSells = OrderLots();
       

            
         if(OrderType() == OP_BUY) {
       
 //Close_Lots - Buy
 
            if(QtyOrders == Lots)
            {                      
               if(Bid - OrderOpenPrice() > Point * _First_Close_TP_)
               {
                     OrderClose(OrderTicket(), First_Close , Bid, _Slippage_, MediumSeaGreen);
                     continue;
               }
            }           
   
   
            if( ( (QtyOrders - Third_Close) > 0.00 ) 
                && (QtyOrders - (Second_Close + Third_Close ) <= 0.00))
            {                 
               if(Bid - OrderOpenPrice() >  (Point * _Second_Close_TP_))
               {
                     OrderClose(OrderTicket(), Second_Close , Bid, _Slippage_, MediumSeaGreen);
                     continue;
               }
            }           
   
            if((QtyOrders - Third_Close <= 0.00)
                && (QtyOrders > 0.00 ))
            {                 
               if(Bid - OrderOpenPrice() > Point * _Third_Close_TP_)
               {
                     OrderClose(OrderTicket(), QtyOrders , Bid, _Slippage_, MediumSeaGreen);
                     continue;
               }
            }           
      
         }
       
         if(OrderType() == OP_SELL) {
         

  //Close_Lots - Sell
  // Sell trades must exit at Ask price 
  

 
            if(QtyOrderSells == Lots)
            {                      
               if(OrderOpenPrice() - Ask > Point * _First_Close_TP_)
               {
                     OrderClose(OrderTicket(), First_Close , Ask, _Slippage_, MediumSeaGreen);
                     continue;
               }
            }           
   
   
            if((QtyOrderSells - Third_Close > 0.00 ) 
             &&(QtyOrderSells - (Second_Close + Third_Close ) <= 0.00) )
            {                 
               if(OrderOpenPrice() - Ask >  (Point * _Second_Close_TP_))
               {
                     OrderClose(OrderTicket(), Second_Close , Ask, _Slippage_, MediumSeaGreen);
                     continue;
               }
            }           
   
            if((QtyOrderSells - Third_Close <= 0.00 )
                && (QtyOrderSells > 0.00 ))
            {                 
               if(OrderOpenPrice() - Ask > Point * _Third_Close_TP_)
               {
                     OrderClose(OrderTicket(), QtyOrderSells , Ask, _Slippage_, MediumSeaGreen);
                     continue;
               }
            }           
         } 
      } 
   } 
}

/*
// Fix of Point for Brokers using 3 and 5 digit pricing
double SetPoint(string mySymbol)
{
   double mPoint, myDigits;
   
   myDigits = MarketInfo (mySymbol, MODE_DIGITS);
   if (myDigits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

*/

void ShowCommentsMode()
{ 
      double MacdCurrent_M5_H,MacdCurrent,MacdPrevious, MacdCurrent_M15,MacdPrevious_M15, MacdCurrent_M5,MacdPrevious_M5, MacdCurrent_M30,MacdPrevious_M30 ;
   double SignalCurrent, SignalPrevious, SignalPrevious_M5, SignalPrevious_M5_H;
   double MaCurrent, MaPrevious,MaCurrent_H1_P15,MaCurrent_M15, MaPrevious_M15;
   double MaCurrent_4_H1, MaCurrent_8_H1;

   double  _TakeProfit_ = TakeProfit*TickMultiplier;
   double  _HardStopLoss_ =  HardStopLoss*TickMultiplier;
   double  _Slippage_ =  Slippage*TickMultiplier;
   double  _TrailingStop_  =  TrailingStop*TickMultiplier;


   MacdCurrent_M5=iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious_M5=iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_MAIN,1); 
   SignalPrevious_M5=iMACD(NULL,PERIOD_M5,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); 
   MacdCurrent_M5_H=iMACD(NULL,PERIOD_M5,144,312,108,PRICE_CLOSE,MODE_MAIN,0);
   SignalPrevious_M5_H=iMACD(NULL,PERIOD_M5,144,312,108,PRICE_CLOSE,MODE_SIGNAL,1); 
   MacdCurrent=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   MacdCurrent_M15=iMACD(NULL,PERIOD_M15,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious_M15=iMACD(NULL,PERIOD_M15,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   MacdCurrent_M30=iMACD(NULL,PERIOD_M30,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious_M30=iMACD(NULL,PERIOD_M30,12,26,9,PRICE_CLOSE,MODE_MAIN,1); 
   MaCurrent_M15=iMA(NULL,PERIOD_M15,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   SignalCurrent=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,PERIOD_H1,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
   MaPrevious_M15=iMA(NULL,PERIOD_M15,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   MaCurrent=iMA(NULL,PERIOD_H1,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   MaPrevious=iMA(NULL,PERIOD_H1,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   MaCurrent_H1_P15=iMA(NULL,PERIOD_H1,MATrendPeriod_2,0,MODE_EMA,PRICE_CLOSE,0);

   MaCurrent_4_H1=iMA(NULL,PERIOD_H1,4,0,MODE_EMA,PRICE_CLOSE,0);
   MaCurrent_8_H1=iMA(NULL,PERIOD_H1,8,0,MODE_EMA,PRICE_CLOSE,0);



/*
      
string MACDOpenLevelDirection = "None";
      if(
          MacdCurrent>SignalCurrent &&
          MaCurrent>MaPrevious    
      )
      MACDOpenLevelDirection = "Long";
   
      if(
         
          MacdCurrent<SignalCurrent &&
          MaCurrent<MaPrevious 
      )
        MACDOpenLevelDirection = "Short";
      
*/
string MacdDirection = "None";
      if( MacdCurrent > MacdPrevious &&
          MacdCurrent_M15 > MacdPrevious_M15 &&
          MacdCurrent_M30 > MacdPrevious_M30 &&
          MacdCurrent_M5 > MacdPrevious_M5 &&
          MacdCurrent_M5 > SignalPrevious_M5 && 
          MacdCurrent_M5 > MacdPrevious_M5 &&
          MacdCurrent_M5 > SignalPrevious_M5 &&
          MacdCurrent_M5_H > SignalPrevious_M5_H &&
          MacdCurrent>SignalCurrent 
      )
      MacdDirection = "Long";
   
      if( MacdCurrent < MacdPrevious &&
          MacdCurrent_M15 < MacdPrevious_M15 &&
          MacdCurrent_M30 < MacdPrevious_M30 &&
          MacdCurrent_M5 < MacdPrevious_M5 &&
          MacdCurrent_M5 < SignalPrevious_M5 && 
          MacdCurrent_M5 < MacdPrevious_M5 &&
          MacdCurrent_M5 < SignalPrevious_M5 &&
          MacdCurrent_M5_H < SignalPrevious_M5_H &&
          MacdCurrent<SignalCurrent 
      )
        MacdDirection = "Short";
     
string MADirection = "None";
      if(
      MaCurrent_4_H1>MaCurrent_8_H1 &&
      MaCurrent>MaPrevious &&
      MaCurrent_M15>MaPrevious_M15 &&
      Bid > MaCurrent_H1_P15  )
      MADirection = "Long";
   
      if(
      MaCurrent_4_H1<MaCurrent_8_H1 &&      
      MaCurrent<MaPrevious &&
      MaCurrent_M15<MaPrevious_M15 &&
      Ask < MaCurrent_H1_P15
      )
      MADirection = "Short";
   
    
string TradeDirection = "None";
if(MADirection == "Short"
&& MacdDirection == "Short"  
   ) TradeDirection = "Short";

if(MADirection == "Long"  
&& MacdDirection == "Long"  
   ) TradeDirection = "Long";



string CloseDirection = "None";
if(MADirection == "Long"
&& MacdDirection == "Long"
   )

CloseDirection = "CloseSell";
   
if(MADirection == "Short"
&& MacdDirection == "Short"
  )

CloseDirection = "CloseBuy";



    int Total;
   double QtyOrders = 0.00;

   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      
 if(OrderSymbol() == Symbol()
   && OrderMagicNumber() == MagicNumber 
   &&( OrderType() == OP_BUY || OrderType() == OP_SELL)) QtyOrders = OrderLots();
 string TradingHour = "Trading is stopped" ;      
 if (UseTradingHours != 1 || QtyOrders != 0)TradingHour = "We are Trading";

   if(QtyOrders == 0) {
     YesStop = false;
      
     if (UseTradingHours == 1) {
        YesStop = CheckTradingTimes();
        
   //Check position        
        if (YesStop == true && QtyOrders != 0) 
        TradingHour = "Trading is stopped";
        
}} 

}
 
     Comment (
          "", "\n",              
          TradingHour, "\n",  
          "TradeDirection   " ,  TradeDirection,"  CloseDirection   " ,  CloseDirection, "\n",
          "Spread     ", MathAbs(Ask - Bid)/ Point ,"\n",              
          "Qty in trade     ", QtyOrders ,"\n",              
          "MACD Direcion ", MacdDirection ,"\n",
          "MA Direction    ", MADirection , "\n",
          "Orders Total " , OrdersTotal(),"\n",
          "EA_Comment   " , EA_Comment
          );


       



   
   }





// Modified to use a function for easier use in an EA
void MoveStopOnceMode()
{
   int Total;
   double QtyOrders = 0.00;
   double QtyOrderSells = 0.00;
   double  _MoveStopWhenProfit_  =  MoveStopWhenProfit*TickMultiplier;
   double  _MoveStopToProfitOf_  =  _MoveStopToProfitOf_*TickMultiplier;

   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() > OP_SELL) continue;
      IsTrade = True;
      if(OrderType() == OP_BUY)
        {
         QtyOrders = OrderLots();
         //MoveOnce 
         if(MoveStopOnce && _MoveStopWhenProfit_ > 0 && QtyOrders > MoveStopWhenQty)
           {
            if(Bid - OrderOpenPrice() >= Point * _MoveStopWhenProfit_)
              {
               if(OrderStopLoss() < OrderOpenPrice() + Point * _MoveStopToProfitOf_)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() + Point * _MoveStopToProfitOf_, OrderTakeProfit(), 0, Red);
                  if(!EachTickMode) BarCount = Bars;
                  continue; 
                 }
              }
           }  
        }
      else
        {
         QtyOrderSells = OrderLots();
         //MoveOnce 
         if(MoveStopOnce && _MoveStopWhenProfit_ > 0)
           {
            if(OrderOpenPrice() - Ask >= Point * _MoveStopWhenProfit_ && QtyOrderSells > MoveStopWhenQty)
              {
               if(OrderStopLoss() > OrderOpenPrice() - Point * _MoveStopToProfitOf_)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() - Point * _MoveStopToProfitOf_, OrderTakeProfit(), 0, Red);
                  if(!EachTickMode) BarCount = Bars;
                  continue; 
                 }
              }
           }
        }
     }
  }
  
  
void MoveStopOnceWhenQtyMode()
{
   int Total;
   double QtyOrders = 0.00;
   double QtyOrderSells = 0.00;
   double  _MoveStopBy_  =  MoveStopBy*TickMultiplier;
   double  _MoveStopToProfitOf_  =  MoveStopToProfitOf*TickMultiplier;

   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() > OP_SELL) continue;
      IsTrade = True;
      if(OrderType() == OP_BUY)
        {
         QtyOrders = OrderLots();
         //MoveOnce 
         if(MoveStopOnceWhenQty &&  QtyOrders == MoveStopWhenQty )
           {
            if(Bid - OrderOpenPrice() >= Point * _MoveStopToProfitOf_)
              {
               if(OrderStopLoss() > OrderOpenPrice() - Point * _MoveStopBy_)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() - Point * _MoveStopBy_, OrderTakeProfit(), 0, Red);
                  if(!EachTickMode) BarCount = Bars;
                  continue; 
                 }
              }
           }  
        }
      else
        {
         QtyOrderSells = OrderLots();
         //MoveOnce 
         if(MoveStopOnce && QtyOrderSells == MoveStopWhenQty )
           {
            if(OrderOpenPrice() - Ask >= Point * _MoveStopToProfitOf_)
              {
               if(OrderStopLoss() < OrderOpenPrice() + Point * _MoveStopBy_)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() + Point * _MoveStopBy_, OrderTakeProfit(), 0, Red);
                  if(!EachTickMode) BarCount = Bars;
                  continue; 
                 }
              }
           }
        }
     }
  }
  
  
  
void DoStealthStopLoss()

{
   int Total;
   double QtyOrders = 0.00;
   double QtyOrderSells = 0.00;
   double OrderOpenPr = 0.00;
   double OrderStopLo = 0.00;
   double  _StealthStopLoss_  =  StealthStopLoss*TickMultiplier;
   double  _SlippageForAbove_  =  SlippageForAbove*TickMultiplier;

   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() <= OP_SELL)
      {
         IsTrade = True;
         
 //        if(OrderType() == OP_BUY) 
       
//         if(OrderType() == OP_SELL) 
         if(OrderType() == OP_BUY) {
       
 //Close_Lots - Buy
             QtyOrders = OrderLots();
             OrderOpenPr =OrderOpenPrice();
//             OrderStopLo = OrderStopLoss();
            if(QtyOrders ==  Lots )
            {                      
               if( (OrderOpenPr - Bid  == Point * _StealthStopLoss_ ) || (OrderOpenPr - Bid  > Point * _StealthStopLoss_)) 
//               
               {      OrderClose(OrderTicket(), QtyOrders - QtyForStopExcept , Bid, _SlippageForAbove_, MediumSeaGreen);
                     continue;
               }
            }           
   
      
         }
       
      
         if(OrderType() == OP_SELL) {
         

  //Close_Lots - Sell
  // Sell trades must exit at Ask price   
           QtyOrderSells = OrderLots();
           OrderOpenPr =OrderOpenPrice();
 //            OrderStopLo = OrderStopLoss();
            if(QtyOrderSells ==  Lots )
            {                      
               if((Ask - OrderOpenPr  == Point * _StealthStopLoss_) || (Ask - OrderOpenPr  > Point * _StealthStopLoss_))
             //  
                 {    OrderClose(OrderTicket(), QtyOrderSells - QtyForStopExcept , Ask, _SlippageForAbove_, MediumSeaGreen);
                     continue;
               }
            }           
   
   
   
         } 
      } 
   } 
}
 
void DoCloseExcept()  
{
   int Total;
   double QtyOrders = 0.00;
   double QtyOrderSells = 0.00;
   double OrderOpenPr = 0.00;
   double OrderStopLo = 0.00;
   double  _SlippageForAbove_  =  SlippageForAbove*TickMultiplier;
   double  _StopWhenProfit_  =  StopWhenProfit*TickMultiplier;
   double  _MoveStopToProfitOf_  =  MoveStopToProfitOf*TickMultiplier;
   double  _HardStopLoss_  =  HardStopLoss*TickMultiplier;
   
   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() <= OP_SELL)
      {
         IsTrade = True;
         
 //        if(OrderType() == OP_BUY) 
       
//         if(OrderType() == OP_SELL) 
         if(OrderType() == OP_BUY) {
       
 //Close_Lots - Buy
             QtyOrders = OrderLots();
             OrderOpenPr =OrderOpenPrice();
             OrderStopLo = OrderStopLoss();
            if(OrderStopLo > 0 && OrderStopLo <  OrderOpenPr + Point * _HardStopLoss_  && QtyOrders > QtyForStopExcept)
            {                      
               if(Bid - OrderOpenPr == Point * _StopWhenProfit_)
               {
                     OrderClose(OrderTicket(), QtyOrders - QtyForStopExcept , Bid, _SlippageForAbove_, MediumSeaGreen);
                     continue;
               }
            }           
   
      
         }
       
      
         if(OrderType() == OP_SELL) {
         

  //Close_Lots - Sell
  // Sell trades must exit at Ask price   
           QtyOrderSells = OrderLots();
           OrderOpenPr =OrderOpenPrice();
             OrderStopLo = OrderStopLoss();
            if(OrderStopLo > 0 && OrderStopLo <  OrderOpenPr + Point * _HardStopLoss_  && QtyOrders > QtyForStopExcept)
            {                      
               if(OrderOpenPr - Ask == Point * _StopWhenProfit_)
               {
                     OrderClose(OrderTicket(), QtyOrderSells - QtyForStopExcept , Ask, _SlippageForAbove_, MediumSeaGreen);
                     continue;
               }
            }           
   
   
   
         } 
      } 
   } 
}


void DoHardStopLoss()
{
   int Total;
   double QtyOrders = 0.00;
   double QtyOrderSells = 0.00;
   double  _HardStopLoss_  =  HardStopLoss*TickMultiplier;
   double  _TakeProfit_  =  TakeProfit*TickMultiplier;
   
//   double  _MoveStopToProfitOf_  =  _MoveStopToProfitOf_*TickMultiplier;

   Total = OrdersTotal();
   
   //Check position
   bool IsTrade = False;

// Better to do this from highest to lowest
//   for (int i = 0; i < Total; i ++) {
   for (int i = Total - 1; i >= 0; i --) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
//*******************************************
// Important to have code check MagicNumber and Symbol

      if (OrderSymbol() != Symbol()) continue;
      if (OrderMagicNumber() != MagicNumber) continue;
//*******************************************
      
      if(OrderType() > OP_SELL) continue;
      IsTrade = True;
      if(OrderType() == OP_BUY)
        {
         QtyOrders = OrderLots();
         //MoveOnce 
         if(HardStopLoss  > 0)
           {
            if(QtyOrders == Lots)
              {
               if(OrderStopLoss() == 0 )
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() - Point * _HardStopLoss_, OrderOpenPrice() + Point * _TakeProfit_, 0, Red);
                  if(!EachTickMode) BarCount = Bars;
                  continue; 
                 }
              }
           }  
        }
      else
        {
         QtyOrderSells = OrderLots();
         //MoveOnce 
         if(HardStopLoss  > 0)
           {
            if(QtyOrders == Lots)
              {
               if(OrderStopLoss() == 0 )
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(), OrderOpenPrice() + Point * _HardStopLoss_, OrderOpenPrice() - Point * _TakeProfit_, 0, Red);
                  if(!EachTickMode) BarCount = Bars;
                  continue; 
               }
              }
           }
        }
     }
  }
 