
#define MA_XX 0   //Default State
#define MA_UP 1   //Up Trend
#define MA_DN 2   //Down Trend
#define ErrRet -1 //Invalid or Error Return from function

#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4


int MagicNumber = 839846;
extern string lbl1 = "--Strategy Management--";
extern bool IndicatorTickMode = False; //True=Open Trade imediately after signal appear, False=Open Trade if signal appear on new bar
extern int Fast.MA.Period = 1;
extern int Slow.MA.Period = 34;
extern int  Signal.period = 5;
extern double StopLoss =30;      //Fixed StopLoss
extern double PipsTo0.00 = 5;
extern double MinProfitLock = 1; //OpenPrice + MinStopLevel + MinProfitLock, disable set to 0
extern double TakeProfit1 =15;   //OpenPrice + MinStopLevel + TP1, disable set to 0
extern double TakeProfit2 =30;   //OpenPrice + MinStopLevel + TP2, disable set to 0
extern double TakeProfit3 =45;   //OpenPrice + MinStopLevel + TP3, disable set to 0
extern double TakeProfit4 =60;  //OpenPrice + MinStopLevel + TP4, disable set to 0
extern bool TradeAfterProfitTaking = True;
extern bool HedgingAllow = True;
extern bool ReserveTradeOrder=false; 
extern int MaxNoOfBuyTrade = 5;  
extern int MaxNoOfSellTrade = 5;
extern string lbl2 = "--Time Management--";
extern bool EnableTradeTime=False;  //If true EA trade within Time_Start and Time_Stop
extern int Time_Start=0100;         //Time Start follow Broker Time
extern int Time_Stop=2300;          //Time Stop follow Broker Time

extern string lbl3 = "--Money Management--";
extern double FixedLotSize     = 0.1;  

bool SignalMail = False;
bool EachTickMode = True; //if set to False, TradeAfterProfitTaking will not working!
int Slippage = 3;
int BarCount;
int Current;
bool TickCheck = True;

