//+------------------------------------------------------------------+
//|                                              Marks_NonLag_v1.mq4 |
//|                                  Copyright © 2010, Mark Ellis    |
//|                                        http://www.metaquotes.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, Mark Ellis"
#property link      "http://www.metaquotes.com"
#define Up "Up"
#define Down "Down"
#define Flat "Flat"

//+------------------------------------------------------------------+
//| Assumptions                                                      |
//+------------------------------------------------------------------+
// NonLagMa return value 0 is the price of the MA for charting purposes
// When The return values Up(value 1) and Dn(value 2) from NonLagMA 
//   both hava data, then the MA is in flux (changing direction) and 
//   should not be used for decision making
// For Calculating lows and  Highs equal is included
// When both Long and Short Signal - Stay out !!!!
//+------------------------------------------------------------------+

//---- input parameters
//extern string     SignalDesc                 = "Set to false and No trades will be placed.";
extern bool       MakeTrades                 =  true;
extern bool       DisplayAlert               =  false;
extern bool       DisplayArrow               =  false;
extern color      UpArrowColor               = Blue;
extern color      DownArrowColor             = Red;

extern string     SessionInfo                = "Section on Session Information.";
extern bool       UseSessionTrading          = false;
extern string     SessionTimePeriods         = "Chart times to Open positions";
extern int        StartTradingHour           = 15;
extern int        StartTradingMinute         = 0;
extern int        StopTradingHour            = 23;
extern int        StopTradingMinute          = 0;

extern string     MoneyManagementSection     ="Section on MoneyManagement";
extern string     MMSection1                 ="     Lots will be used unless UseMoneyManagement";
extern string     MMSection2                 ="     is true. If true, Risk percent of account balance";
extern string     MMSection3                 ="     i.e. 10% risk on @10k balance  = 1 lot";
extern double     Lots                       = 1;
extern bool       AutoMoneyManagement        = true;
extern double     PercentToRisk              = 10; 
extern int        AllowedSlippage            = 3;

extern string     StopSection                ="Section on Stops";
extern int        EmergencyStopLoss          = 500;
extern bool       UseFixedStopLoss           = false; // Uses the fixed StopLoss
extern int        FixedStop                  = 24;  // Fixed stop amount in pips

extern string     TakeProfitSection          ="Section on TakeProfit Levels";
extern int        EmergencyTakeProfit        = 500;
extern bool       UseFixedTakeProfit         = false; // Uses the fixed TakeProfit
extern int        FixedTP                    = 50;

extern string     TrackingSection            ="Section on Tracking Trades";
extern int        UniqueEaNumber             = 19600602;
extern string     OrderDescription           = "NonLagMa_v1";
extern bool       DisplayComments            = true;
extern color      CommentsColor              = Black;
extern int        fontsize                   = 10;
extern string     font                       = "Arial"; // "Times New Roman"
extern int        CommentSpacing             = 20;

extern string     SectionOnSignalss          = "Section on Signals";
extern int        NonLagMa_Price             = 0;
extern int        NonLagMa_Length            = 21;
extern int        NonLagMa_Displace          = 0;
extern double     NonLagMa_PctFilter         = 0.0;
extern int        NonLagMa_Color             = 1;
extern int        NonLagMa_ColorBarBack      = 1;
extern double     NonLagMa_Deviation         = 0.0;
extern int        NonLagMa_SoundAlertMode    = 0;


extern string     SectionOnRequirements     = "Section on Requirements";
extern string     SectionOnRequirements1     = "Need the following Indicators named exactly";
extern string     SectionOnRequirements2     = "    NonLagMA";
extern string     SectionOnRequirements3     = "     ";
extern string     SectionOnRequirements4     = "";
   


//for open candle calculation
datetime next_candle;
// running clock
int clock = 182;
//comment variables
string objectName = "";
string commentOrder = "";
string commentStop = "";
string commentTakeProfit = "";
string commentSignalType = "";
string StatusLabel = "";
string label1 = "";
string label2 = "";
string label3 = "";
string label4 = "";
string label5 = "";
//for previous comments (optimaization of EA)
string prevStatusLabel = "";
string prevlabel1 = "";
string prevlabel2 = "";
string prevlabel3 = "";
string prevlabel4 = "";
string prevlabel5 = "";


