#property copyright "Paul Murfin + Modified by Ravi"
#property link      ""
#include <stdlib.mqh>
#include <stderror.mqh>

#define   MODEL "Trend Follower"

#define   STARTBAR  0
#define	LONG         1
#define	SHORT        -1
#define	FLAT         0
#define  ALLLONG     2
#define  ALLSHORT    -2

#define	strLONG      "LONG"
#define	strSHORT     "SHORT"
#define	strFLAT      "FLAT"
#define  strALLLONG  "ALL LONG"
#define  strALLSHORT "ALL SHORT"

#define  REDNUM      16
#define  GREENNUM  12    
#define  BLUENUM     11
#define  ORANGENUM 13
#define  YELLOWNUM 14


extern   bool AlertOn = false;
extern   bool EmailOn = false;
extern   bool ADXFilter=false;
extern int iStopLoss = 100;
extern int iTPIncrement = 35;
extern int iTradeFactor = 50; //1 = .05/.01, 10 = 0.5/0.1, 100 = 5.0/1.0, 1000 = 50/10
extern int PipsTrail   = 35;
extern int       Magic      = 13001;
extern double    Lots       = 0.5;
extern int       MaxTrades  = 0;
extern int       noOfLot=2;
extern int      TakeProfit=0;
extern double      LegLength = 0.66;

int k;
int iTicket;
int iTradeDir;
int iPrevProfit;
double dThisProfit;
int iTradesClosed;
int iSL;
bool breakeven=false;

double   RedMax;
double   RedMin;
int       RedTrend;
int      RedPeriods[REDNUM] = {125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200};

double   GreenMax;
double   GreenMin;
int         GreenTrend;
int       GreenPeriods[GREENNUM] = {78, 82, 86, 90, 94, 98, 102, 106, 110, 114, 118, 122};

double   BlueMax;
double   BlueMin;
int        BlueTrend;
int        BluePeriods[BLUENUM] = {44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74};

double   OrangeMax;
double   OrangeMin;
int        OrangeTrend;
int        OrangePeriods[ORANGENUM] = {17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41};

double   YellowMax;
double   YellowMin;
int        YellowTrend;
int        YellowPeriods[YELLOWNUM] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
						
int	SignalTrend;
int	SlopeTrend;
int	MACDTrend;
int	LaguerreTrend;
int	GuppyTrend;
int	InvestorTrend;
int   TradingIndicator;
int ADXTrend;
int magic=0;
string	strTrends;

//FirstBarTime=StrToTime("00:05"); 