bool IsTradingTime=False;
datetime PreBarTime;
bool NotSameBar=True;
double dblStep;
double dblMinLot;
double dblMaxLot;
double dblContractSize;
double DecPoint;
double DecDigit;
int intLeverage;
int intSpread;
double dblSpread;
int DecPt;
int intMinStopLevel;
double OrderLotSizes;
bool EnableEA = FALSE;
double dblSellSignal,dblBuySignal;
double dblSL,dblTP;
double curAskPrice, curBidPrice;
bool BuyModifyOK,SellModifyOK;
int curBuyTradeOpened=0,curSellTradeOpened=0;
int preBuyTradeOpened=0,preSellTradeOpened=0;
int TicketNo=0;
double LastTradeProfit=0;
bool CloseByTP=false;
int Order=SIGNAL_NONE;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;

   if (dblStep == 0.01) DecPt = 2;
   else DecPt = 1;  

   if (Digits < 4) {
      DecPoint = 0.01;
      DecDigit = 2;
   } else {
      DecPoint = 0.0001;
      DecDigit = 4;
   }

   
   intMinStopLevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   intLeverage = AccountLeverage();
   intSpread = MarketInfo(Symbol(), MODE_SPREAD);
   dblSpread = MathCeil((intSpread * Point)/DecPoint);
   dblStep = NormalizeDouble(MarketInfo(Symbol(), MODE_LOTSTEP), 2);
   dblMinLot = NormalizeDouble(MarketInfo(Symbol(), MODE_MINLOT), 2);
   dblMaxLot = NormalizeDouble(MarketInfo(Symbol(), MODE_MAXLOT), 2);
   dblContractSize=NormalizeDouble(MarketInfo(Symbol(),MODE_LOTSIZE),2);
   
   Print("dblSpread:"+dblSpread);
   
   //ObjectsDeleteAll( 0, OBJ_HLINE);
   //ObjectsDeleteAll( 0, OBJ_TEXT); 
   return (0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {
   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() 
{
   SMA_CrossOver_EA();
   return (0);
}

int SMA_CrossOver_EA() {
   
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;

   if (EachTickMode && Bars != BarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+
   if(IsNotValidTradingTime(Time_Start,Time_Stop)==1 && EnableTradeTime==True)
   {
      CommentTL(1, "EA Stop Open New Trade, Trade Time Not Allowed!", Red);
      IsTradingTime=False;
   }
   else
   {  
      CommentTL(1, "EA Running!", Lime);
      IsTradingTime = True;
   }

    curAskPrice = Ask;
    curBidPrice = Bid; 
 
   dblSellSignal=iCustom(NULL, 0, "SMA CrossOver",IndicatorTickMode,Fast.MA.Period,Slow.MA.Period,Signal.period, 0, 1); 
   dblBuySignal=iCustom(NULL, 0, "SMA CrossOver",IndicatorTickMode,Fast.MA.Period,Slow.MA.Period,Signal.period, 1, 1); 
   //if(dblSellSignal!=EMPTY_VALUE && NotSameBar==true)   Print(TimeToStr(Time[0],TIME_MINUTES)+",Sell:"+dblSellSignal);
   //if(dblBuySignal!=EMPTY_VALUE && NotSameBar==true) Print(TimeToStr(Time[0],TIME_MINUTES)+",Buy:"+dblBuySignal);
   
   CommentTL(2, "BuyTradeOpened("+MaxNoOfBuyTrade+"):"+ curBuyTradeOpened, Yellow);
   CommentTL(3, "SellTradeOpened("+MaxNoOfBuyTrade+"):"+ curSellTradeOpened, Yellow);
   CommentTL(4, "Hedging Allow:" + BPrint(HedgingAllow), Yellow);
   
   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+
   
   //Check position
   bool IsTrade = False;
   
   curBuyTradeOpened=0;curSellTradeOpened=0;
   for (int i = 0; i < Total; i ++)
   {        
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
      {
         IsTrade = True;
         if(OrderType() == OP_BUY)
         {
            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+
               curBuyTradeOpened++;
               double BuyObjPrice = ObjectGet(DoubleToStr(OrderTicket(),0), OBJPROP_PRICE1);
               if(BuyObjPrice==0) BuyObjPrice = OrderStopLoss();
               
               if(Bid <= BuyObjPrice)  Order = SIGNAL_CLOSEBUY;
               
            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+
            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount))))
            {
               bool BuyCloseOK = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumBlue);  
               if(BuyCloseOK == True) 
               {
                  Print("Buy Ticket#"+OrderTicket()+" Closed.");
                  ObjectDelete(DoubleToStr(OrderTicket(),0));
                  ObjectDelete(OrderTicket()+"_txt");
               }
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }//end if
            
            //Move Stop Loss to Break Even DecPoint       
            BuyModifyStopLossLevel();
        } 
        else
        {
            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Sell)                                          |
            //+------------------------------------------------------------------+
               curSellTradeOpened++;
               
               double SellObjPrice = ObjectGet(DoubleToStr(OrderTicket(),0), OBJPROP_PRICE1);
               if(SellObjPrice==0) SellObjPrice = OrderStopLoss();
               
               if(Ask >= SellObjPrice) Order = SIGNAL_CLOSESELL;
               
            //+------------------------------------------------------------------+
            //| Signal End(Exit Sell)                                            |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSESELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount))))
            {
               bool SellCloseOK = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Crimson);  
               if(SellCloseOK == True) 
               {
                  Print("Sell Ticket#"+OrderTicket()+" Closed.");
                  ObjectDelete(DoubleToStr(OrderTicket(),0));
                  ObjectDelete(OrderTicket()+"_txt");
               }
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Close Sell");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }//end if
            
            //Move Stop Loss to Break Even DecPoint      
            SellModifyStopLossLevel();
            
         }//end if
      }//end if
   }//end for

   //+------------------------------------------------------------------+
   //| Signal Begin(Entry Condition)                                              |
   //+------------------------------------------------------------------+
   
   //This portion is handle Open Buy Position for TradeAfterProfitTaking function
   if(preBuyTradeOpened!=curBuyTradeOpened )
   {
      //Print("PreBuyTradeOpened:"+ preBuyTradeOpened +", curBuyTradeOpened:"+curBuyTradeOpened);
      TicketNo=0;
      LastTradeProfit=0;
      CloseByTP=false;
      
      TicketNo = LastClosedTradeProfit(OP_BUY, LastTradeProfit, CloseByTP);
      
      if (CloseByTP == True && preBuyTradeOpened>curBuyTradeOpened && TradeAfterProfitTaking==True)SetBuyTrade();
      if (CloseByTP == True) 
      {  
         Print("Buy Ticket#"+ TicketNo +", Take Profit!, Profit:"+ DoubleToStr(LastTradeProfit,2)); 
         ObjectDelete(DoubleToStr(OrderTicket(),0));
         ObjectDelete(OrderTicket()+"_txt");
      }
                  
      preBuyTradeOpened=curBuyTradeOpened;
   }//end if 
       
   //This portion handles Open Sell Position for TradeAfterProfitTaking function
   if(preSellTradeOpened!=curSellTradeOpened && TradeAfterProfitTaking==True)
   {
      //Print("PreSellTradeOpened:"+ preSellTradeOpened +", curSellTradeOpened:"+curSellTradeOpened);
      TicketNo=0;
      LastTradeProfit=0;
      CloseByTP=false;
      
      TicketNo = LastClosedTradeProfit(OP_SELL, LastTradeProfit, CloseByTP);
        
      if (CloseByTP == True && preSellTradeOpened>curSellTradeOpened)   SetSellTrade();
      if (CloseByTP == True) 
      {  
         Print("Sell Ticket#"+ TicketNo +", Take Profit!, Profit:"+ DoubleToStr(LastTradeProfit,2)); 
         ObjectDelete(DoubleToStr(OrderTicket(),0));
         ObjectDelete(OrderTicket()+"_txt");
      }
      
      preSellTradeOpened=curSellTradeOpened;
   }//end if
   
   //if(IsNewBar()==true)
   {
   //This Portion handles indicator Buy Signal
   if (NotSameBar==true
       && dblBuySignal!=EMPTY_VALUE  
       && curBuyTradeOpened < MaxNoOfBuyTrade
       ) 
       {
            if(ReserveTradeOrder == False && HedgingAllow ==False && curSellTradeOpened > 0) return (0);
            if(ReserveTradeOrder == True && HedgingAllow ==False && curBuyTradeOpened > 0) return (0);
            
            if(ReserveTradeOrder == False)   SetBuyTrade();
            else SetSellTrade();
       }//end if
       
   //This Portion handles indicator Sell Signal
   if (NotSameBar==true
       //&& IsNewBar()==true
       && dblSellSignal!=EMPTY_VALUE  
       && curSellTradeOpened < MaxNoOfSellTrade
       ) 
      {
         if(ReserveTradeOrder == False && HedgingAllow ==False && curBuyTradeOpened > 0) return (0);
         if(ReserveTradeOrder == True && HedgingAllow ==False && curSellTradeOpened > 0) return (0);
            
         if(ReserveTradeOrder == False)   SetSellTrade();
         else  SetBuyTrade();   
      }//end if
   }

   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+

   //Check & Record for same candle bar time to avoid open same position at one candle bar
   if(PreBarTime!=Time[0])
   {
        NotSameBar=True;
        PreBarTime=Time[0]; 
   }
   
   //Buy Order Send
   if (IsTradingTime==TRUE && Order == SIGNAL_BUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      {
         Ticket = OrderSend(Symbol(), OP_BUY, OrderLotSizes , Ask, Slippage, dblSL , dblTP , "Buy(#" + MagicNumber + ")", MagicNumber, 0, Blue);
         if(Ticket > 0)
         {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES))
            {
              if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Ask, Digits) + " Open Buy");
              NotSameBar=false;
			   }
			   else 
			   {
				  Print("Error opening BUY order : ", GetLastError());
			   }
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         return(0);
      }
   }

   //Sell Order Send
   if (IsTradingTime==TRUE && Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      {
               
         Ticket = OrderSend(Symbol(), OP_SELL, OrderLotSizes , Bid, Slippage,  dblSL , dblTP , "Sell(#" + MagicNumber + ")", MagicNumber, 0, Red);
         if(Ticket > 0) 
         {
            if (OrderSelect(Ticket, SELECT_BY_TICKET, MODE_TRADES))
            {
              if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Open Sell");
              NotSameBar=false;
			   }
			   else
			   {
				  Print("Error opening SELL order : ", GetLastError());
			   }
         }
         if (EachTickMode) TickCheck = True;
         if (!EachTickMode) BarCount = Bars;
         
         return(0);
      }
   }

   if (!EachTickMode) BarCount = Bars;

   return(0);
}