//for Global IndicatorShortName   
//up values
double   NonLagMa1Up = EMPTY_VALUE;//first return value 1 bar back
double   NonLagMa2Up = EMPTY_VALUE;//first return value 2 bars back
double   NonLagMa3Up = EMPTY_VALUE;//first return value 3 bars back
//dn values
double   NonLagMa1Dn = EMPTY_VALUE;//first return value 1 bar back
double   NonLagMa2Dn = EMPTY_VALUE;//first return value 2 bars back
double   NonLagMa3Dn = EMPTY_VALUE;//first return value 3 bars back
 

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   next_candle=Time[0]+Period();
   objectName = Symbol()+Period()+OrderDescription;
    // Validate proper FractalMovePercentage
 
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   // delete comment objects
    DeleteAllObjects();
    Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   //Check for close on every tick
   //if ((NumberOfOrders>0))  CheckForClose();
   
   // New candle processing
   if(next_candle<=Time[0])
   {
      next_candle=Time[0]+Period();
      // New candle. Your trading functions here
      // set indicator values (for efficiency)
   //NonLagMA Value
     double   NonLagMa1 = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,0,1);//first return value 1 bar back
     double   NonLagMa3 = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,0,3);//first return value 3 bar back
     double   NonLagMa2 = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,0,2);//first return value 2 bars back
   //up values
      NonLagMa1Up = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,1,1);//Second return value 1 bar back
      NonLagMa2Up = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,1,2);//Second return value 2 bars back
      NonLagMa3Up = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,1,3);//Second return value 3 bars back
   //dn values
      NonLagMa1Dn = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,2,1);//Third return value 1 bar back
      NonLagMa2Dn = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,2,2);//Third return value 2 bars back
      NonLagMa3Dn = iCustom(NULL,0,"NonLagMA", NonLagMa_Price,NonLagMa_Length,NonLagMa_Displace,NonLagMa_PctFilter,NonLagMa_Color,NonLagMa_ColorBarBack,NonLagMa_Deviation,NonLagMa_SoundAlertMode,2,3);//Third return value 3 bars back
     
      int NumberOfOrders = CalculateCurrentOrders();
      //Check for close on new candle
      if (NumberOfOrders>0)   CheckForClose();
      if (NumberOfOrders==0)   CheckForOpen();
   }   
   Display_Info();   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Delete All Objects                                               |