////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int init () {

	SignalTrend = FLAT;
	SlopeTrend = FLAT;
	MACDTrend = FLAT;
	LaguerreTrend = FLAT;
	InvestorTrend = FLAT;
	GuppyTrend = FLAT;
	TradingIndicator = FLAT;

	NewBar();
	CalculateIndicators(STARTBAR);
	DisplayComment();
	
	return (0);
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int deinit () {

	return (0);
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int start () {
   magic=Magic;
   double tp =0;
	if (NewBar()) { 
		CalculateIndicators(STARTBAR);
		if (TradingIndicator == LONG) {
		    if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG");
		    if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO LONG");
		     bool ct = _Trend_CanTrade(Symbol(), magic, MaxTrades) && IsTradeAllowed();
		    closeOrder(Symbol(),magic,OP_SELL);
		    if (!_Trend_ActivePosition(Symbol(), magic) && ct) {
		       if ( TakeProfit > 0){
		          tp =  Ask + TakeProfit*MarketInfo(Symbol(), MODE_POINT);
		       }
		       OrderSend(Symbol(), OP_BUY, 0.01 * iTradeFactor * noOfLot, Ask, 3, Ask - iStopLoss*MarketInfo(Symbol(), MODE_POINT),tp , "TREND FOLLOWER", magic, 0, Blue);
		    }
		} else if (TradingIndicator == SHORT) {
		    if (AlertOn) Alert(MODEL+" "+Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT");
		    if (EmailOn) SendMail(MODEL,Symbol()+" "+Period()+"Min -  All Indicators Aligned - GO SHORT");
		    ct = _Trend_CanTrade(Symbol(), magic, MaxTrades) && IsTradeAllowed();
		    closeOrder(Symbol(),magic,OP_BUY);
		    if (!_Trend_ActivePosition(Symbol(), magic) && ct) {
		       if ( TakeProfit > 0){
		          tp =  Bid - TakeProfit*MarketInfo(Symbol(), MODE_POINT);
		       }
		        OrderSend(Symbol(), OP_SELL, 0.01 * iTradeFactor * noOfLot, Bid, 3, Bid + iStopLoss*MarketInfo(Symbol(), MODE_POINT), tp, "TREND FOLLOWER", magic, 0, Red);
		    }
		   
		}
	}
	DisplayComment();
	// do any orders exist?
   if (OrdersTotal() > 0)
   {
      
         iTicket = 0;
         // cycle through open orders looking for one for this symbol
         for (k = 0; k < OrdersTotal(); k++)
       
            if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES) == true)
               // if found, store the ticket number
               if(OrderMagicNumber() == magic) {
               if (OrderSymbol() == Symbol()
                  && (OrderType() == OP_BUY || OrderType() == OP_SELL))
                    iTicket = OrderTicket();
         // if ticket is valid
         
         if (iTicket != 0)
         {
            // select current order to be managed
            OrderSelect(iTicket, SELECT_BY_TICKET);

            // set variables for long order
            iTradeDir = 1;
            dThisProfit = Bid - OrderOpenPrice();
            // change variables if order is short
            if (OrderType() == OP_SELL)
            {
               iTradeDir = -1;
               dThisProfit = - dThisProfit;
            }   
            iTradesClosed = noOfLot - (OrderLots() / (0.01 * iTradeFactor));
            iSL = iStopLoss;
            if (iTradesClosed >= 1) iSL = 0;
            iPrevProfit = iTradesClosed * iTPIncrement;
         
            // check price against current stoploss
            if (dThisProfit < -(iSL * Point))
            {
               // if violated, close entire order and reset tracking variables and quit
               OrderClose(OrderTicket(), OrderLots(), Bid, 5, Red);
               iTicket = 0;
               iTradeDir = 0;
               iPrevProfit = 0;
               dThisProfit = 0.0;
               iTradesClosed = 0;
               iSL = iStopLoss;
               return(0);
            }   

            // check if next TP has been reached
            if (dThisProfit > (iPrevProfit + iTPIncrement) * Point)
            {
               // if so, move stoploss to BE
               iSL = 0;
             
               // make sure only 4 TPs are used
               if (iTradesClosed < (noOfLot-1))
               {
                  // set next TP to next increment
                  iPrevProfit += iTPIncrement;
                  // close one portion of the trade according to the trade direction (long/short)
                  switch(iTradeDir)
                  {
                     case 1:
                        OrderClose (OrderTicket(), 0.01 * iTradeFactor, Bid, 3, Blue);
                     case -1:
                        OrderClose (OrderTicket(), 0.01 * iTradeFactor, Ask, 3, Red);
                  }      
               }
            }
             if ( (iTradesClosed == 1) && breakeven==false ) {
               switch(iTradeDir)
               {
                 case 1:
                   OrderModify (OrderTicket(), OrderOpenPrice(), OrderOpenPrice(),OrderTakeProfit(), OrderExpiration(), Blue);
                 case -1:
                  OrderModify (OrderTicket(), OrderOpenPrice(), OrderOpenPrice(),OrderTakeProfit(), OrderExpiration(), Red);
               }
               breakeven= true;
            }
       
          ProfitStepTrail(iTradeDir,OrderOpenPrice(),Symbol(),OrderStopLoss(), OrderTicket());
         }
         
        Comment(strTrends,"\n","Ticket = ", iTicket, "\n",
                 "Trade Direction = ", iTradeDir, "\n",
                 "Current Profit = ", dThisProfit, "\n",
                 "StopLoss = ", iSL, "\n",
                 "TPs Hit = ", iTradesClosed, "\n",
                 "Next TP = ", iPrevProfit + iTPIncrement);
      }
   }

	
	
	return (0);

}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