int BuyModifyStopLossLevel()
{
            double BuyTPinPips = (Bid - OrderOpenPrice());
            double BuySLinPips = (Bid - OrderStopLoss());
            double BuyTP_curPrice = 0;
            double BuyObjPrice = 0; 
            double BuyTargetLevel1= (dblSpread + PipsTo0.00 ) * DecPoint;
            double BuyTargetLevel2= (TakeProfit1 + PipsTo0.00 ) * DecPoint;
            double BuyTargetLevel3= (TakeProfit2 + PipsTo0.00 ) * DecPoint;
            double BuyTargetLevel4= (TakeProfit3 + PipsTo0.00 ) * DecPoint;
            
            int BuyModifyLevel = 0;
            if( BuyTPinPips > BuyTargetLevel1 &&  BuyTargetLevel1 < BuySLinPips +BuyTargetLevel1)
            {
               BuyModifyLevel = 1;
               if ( BuyTPinPips > BuyTargetLevel2  &&  BuyTargetLevel2 < BuySLinPips + BuyTargetLevel2) 
               {
                  BuyModifyLevel = 2;
                  if ( BuyTPinPips > BuyTargetLevel3 &&  BuyTargetLevel3 < BuySLinPips + BuyTargetLevel3) 
                  {
                     BuyModifyLevel = 3;
                     if ( BuyTPinPips > BuyTargetLevel4 &&  BuyTargetLevel4 < BuySLinPips + BuyTargetLevel4)
                     {
                        BuyModifyLevel = 4;
                     }//end if 
                  }//end if
               }//end if
            }//end if
               
            BuyObjPrice = ObjectGet(DoubleToStr(OrderTicket(),0), OBJPROP_PRICE1);
            if(BuyObjPrice==0) BuyObjPrice = OrderStopLoss();
                              
            switch(BuyModifyLevel)
            {
            case 1:
                  BuyTP_curPrice = OrderOpenPrice() + MinProfitLock * DecPoint;
                  if(Bid > BuyTP_curPrice  && BuyObjPrice<BuyTP_curPrice) 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (BuyTP_curPrice), Time[24], (BuyTP_curPrice), RoyalBlue, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (BuyTP_curPrice + (3*Point)), Time[24],(BuyTP_curPrice+ (3*Point)), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+BuyModifyLevel, "Arial", 7, White);
                      Print("Buy Ticket#"+OrderTicket() +" MinProfitLock Locked OK!");
                  }
                  break; 
            case 2:
                  BuyTP_curPrice = OrderOpenPrice() + (TakeProfit1 + MinProfitLock) * DecPoint;
                  if(Bid > BuyTP_curPrice && BuyObjPrice < BuyTP_curPrice ) 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (BuyTP_curPrice), Time[24], (BuyTP_curPrice), RoyalBlue, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (BuyTP_curPrice+ (3*Point)), Time[24],(BuyTP_curPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+BuyModifyLevel, "Arial", 7, White);
                      Print("Buy Ticket#"+OrderTicket() +" TakeProfit1 Locked OK!");
                  }
                  break;   
            case 3:
                  BuyTP_curPrice = OrderOpenPrice() + (TakeProfit2 + MinProfitLock) * DecPoint;
                  if(Bid > BuyTP_curPrice && BuyObjPrice  < BuyTP_curPrice) 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (BuyTP_curPrice), Time[24], (BuyTP_curPrice), RoyalBlue, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (BuyTP_curPrice+ (3*Point)), Time[24],(BuyTP_curPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+BuyModifyLevel, "Arial", 7, White);                  
                      Print("Buy Ticket#"+OrderTicket() +" TakeProfit2 Locked OK!");
                  }
                  break;
            case 4:
                  BuyTP_curPrice = OrderOpenPrice() + (TakeProfit3 + MinProfitLock) * DecPoint;
                  if( Bid > BuyTP_curPrice && BuyObjPrice  < BuyTP_curPrice ) 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (BuyTP_curPrice), Time[24], (BuyTP_curPrice), RoyalBlue, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (BuyTP_curPrice+ (3*Point)), Time[24],(BuyTP_curPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+BuyModifyLevel, "Arial", 7, White);                  
                      Print("Buy Ticket#"+OrderTicket() +" TakeProfit3 Locked OK!");
                  }
                  break;
            }//end switch
}