//+------------------------------------------------------------------+ 
void DeleteAllObjects()
{
   int objs = ObjectsTotal();
   string name;
   for(int cnt=ObjectsTotal()-1;cnt>=0;cnt--)
   {
      name=ObjectName(cnt);
      if (StringFind(name,objectName,0)>-1) ObjectDelete(name);
      WindowRedraw();
   }
}
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//| Check For Open                                                   |
//+------------------------------------------------------------------+ 
void CheckForOpen()
{
   double   StopLoss, TakeProfit;
   double   Risk = NormalizeDouble((PercentToRisk/100),2);
   bool     LongSignal = false;
   bool     ShortSignal = false;
   bool     ConfirmedSignal = true;  // always true unless checking for confirmation
   bool     validTradingTime = true;// always true unless using session trading time     
   label1 = "";

   //if (Offset>0) Offset=Offset*Point; // convert Offset into pip value for currency
// Valid Trading Time?    
   if (UseSessionTrading)         
   {
    validTradingTime = CheckForValidTradeTime();
   }

//Signal Generation
   //NonLagMA Signals
   if ((NonLagMa1Dn == EMPTY_VALUE && NonLagMa2Dn == EMPTY_VALUE && NonLagMa3Dn != EMPTY_VALUE))// && Close[2] > NonLagMa1Up && Open[2] < NonLagMa1Up)  
   {
      LongSignal = true; 
      if (DisplayArrow) CreateArrow(Up);
      if (DisplayAlert) CreateAlert(Up);
      commentSignalType = "NonLagMa Buy Signal at "+TimeToStr(TimeCurrent(),TIME_MINUTES);
   }
   if ((NonLagMa1Up == EMPTY_VALUE && NonLagMa2Up == EMPTY_VALUE && NonLagMa3Up != EMPTY_VALUE))// && Close[2] < NonLagMa2Dn && Open[2] > NonLagMa2Dn)  
   {
      ShortSignal = true;
      if (DisplayArrow) CreateArrow(Down);
      if (DisplayAlert) CreateAlert(Down);
      commentSignalType = "NonLagMa Sell Signal at "+TimeToStr(TimeCurrent(),TIME_MINUTES);
   }   
   
// Mixed Signals ?
   if (LongSignal && ShortSignal)// both Long and Short Signal - Stay out !!!!
   {
      LongSignal = false;
      ShortSignal = false;
   }
// Calculate trade info
   else // clean signal calculate trade info
   {
    //Calculate Stop Loss value in Pips
      //set emergency Stop and TP
      StopLoss = EmergencyStopLoss;
      TakeProfit = EmergencyTakeProfit;
      //set default Stops
      if (UseFixedStopLoss) StopLoss = FixedStop;
      StopLoss = NormalizeDouble(StopLoss, 0 );
  
    //Calculate Take Profit value in pips
      if (UseFixedTakeProfit) TakeProfit = FixedTP;
      TakeProfit = NormalizeDouble(TakeProfit, 0 );
    
    // Calculate Lot Size  
      if (AutoMoneyManagement)
         Lots = NormalizeDouble(AccountBalance()*Risk/StopLoss/(MarketInfo(Symbol(), MODE_TICKVALUE)),2);
   } // end not mixed signal - calculate trade info
   // Long Signal
   if (LongSignal) // LongSignal
   {
      // Set the comment strings
      commentOrder = "Long @"+Bid;
      commentStop = "Stop = "+StopLoss+" pips @"+(Ask+StopLoss*Point);
      commentTakeProfit = "TakeProfit = "+TakeProfit+" pips @"+(Bid-TakeProfit*Point);
     
      if(validTradingTime)// Valid Trade Session
      {
        if ((ConfirmedSignal) && (MakeTrades))
        {
           OrderSend(Symbol(),OP_BUY,Lots,Ask,AllowedSlippage,Bid-StopLoss*Point,Ask+TakeProfit*Point, OrderDescription,UniqueEaNumber,0,Lime); 
           //Print("Lots ordered : ", DoubleToStr(Lots,8));
           //Print("Tick Value : ",MarketInfo(Symbol(), MODE_TICKVALUE));
           //Print("Account Balance : ",DoubleToStr(AccountBalance(),8));
           //Print("Risk : ",DoubleToStr(Risk,8));
           //Print("PercentRisk : ",DoubleToStr(PercentToRisk,8));
           //Print("StopLoss : ",DoubleToStr(StopLoss,8));
           //Comment("Upper ", upFractal, "   StopLoss ", StopLoss, "   TakeProfit ", TakeProfit, "   Lots ", Lots );      
        }
      }
   }
   
   // Short Signal
   if (ShortSignal) // ShortSignal
   {
     // Set the comment strings
     commentOrder = "Short @"+Ask;
     commentStop = "Stop = "+StopLoss+" pips @"+(Bid-StopLoss*Point);
     commentTakeProfit = "TakeProfit = "+TakeProfit+" pips @"+(Ask+TakeProfit*Point);
     
     if(validTradingTime)// Valid Trade Session
      {
        if ((ConfirmedSignal) && (MakeTrades))
        {
           OrderSend(Symbol(),OP_SELL,Lots,Bid,AllowedSlippage,Ask+StopLoss*Point,Bid-TakeProfit*Point, OrderDescription,UniqueEaNumber,0,Red);
           //Print("Lots ordered : ", DoubleToStr(Lots,8));
           //Print("Tick Value : ",MarketInfo(Symbol(), MODE_TICKVALUE));
           //Print("Account Balance : ",DoubleToStr(AccountBalance(),8));
           //Print("Risk : ",DoubleToStr(Risk,8));
           //Print("PercentRisk : ",DoubleToStr(PercentToRisk,8));
           //Print("StopLoss : ",DoubleToStr(StopLoss,8));
           //Comment("Lower ", dnFractal, "   StopLoss ", StopLoss, "   TakeProfit ", TakeProfit, "   Lots ", Lots );
        }
      }
   }
      
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Check if I should Close an Order                                  |
//+------------------------------------------------------------------+
void CheckForClose()
{       
//=============== CHECK CLOSE/TRAILING STOP ORDERS  

   int total = OrdersTotal();
   
   for(int cnt=0;cnt<total;cnt++)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      //select only orders for this currency and MagicNumber and OrderDesription
      if((OrderType() <= OP_SELL) && (OrderSymbol() == Symbol()) && (OrderMagicNumber() == UniqueEaNumber) && (OrderComment() == OrderDescription))
      {
         //if buy order
         if(OrderType() == OP_BUY)
         {
            // if lower highs on last two closed candles
            if ((High[1] <= High[3]) && (High[2] <= High[3])) 
            {
               //Print("CloseOrder reason: lower highs on last 2 candles.");
               OrderClose(OrderTicket(),OrderLots(),Bid,AllowedSlippage,Blue);
               commentStop = "CloseOrder reason: lower highs on last 2 candles.";
               commentTakeProfit = "CloseOrder reason: lower highs on last 2 candles.";
            }
            // if NonLagMa changes color (to red) for 2 closed candles
            if ((NonLagMa1Dn != EMPTY_VALUE && NonLagMa2Dn != EMPTY_VALUE)&&(NonLagMa1Up == EMPTY_VALUE && NonLagMa2Up == EMPTY_VALUE)) // on price went below current alf
            {
               //Print("CloseOrder reason Broke Current Alf="+Alf);
               OrderClose(OrderTicket(),OrderLots(),Bid,AllowedSlippage,Blue);
               commentStop = "CloseOrder reason: NonLagMa change color on last 2 closed candles";
               commentTakeProfit = "CloseOrder reason: NonLagMa change color on last 2 closed candles";
            }            
            //add other close reasons here                  
         }
         // if sell order
         if(OrderType() == OP_SELL)
         {
            // if higher lows on last two closed candles
            if ((Low[1] >= Low[3]) && (Low[2] >= Low[3])) 
            {
               //Print("CloseOrder reason: higher lows on last 2 candles.");
               OrderClose(OrderTicket(),OrderLots(),Bid,AllowedSlippage,Blue);
               commentStop = "CloseOrder reason: higher lows on last 2 candles.";
               commentTakeProfit = "CloseOrder reason: higher lows on last 2 candles.";
            }
            // if NonLagMa changes color (to green) for 2 closed candles
            if ((NonLagMa1Up != EMPTY_VALUE && NonLagMa2Up != EMPTY_VALUE)&&(NonLagMa1Dn == EMPTY_VALUE && NonLagMa2Dn == EMPTY_VALUE)) // on price went below current alf
            {
               //Print("CloseOrder reason Broke Current Alf="+Alf);
               OrderClose(OrderTicket(),OrderLots(),Bid,AllowedSlippage,Blue);
               commentStop = "CloseOrder reason: NonLagMa change color on last 2 closed candles";
               commentTakeProfit = "CloseOrder reason: NonLagMa change color on last 2 closed candles";
            }            
            //add other close reasons here  
         }
      }
    }
}// end Check For Close
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Check For Valid Trading Time                                     |
//+------------------------------------------------------------------+ 
bool CheckForValidTradeTime()
{
   bool valid = true;// assume is a valid trading time then check
   string startTime,stopTime;
   startTime = StartTradingHour+":"+StartTradingMinute;
   stopTime = StopTradingHour+":"+StopTradingMinute;
   //Correct display if single digit minute
   if (StartTradingMinute < 10) startTime = StartTradingHour+":0"+StartTradingMinute;
   if (StopTradingMinute < 10) stopTime = StopTradingHour+":0"+StopTradingMinute;
   label1 = "Trading Session  "+startTime+" - "+stopTime;
   
   // take of of trading when start time is < end Time
   if (StartTradingHour <= StopTradingHour)
   {
      if (Hour() < StartTradingHour) valid = false;
      if ((Hour() == StartTradingHour) && (Minute() < StartTradingMinute)) valid = false;
      if (Hour() > StopTradingHour) valid = false;
      if ((Hour() == StopTradingHour) && (Minute() > StopTradingMinute)) valid = false;      
   }
   else if (StartTradingHour > StopTradingHour)
   {
      if ((Hour() < StartTradingHour) && (Hour() > StopTradingHour)) valid = false;
      if ((Hour() == StartTradingHour) && (Minute() < StartTradingMinute)) valid = false;
      //if ((Hour() > StopTradingHour) && (Hour() > 0 )) valid = false;
      if ((Hour() == StopTradingHour) && (Minute() > StopTradingMinute)) valid = false; 
   }
   else if ((StartTradingHour == StopTradingHour) && (StartTradingMinute == StopTradingMinute))
   {
      label1 = "Trading Session Time is 24Hrs a day";
      valid = true;
   }

   return(valid);   
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders()
{
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==UniqueEaNumber && OrderComment()==OrderDescription)
      {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
      }
   }
   return(buys+sells);
}