void CalculateIndicators (int BarNo) {

	double  up;
	double  dn;
	double  L0;
	double  L1;
	double  f1;
	double  f2;
	double  s1;
	double  s2;
	double  MACD0;
	double  MACD1;
	double  AD0;
	double  AD1;
	double  AD2;
   double  D1;
   double  D2;
   SignalTrend = FLAT;
	SlopeTrend = FLAT;
	MACDTrend = FLAT;
	LaguerreTrend = FLAT;
	InvestorTrend = FLAT;
	GuppyTrend = FLAT;
	TradingIndicator = FLAT;
	ADXTrend = FLAT;

//	Signal Direction

	f1 = iMA(NULL, 0, 4, 0, MODE_EMA, PRICE_CLOSE, BarNo);
	s1 = iMA(NULL, 0, 8, 0, MODE_EMA, PRICE_CLOSE, BarNo);
	f2 = iMA(NULL, 0, 4, 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
	s2 = iMA(NULL, 0, 8, 0, MODE_EMA, PRICE_CLOSE, BarNo+1);

	if (f1 > s1 && f2 < s2) 
		SignalTrend = LONG;
	else if (f1 < s1 && f2 > s2) 
		SignalTrend = SHORT;
	
	if (SignalTrend == FLAT) {

	f1 = iMA(NULL, 0, 4, 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
	s1 = iMA(NULL, 0, 8, 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
	f2 = iMA(NULL, 0, 4, 0, MODE_EMA, PRICE_CLOSE, BarNo+2);
	s2 = iMA(NULL, 0, 8, 0, MODE_EMA, PRICE_CLOSE, BarNo+2);

	if (f1 > s1 && f2 < s2) 
		SignalTrend = LONG;
	else if (f1 < s1 && f2 > s2) 
		SignalTrend = SHORT;
	
	}
	// ADX
   AD0 = iADX(NULL,0,8,PRICE_CLOSE,MODE_MAIN,BarNo);
   AD1 = iADX(NULL,0,8,PRICE_CLOSE,MODE_MAIN,BarNo+1);
   AD2 = iADX(NULL,0,8,PRICE_CLOSE,MODE_MAIN,BarNo+2);
   D1 = iADX(NULL,0,8,PRICE_CLOSE,MODE_PLUSDI,BarNo+1);
   D2 = iADX(NULL,0,8,PRICE_CLOSE,MODE_MINUSDI,BarNo+1);
   if ( AD0 > D1 && AD0 > D2 && AD0>AD1 && AD1 > AD2 ) {
      if ( D1 > D2) {
         ADXTrend = LONG;
      } else if ( D1 < D2) {
         ADXTrend = SHORT;
      }
   
   }
//	Slope Direction

	up = iCustom(NULL,0,"Slope Direction Line",80,3,0,BarNo);
	dn = iCustom(NULL,0,"Slope Direction Line",80,3,1,BarNo);

	if (up == EMPTY_VALUE && dn != EMPTY_VALUE) 
		SlopeTrend = SHORT;
   else if (dn == EMPTY_VALUE && up != EMPTY_VALUE) 
		SlopeTrend = LONG;


//	MACD

	MACD0 = iMACD(NULL,0,5,35,5,PRICE_CLOSE,0,BarNo);
	
	if (MACD0 > 0) 
		MACDTrend = LONG;
   else if (MACD0 < 0) 
		MACDTrend = SHORT;
	

//	Laguerre

//	L0 = iCustom(NULL,0,"Laguerre",0.66,9500,0,BarNo);
//	L1 = iCustom(NULL,0,"Laguerre",0.66,9500,0,BarNo+1);
	L0 = iCustom(NULL,0,"Laguerre",LegLength,9500,0,BarNo);
	L1 = iCustom(NULL,0,"Laguerre",LegLength,9500,0,BarNo+1);

	if (L0 > 0.15 && L1 < 0.15) 
		LaguerreTrend = LONG;
	else if (L0 < 0.75 && L1 > 0.75)  
		LaguerreTrend = SHORT;
	

	if (LaguerreTrend == FLAT) {

	L0 = iCustom(NULL,0,"Laguerre",LegLength,9500,0,BarNo+1);
	L1 = iCustom(NULL,0,"Laguerre",LegLength,9500,0,BarNo+2);

	if (L0 > 0.15 && L1 < 0.15) 
		LaguerreTrend = LONG;
	else if (L0 < 0.75 && L1 > 0.75)  
		LaguerreTrend = SHORT;
	

	}


//	Guppy

	CalculateGuppy(BarNo);

//	Trading Indicator

	if ( ADXFilter == true ) {
	  if (SignalTrend == LONG && LaguerreTrend == LONG && MACDTrend == LONG && GuppyTrend == LONG && SlopeTrend==LONG && ADXTrend==LONG) TradingIndicator = LONG;
	  else if (SignalTrend == SHORT && LaguerreTrend == SHORT && MACDTrend == SHORT && GuppyTrend == SHORT && SlopeTrend==SHORT && ADXTrend==SHORT ) TradingIndicator = SHORT;
	} else {
	  if (SignalTrend == LONG && LaguerreTrend == LONG && MACDTrend == LONG && GuppyTrend == LONG && SlopeTrend==LONG ) TradingIndicator = LONG;
	  else if (SignalTrend == SHORT && LaguerreTrend == SHORT && MACDTrend == SHORT && GuppyTrend == SHORT && SlopeTrend==SHORT  ) TradingIndicator = SHORT;
	}
  /* if (SignalTrend == LONG && LaguerreTrend == LONG && MACDTrend == LONG && GuppyTrend == LONG ) TradingIndicator = LONG;
	else if (SignalTrend == SHORT && LaguerreTrend == SHORT && MACDTrend == SHORT  && GuppyTrend == SHORT ) TradingIndicator = SHORT; */

//	Display string

strTrends = "\nRed : "+GSD(RedTrend)+"  Green : "+GSD(GreenTrend)+ "  Blue : "+GSD(BlueTrend)+ "  Orange : "+GSD(OrangeTrend)+ "  Yellow : "+GSD(YellowTrend)+
"\n\nSignal : "+GSD(SignalTrend)+"  Slope : "+GSD(SlopeTrend)+"  MACD : "+GSD(MACDTrend)+"  Laguerre : "+GSD(LaguerreTrend)+"  Guppy : "+GSD(GuppyTrend)+"   ADX     : "+GSD(ADXTrend)+ "      TRADE : "+GSD(TradingIndicator);




}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

int CalculateGuppy (int BarNo) {

   int      i;
   double   curr;
   double   prev;
   int      count;
     
   RedTrend = FLAT;
   RedMin = 0;
   RedMax = 0;
   GreenTrend = FLAT;
   GreenMin = 0;
   GreenMax = 0;
   BlueTrend = FLAT;
   BlueMin = 0;
   BlueMax = 0;
   OrangeTrend = FLAT;
   OrangeMin = 0;
   OrangeMax = 0;
   YellowTrend = FLAT;
   YellowMin = 0;
   YellowMax = 0;
   InvestorTrend = FLAT;
   GuppyTrend = FLAT;

   // Red Trends

   count = 0;   
   for (i=0;i<REDNUM;i++) {
      curr = iMA(NULL, 0, RedPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, RedPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (RedMax == 0 || curr > RedMax) RedMax = curr;
      if (RedMin == 0 || curr < RedMin) RedMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == REDNUM) RedTrend = ALLLONG;
   else if (count == -REDNUM) RedTrend = ALLSHORT;
   else RedTrend = FLAT;
   
   // Green Trends

   count = 0;   
   for (i=0;i<GREENNUM;i++) {
      curr = iMA(NULL, 0, GreenPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, GreenPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (GreenMax == 0 || curr > GreenMax) GreenMax = curr;
      if (GreenMin == 0 || curr < GreenMin) GreenMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == GREENNUM) GreenTrend = ALLLONG;
   else if (count == -GREENNUM) GreenTrend = ALLSHORT;
   else GreenTrend = FLAT;
   
  // Blue Trends

   count = 0;   
   for (i=0;i<BLUENUM;i++) {
      curr = iMA(NULL, 0, BluePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, BluePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (BlueMax == 0 || curr > BlueMax) BlueMax = curr;
      if (BlueMin == 0 || curr < BlueMin) BlueMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == BLUENUM) BlueTrend = ALLLONG;
   else if (count == -BLUENUM) BlueTrend = ALLSHORT;
   else BlueTrend = FLAT;
 
// Orange Trends

   count = 0;   
   for (i=0;i<ORANGENUM;i++) {
      curr = iMA(NULL, 0, OrangePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, OrangePeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (OrangeMax == 0 || curr > OrangeMax) OrangeMax = curr;
      if (OrangeMin == 0 || curr < OrangeMin) OrangeMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == ORANGENUM) OrangeTrend = ALLLONG;
   else if (count == -ORANGENUM) OrangeTrend = ALLSHORT;
   else OrangeTrend = FLAT;
    
// Yellow Trends

   count = 0;   
   for (i=0;i<YELLOWNUM;i++) {
      curr = iMA(NULL, 0, YellowPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo);
      prev = iMA(NULL, 0, YellowPeriods[i], 0, MODE_EMA, PRICE_CLOSE, BarNo+1);
      if (YellowMax == 0 || curr > YellowMax) YellowMax = curr;
      if (YellowMin == 0 || curr < YellowMin) YellowMin = curr;
      if (curr > prev) count++;
      else if (curr < prev) count--;
   }
   if (count == YELLOWNUM) YellowTrend = ALLLONG;
   else if (count == -YELLOWNUM) YellowTrend = ALLSHORT;
   else YellowTrend = FLAT;    
      
// InvestorTrend

     if (RedTrend == ALLLONG &&  GreenTrend == ALLLONG && RedMax <= GreenMin) InvestorTrend = LONG;
     else if (RedTrend == ALLSHORT && GreenTrend == ALLSHORT && RedMin >= GreenMax) InvestorTrend = SHORT;
     else InvestorTrend = FLAT;

// Guppy Trend
 
     if (YellowTrend == ALLLONG && OrangeTrend == ALLLONG && BlueTrend == ALLLONG && InvestorTrend == LONG) GuppyTrend = LONG;
     else if (YellowTrend == ALLSHORT && OrangeTrend == ALLSHORT && BlueTrend == ALLSHORT && InvestorTrend == SHORT) GuppyTrend = SHORT;
     else GuppyTrend = FLAT;
    
	
}


////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

string GSD(int D) {

	switch (D) {
		case LONG : return (strLONG);
		case SHORT : return (strSHORT);
		case ALLLONG : return (strALLLONG);
		case ALLSHORT : return (strALLSHORT);
	}
	return (strFLAT);

}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////

bool NewBar() {

	static datetime LastTime = 0;

	if (Time[0] != LastTime) {
		LastTime = Time[0];		
		return (true);
	} else
		return (false);
}



void DisplayComment() {

   Comment(strTrends);
}
void ProfitStepTrail(int oType, double price, string sym,double cStopLoss, int ticket) {
   bool Visual = true;
   double _Bid,_Ask,nStopLoss,nStopLoss1;
   int _Digits = MarketInfo(sym, MODE_DIGITS);
   if(_Digits == 0) _Digits = 2;
   double _Point = MarketInfo(sym, MODE_POINT);
  if(NormalizeDouble(_Point, _Digits) == 0.0) _Point = Point;
  _Bid = MarketInfo(sym, MODE_BID);
  _Ask = MarketInfo(sym, MODE_ASK);
  
   if(iTradeDir == 1) {
     if  (_Ask > price ) {
       double _virtualProfit = (_Ask - price);
       if ( _Digits == 3 ) {
         _virtualProfit = _virtualProfit *10;
       } else if ( _Digits == 4 ) {
         _virtualProfit = _virtualProfit *100;
       } 
       if ( _virtualProfit > 0.5 &&
           _virtualProfit < 1 ) {
         nStopLoss = price;
      } else  if ( _virtualProfit > 1.0 &&
           _virtualProfit < 1.5 ) {
         nStopLoss = price + PipsTrail* _Point;
      }else if (_virtualProfit >1.5 &&
                 _virtualProfit < 2 ) {
         nStopLoss = price + (PipsTrail*2)* _Point;
         //Alert (" nStopLoss 3:",nStopLoss);
      } else if (_virtualProfit >2 &&
                 _virtualProfit < 2.5 ) {
         nStopLoss = price + (PipsTrail*4)* _Point;
      } else if (_virtualProfit >2.5 &&
                 _virtualProfit < 3 ) {
           nStopLoss = price + (PipsTrail*6)* _Point;
      }else if (_virtualProfit >3 &&
                 _virtualProfit < 3.5 ) {
            nStopLoss = price + (PipsTrail*8)* _Point;
       }
     
      if (((cStopLoss == 0)|| (cStopLoss < nStopLoss)) && nStopLoss !=0) {
        OrderModify(iTicket, price, nStopLoss, OrderTakeProfit(), OrderExpiration(), Green);
      }
     }
     
   } else  if ( iTradeDir == -1){

      if  (_Bid < price ) {
      
         double _virtualProfit1 = (price- _Bid);
         if ( _Digits == 3 ) {
            _virtualProfit1 = _virtualProfit1 *10;
         } else if ( _Digits == 4 ) {
            _virtualProfit1 = _virtualProfit1 *100;
         }
         if ( _virtualProfit1 > 0.5 &&
           _virtualProfit1 < 1) {
         nStopLoss1 = price;
        // - sl * 0.25* _Point;
         } else  if ( _virtualProfit1 > 1 &&
            _virtualProfit1 < 1.5) {
          nStopLoss1 = price -  PipsTrail* _Point;
         }else if (_virtualProfit1 >1.5 &&
                 _virtualProfit1 < 2 ) {
            nStopLoss1 = price - (PipsTrail*2)* _Point;
         } else if (_virtualProfit1 >2 &&
                 _virtualProfit1 < 2.5 ) {
            nStopLoss1 = price -(PipsTrail*4)* _Point;
         }else if (_virtualProfit1 >2.5 &&
                 _virtualProfit1 < 3 ) {
            nStopLoss1 = price - (PipsTrail*6)* _Point;
         }else if (_virtualProfit1 >3 &&
                 _virtualProfit1 < 3.5 ) {
            nStopLoss1 = price - (PipsTrail*8)* _Point;
         }
     /*     Comment (" nStopLoss1 1:",nStopLoss1,"\n",
          " cStopLoss1:",cStopLoss,"\n",
          " price:",price,"\n"
          ); */
         if (((cStopLoss == 0)|| (cStopLoss > nStopLoss1)) && nStopLoss1 !=0) {
            OrderModify(iTicket, price, nStopLoss1, OrderTakeProfit(), OrderExpiration(), Green);
         }
      }
     
   } //Sell
}

bool closeOrder(string sym,int magic,bool orderType) {
    for(int i=OrdersTotal()-1; i >= 0; i--)
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
      if(OrderSymbol() == sym)
      if(OrderMagicNumber() == magic)
      if ( OrderType() == orderType) {
         if(!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 1) ) _ce();
      }
    }
    
  return(true);
   
}
bool _Trend_CanTrade(string symbol, int magic, int max)
{
  int today_trades = 0;
  datetime today = iTime(symbol, PERIOD_D1, 0);
  for(int i=OrdersHistoryTotal()-1; i >= 0; i--)
    if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)){
      if(OrderSymbol() == symbol)
      if(OrderMagicNumber() == magic)
      if(OrderOpenTime() >= today){
        today_trades++;
         
        if(MaxTrades > 0)
        if(today_trades >= MaxTrades)
          return(false);
      
      }
    }else
      Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
  return(true);
}

bool _Trend_ActivePosition(string symbol, int magic)
{
  for(int i=OrdersTotal()-1; i >= 0; i--)
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)){
    if(OrderType() <= OP_SELL)
    if(OrderSymbol() == symbol)
    if(OrderMagicNumber() == magic)
      return(true);
    }else
      Print("OrderSelect() error - ", ErrorDescription(GetLastError()));
  return(false);
}
bool _ce()
{
  int err=GetLastError();
  if(err != ERR_NO_ERROR){
    Print("Error #", err, " ", ErrorDescription(err));
    return(true);
  }
  return(false);
}