int SellModifyStopLossLevel()
{
            double SellTPinPips = (OrderOpenPrice() - Ask);
            double SellSLinPips = (OrderStopLoss() - Ask);
            double SellProfitLvlPrice = 0;
            double SellObjPrice = 0; 
            
            double SellTargetLevel1= (dblSpread + PipsTo0.00 ) * DecPoint;
            double SellTargetLevel2= (TakeProfit1 + PipsTo0.00 ) * DecPoint;
            double SellTargetLevel3= (TakeProfit2 + PipsTo0.00 ) * DecPoint;
            double SellTargetLevel4= (TakeProfit3 + PipsTo0.00 ) * DecPoint;
            
            int SellModifyLevel = 0;
            if( SellTPinPips > SellTargetLevel1 &&  SellTargetLevel1 < SellSLinPips - SellTargetLevel1)
            {
               SellModifyLevel = 1;
               if ( SellTPinPips > SellTargetLevel2  &&  SellTargetLevel2 < SellSLinPips - SellTargetLevel2) 
               {
                  SellModifyLevel = 2;
                  if ( SellTPinPips > SellTargetLevel3 &&  SellTargetLevel3 < SellSLinPips - SellTargetLevel3) 
                  {
                     SellModifyLevel = 3;
                     if ( SellTPinPips > SellTargetLevel4 &&  SellTargetLevel4 < SellSLinPips - SellTargetLevel4)
                     {
                        SellModifyLevel = 4;
                     }//end if 
                  }//end if
               }//end if
            }//end if
            
            
               SellObjPrice = ObjectGet(DoubleToStr(OrderTicket(),0), OBJPROP_PRICE1);
               if(SellObjPrice==0) SellObjPrice = OrderStopLoss();
                
            switch(SellModifyLevel)
            {
            case 1:
                  SellProfitLvlPrice = OrderOpenPrice() - MinProfitLock * DecPoint;
                  if(Ask < SellProfitLvlPrice  && SellObjPrice>SellProfitLvlPrice)                 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (SellProfitLvlPrice), Time[24], (SellProfitLvlPrice), Crimson, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (SellProfitLvlPrice+ (3*Point)), Time[24],(SellProfitLvlPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+SellModifyLevel, "Arial", 7, White);
                      Print("Sell Ticket#"+OrderTicket() +" MinProfitLock Locked OK!");
                  }
                  break; 
            case 2:
                  SellProfitLvlPrice = OrderOpenPrice() - (TakeProfit1 + MinProfitLock ) * DecPoint;
                  if(Ask < SellProfitLvlPrice  && SellObjPrice>SellProfitLvlPrice)                 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (SellProfitLvlPrice), Time[24], (SellProfitLvlPrice), Crimson, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (SellProfitLvlPrice+ (3*Point)), Time[24],(SellProfitLvlPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+SellModifyLevel, "Arial", 7, White);
                      Print("Sell Ticket#"+OrderTicket() +" TakeProfit1 Locked OK!");
                  }
                  break;   
            case 3:
                  SellProfitLvlPrice = OrderOpenPrice() - (TakeProfit2 + MinProfitLock ) * DecPoint;
                  if(Ask < SellProfitLvlPrice  && SellObjPrice>SellProfitLvlPrice)                 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (SellProfitLvlPrice), Time[24], (SellProfitLvlPrice), Crimson, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (SellProfitLvlPrice+ (3*Point)), Time[24],(SellProfitLvlPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+SellModifyLevel, "Arial", 7, White);
                      Print("Sell Ticket#"+OrderTicket() +" TakeProfit2 Locked OK!");
                  }
                  break;  
            case 4:
                  SellProfitLvlPrice = OrderOpenPrice() - (TakeProfit3 + MinProfitLock ) * DecPoint;
                  if(Ask < SellProfitLvlPrice  && SellObjPrice>SellProfitLvlPrice)                 
                  {
                      MoveObject(OrderTicket(), OBJ_HLINE, Time[24], (SellProfitLvlPrice), Time[24], (SellProfitLvlPrice), Crimson, 1, 0);
                      MoveObject(OrderTicket()+"_txt", OBJ_TEXT, Time[24], (SellProfitLvlPrice+ (3*Point)), Time[24],(SellProfitLvlPrice), White);
                      SetObjectText(OrderTicket()+"_txt", "#"+OrderTicket()+" Level:"+SellModifyLevel, "Arial", 7, White);
                      Print("Sell Ticket#"+OrderTicket() +" TakeProfit3 Locked OK!");
                  }
                  break; 
            }//end switch
}