//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Display Information on the EA                                    |
//+------------------------------------------------------------------+
void Display_Info()
{
   //draw comment lines
   
   clock++;
   if(clock>194)
   {
      clock=183;
   }  
    if(ObjectFind(objectName+"Clock")==-1)
   {
      ObjectCreate(objectName+"Clock",OBJ_LABEL,0,0,0,0,0,0,0);
      ObjectSetText(objectName+"Clock",CharToStr(clock),14,"Wingdings",CommentsColor);
      ObjectSet(objectName+"Clock",OBJPROP_XDISTANCE,0);
      ObjectSet(objectName+"Clock",OBJPROP_YDISTANCE,20);
   }
   else
   {
      ObjectDelete(objectName+"Clock");
      ObjectCreate(objectName+"Clock",OBJ_LABEL,0,0,0,0,0,0,0);
      ObjectSetText(objectName+"Clock",CharToStr(clock),14,"Wingdings",CommentsColor);
      ObjectSet(objectName+"Clock",OBJPROP_XDISTANCE,0);
      ObjectSet(objectName+"Clock",OBJPROP_YDISTANCE,20);
   }
   
   if(CalculateCurrentOrders()!= 0)
   {
      //StatusLabel = commentOrder+" : "+commentStop+" : "+commentTakeProfit;
      StatusLabel = "In Trade ... ";
      label1 = commentOrder;
      label2 = commentStop;
      label3 = commentTakeProfit;
   }
   else
   {
      StatusLabel = "Status: Waiting for Buy/Sell opportunity.";
      label2 = " ";
      label3 = " ";
   }
   if ((StatusLabel!="") && (StatusLabel != prevStatusLabel))
   {
      if(ObjectFind(objectName+"Status")==-1)
      {
         ObjectCreate(objectName+"Status",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"Status",StatusLabel,fontsize,font,CommentsColor);
         ObjectSet(objectName+"Status",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"Status",OBJPROP_YDISTANCE,40);
      }
      else
      {
         ObjectDelete(objectName+"Status");
         ObjectCreate(objectName+"Status",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"Status",StatusLabel,fontsize,font,CommentsColor);
         ObjectSet(objectName+"Status",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"Status",OBJPROP_YDISTANCE,40);
      }
      prevStatusLabel = StatusLabel;
   }
   if ((label1!="") && (label1!= prevlabel1))
   {
      if(ObjectFind(objectName+"1")==-1)
      {
         ObjectCreate(objectName+"1",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"1",label1,fontsize,font,CommentsColor);
         ObjectSet(objectName+"1",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"1",OBJPROP_YDISTANCE,60);
      }
      else
      {
         ObjectDelete(objectName+"1");
         ObjectCreate(objectName+"1",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"1",label1,fontsize,font,CommentsColor);
         ObjectSet(objectName+"1",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"1",OBJPROP_YDISTANCE,60);
      }
      prevlabel1 = label1;
   } 
   if ((label2!="") && (label2!= prevlabel2))
   {
      if(ObjectFind(objectName+"2")==-1)
      {
         ObjectCreate(objectName+"2",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"2",label2,fontsize,font,CommentsColor);
         ObjectSet(objectName+"2",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"2",OBJPROP_YDISTANCE,80);
      }
      else
      {
         ObjectDelete(objectName+"2");
         ObjectCreate(objectName+"2",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"2",label2,fontsize,font,CommentsColor);
         ObjectSet(objectName+"2",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"2",OBJPROP_YDISTANCE,80);
      }  
      prevlabel2 = label2;
   } 
   if ((label3!="") && (label3!= prevlabel3))
   {
      if(ObjectFind(objectName+"3")==-1)
      {
         ObjectCreate(objectName+"3",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"3",label3,fontsize,font,CommentsColor);
         ObjectSet(objectName+"3",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"3",OBJPROP_YDISTANCE,100);
      }
      else
      {
         ObjectDelete(objectName+"3");
         ObjectCreate(objectName+"3",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"3",label3,fontsize,font,CommentsColor);
         ObjectSet(objectName+"3",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"3",OBJPROP_YDISTANCE,100);
      }
      prevlabel3 = label3;
   } 
   if ((label4!="") && (label4!= prevlabel4))
   {
      if(ObjectFind(objectName+"4")==-1)
      {
         ObjectCreate(objectName+"4",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"4",label4,fontsize,font,CommentsColor);
         ObjectSet(objectName+"4",OBJPROP_XDISTANCE,0);
         ObjectSet(objectName+"4",OBJPROP_YDISTANCE,120);
      }
      else
      {
         ObjectDelete(objectName+"4");
         ObjectCreate(objectName+"4",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"4",label4,fontsize,font,CommentsColor);
         ObjectSet(objectName+"4",OBJPROP_XDISTANCE,0);
         ObjectSet(objectName+"4",OBJPROP_YDISTANCE,120);
      }
      prevlabel4 = label4;
   } 
   if ((label5!="") && (label4!= prevlabel5))
   {
      if(ObjectFind(objectName+"5")==-1)
      {
         ObjectCreate(objectName+"5",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"5",label5,fontsize,font,CommentsColor);
         ObjectSet(objectName+"5",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"5",OBJPROP_YDISTANCE,140);  
      }
      else
      {
         ObjectDelete(objectName+"5");
         ObjectCreate(objectName+"5",OBJ_LABEL,0,0,0,0,0,0,0);
         ObjectSetText(objectName+"5",label5,fontsize,font,CommentsColor);
         ObjectSet(objectName+"5",OBJPROP_XDISTANCE,5);
         ObjectSet(objectName+"5",OBJPROP_YDISTANCE,140);  
      }   
      prevlabel5 = label5;
   } 
   return(0);
}