//select the latest opened trade
int LastClosedTradeProfit(int OrdType, double &Order_Profit, bool &CloseByTP)
{  
   for(int i=OrdersHistoryTotal()-1;i>=0;i--)
   {
      if (OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)!= 0 && OrderSymbol() == Symbol() && OrderMagicNumber()== MagicNumber && OrderType()==OrdType)
      {
         if( MathAbs(OrderTakeProfit() - OrderClosePrice()) <= Slippage*DecPoint )
            {
               Order_Profit = OrderProfit();
               CloseByTP=true;
               return (OrderTicket());
               break;
            }
            else
            {
               Order_Profit = OrderProfit();
               CloseByTP=false;
               return (OrderTicket());
               break;
            }
            //end if
      }//end if
   }//end for 
   return(0); 
}

int SetBuyTrade()
{
   if(TakeProfit4 == 0) dblTP = 0;
   else dblTP = Ask + TakeProfit4 * DecPoint;
         
   if(StopLoss == 0) dblSL = 0;
   else dblSL = Ask - StopLoss * DecPoint; 
         
   OrderLotSizes= FixedLotSize;
   Order = SIGNAL_BUY;  
}
int SetSellTrade()
{
   if(TakeProfit4 == 0) dblTP = 0;
   else dblTP = Bid - TakeProfit4 * DecPoint;
         
   if(StopLoss == 0) dblSL = 0;
   else dblSL = Bid + StopLoss * DecPoint; 
         
   OrderLotSizes= FixedLotSize;
   Order = SIGNAL_SELL;
}
//+------------------------------------------------------------------+
int IsNotValidTradingTime(int TimeIn, int TimeOut) {
   //int TradeTime = 100 * Hour() + Minute();
   int TradeTime = 100*TimeHour(TimeLocal())+TimeMinute(TimeLocal());
   if (TimeIn <= TimeOut) {
      if (TradeTime < TimeIn || TradeTime > TimeOut) return (1);
   } else
      if (TradeTime > TimeOut && TradeTime < TimeIn) return (1);
   return (0);
}

double MMLots(double EntryPrice,double SL, double dblRiskRatio, double dblAccMargin, int &OutOfMinMaxMarginRequire)
{
   double SL_Pips;
   
   SL_Pips=MathAbs(EntryPrice-SL)/DecPoint;
   
  //return(NormalizeLots(dblRiskRatio * dblAccMargin / MarketInfo(Symbol(), MODE_MARGINREQUIRED) / (AccountLeverage() / 100.0), OutOfMinMaxMarginRequire));
  return(NormalizeLots(dblRiskRatio * dblAccMargin /( SL_Pips * MarketInfo( Symbol(), MODE_TICKVALUE ) ), OutOfMinMaxMarginRequire));
}

double NormalizeLots(double dblActualMarginRequire, int &intOutOfMinMaxMarginRequire) {
   double dblLotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   double dblMinLot = MarketInfo(Symbol(), MODE_MINLOT);
   double dblMaxLot = MarketInfo(Symbol(), MODE_MAXLOT);
   double dblLegalLotSize = MathCeil(dblActualMarginRequire / dblLotStep) * dblLotStep;
   intOutOfMinMaxMarginRequire = 0;
   if (dblLegalLotSize < dblMinLot) {
      dblLegalLotSize = dblMinLot;
      intOutOfMinMaxMarginRequire = -1;
   }
   if (dblLegalLotSize > dblMaxLot) {
      dblLegalLotSize = dblMaxLot;
      intOutOfMinMaxMarginRequire = 1;
   }
   return (dblLegalLotSize);
}