//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Create Signal on the EA                                          |
//+------------------------------------------------------------------+
void CreateArrow(string direction)
{
   datetime now = TimeCurrent();
   ObjectDelete(objectName+"SignalArrow"+now);
   ObjectCreate(objectName+"SignalArrow"+now,OBJ_ARROW,0,Time[1],Open[0],0,0,0,0);
      
   if (direction == Up)
   {
      //ObjectCreate(objectName+"SignalArrow"+now,OBJ_ARROW,0,Time[1],Open[0],0,0,0,0);
      ObjectSet(objectName+"SignalArrow"+now, OBJPROP_ARROWCODE, 241);// 1; //241;
      ObjectSet(objectName+"SignalArrow"+now, OBJPROP_COLOR, UpArrowColor);
   }
   if (direction == Down)
   {
      //ObjectCreate(objectName+"SignalArrow"+now,OBJ_ARROW,0,Time[1],Open[0],0,0,0,0);
      ObjectSet(objectName+"SignalArrow"+now, OBJPROP_ARROWCODE, 242); //2; //242;
      ObjectSet(objectName+"SignalArrow"+now, OBJPROP_COLOR, DownArrowColor);
   }

   return(0);
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Create Signal on the EA                                          |
//+------------------------------------------------------------------+
void CreateAlert(string direction)
{
   datetime now = TimeCurrent();
   string AlertMessage = Symbol()+Period()+OrderDescription+direction;
   
   Alert(AlertMessage);

   return(0);
}

//+------------------------------------------------------------------+