string tf2txt(int TF2Txt) {
   switch (TF2Txt) {
   case 1:
      return ("M1");
   case 5:
      return ("M5");
   case 15:
      return ("M15");
   case 30:
      return ("M30");
   case 60:
      return ("H1");
   case 240:
      return ("H4");
   case 1440:
      return ("D1");
   case 10080:
      return ("W1");
   case 43200:
      return ("MN");
   }
   return ("??");
}


string UpOrDn (double Number)
{
   if (Number == 1) return ("Trend UP");
   else if (Number == 2) return ("Trend DN");
   else return ("Sideway");
}

int CommentTL(int line, string MsgDsply, color colour)
{
//----   
   ObjectCreate("TpLf_Label" + line, OBJ_LABEL, 0, 0, 0);
   ObjectSetText("TpLf_Label" + line, MsgDsply, 10, "courier new bold", colour);
   ObjectSet("TpLf_Label" + line, OBJPROP_CORNER, 0);
   ObjectSet("TpLf_Label" + line, OBJPROP_XDISTANCE, 1);
   ObjectSet("TpLf_Label" + line, OBJPROP_YDISTANCE, (10+((line-1) * 15)));   
//---- 
   return(0);
}  

int CommentTR(int line, string MsgDsply, color colour)
{
//---- 
   ObjectCreate("TpRh_Label" + line, OBJ_LABEL, 0, 0, 0);
   ObjectSetText("TpRh_Label" + line, MsgDsply, 10, "courier new bold", colour);
   ObjectSet("TpRh_Label" + line, OBJPROP_CORNER, 1);
   ObjectSet("TpRh_Label" + line, OBJPROP_XDISTANCE, (175-StringLen(MsgDsply)*8));
   ObjectSet("TpRh_Label" + line, OBJPROP_YDISTANCE, (10+((line-1) * 15)));   
//---- 
   return(0);
} 

string BPrint(bool ai_0) {
   if (ai_0) return ("True");
   return ("False");
}

void SetObjectText(string name, string text, string font, int fontsize, color text_color)
{
   ObjectSetText(name, text, fontsize, font, text_color);
}

int MoveObject(string ObjName, int type, int time1, double price1, int time2 = 0, double price2 = 0.0, color text_color = -1, int unused2 = 0, int unused2 = 0)
{
   int nRet;
   if (ObjectFind(ObjName) != -1)//if cant find object, returned -1
   {
      nRet = ObjectType(ObjName);
      if (nRet == 0 || nRet == 1 || nRet == 3 || nRet == 21 || nRet == 22 || nRet == 23) 
         //OBJ_VLINE|OBJ_HLINE|OBJ_TRENDBYANGLE|OBJ_TEXT|OBJ_ARROW|OBJ_LABEL
         return (ObjectMove(ObjName,0,time1,price1)); //if cant move object, returned FALSE
               
      if (nRet == 7 || nRet == 8 || nRet == 9 || nRet == 10 || nRet == 11 || nRet == 12 || nRet == 13 || nRet == 16 || nRet == 18 || nRet == 20 || nRet == 2 || nRet == 6 || nRet == 4) 
        //OBJ_GANNLINE|OBJ_GANNFAN|OBJ_GANNGRID|OBJ_FIBO|OBJ_FIBOTIMES|OBJ_FIBOFAN|OBJ_FIBOARC|OBJ_RECTANGLE|OBJ_ELLIPSE|OBJ_CYCLES|OBJ_TREND|OBJ_STDDEVCHANNEL|OBJ_REGRESSION
         return (ObjectMove(ObjName, 0, time1, price1) && ObjectMove(ObjName, 1, time2, price2));
   }
   else
   {
      return (ObjectCreate(ObjName, type, 0, time1, price1, time2, price2, 0, 0) && ObjectSet(ObjName, OBJPROP_COLOR, text_color));
   }//end if
   return (0);
}

bool IsNewBar() 
{ 
   static datetime lastbar=0; 
   datetime curbar = Time[0]; 
   if(lastbar!=curbar) 
   { 
   lastbar=curbar; 
      return (true); 
   } 
   else 
   { 
      return(false); 
   } 
}

/*
#import "kernel32.dll"
   int   GetCurrentProcessId();
   void  GetLocalTime(int& TimeArray[]);
   int   GetTimeZoneInformation(int& TZInfoArray[]);
#import

extern bool AutoLocalGmtOffset = TRUE;
extern double GmtOffset = 0.0;

string strBrokerTime;
string strGmtTime;
string strGmtOffset;
int servertime;
int GMT_time;
int GMT_Hour; 

   GmtOffset=GetGmtOffset();
   servertime = TimeCurrent();
   
   GMT_time = servertime - 3600.0 * GmtOffset;
   strGmtOffset = DoubleToStr(GmtOffset, 1);
   strBrokerTime = TimeToStr(servertime);
   strGmtTime=TimeToStr(GMT_time);
   GMT_Hour = TimeHour(GMT_time);
   int PCLocalTime = servertime - 3600.0 * GMT_Hour - 60 * TimeMinute(GMT_time) - TimeSeconds(GMT_time);

   CommentTL(4, "Broker Time:"+ strBrokerTime, Yellow);
   CommentTL(5, "GMT Time   :"+ strGmtTime, Yellow);
   CommentTL(6, "GMT Offset:"+ strGmtOffset, Yellow);
   CommentTL(7, "Time:"+ TimeToStr(PCLocalTime), Yellow);


double TimeZoneServer()
{
int HrsDiff = (TimeCurrent() - TimeLocal()) / 60;
int li_4 = MathRound(HrsDiff / 30.0);
HrsDiff = 30 * li_4;
double dCurBrokerGMTOffset = TimeZoneLocal() + HrsDiff / 60.0;
return (dCurBrokerGMTOffset);
}

double GetGmtOffset()
{
   return(TimeZoneServer());
}

double TimeZoneLocal()
{
   int TIME_ZONE_INFORMATION [43];
   int TimeRet;
   switch (GetTimeZoneInformation(TIME_ZONE_INFORMATION ))
   {
      case 0: 
         TimeRet=TIME_ZONE_INFORMATION [0] / (-60.0);
         break;
      case 1: 
         TimeRet=TIME_ZONE_INFORMATION [0] / (-60.0);
         break;
      case 2: 
         TimeRet=(TIME_ZONE_INFORMATION [0] + TIME_ZONE_INFORMATION [42]) / (-60.0);
         break;
   }      
      return (TimeRet);
}
string GMPrint(int ai_0) {
   switch (ai_0) {
   case 1:
      return ("automatic: server 1");
   case 2:
      return ("automatic: server 2");
   case 4:
      return ("automatic: local");
   }
   return ("manual");
}
*/   