
extern bool UseProfitManager = false;
extern bool tradeOnHolidays = false;
extern bool useATRStopLoss = true;
extern int trailingStop=0;
extern int takeProfit=100;
extern double lots=0.1;
extern int slippage = 3;
extern int ema3_period=3;
extern int ema5_period=5;
extern int ema13_period=13;
extern int ema21_period=21;
extern int ema80_period=80;
extern string ExpertName = "MultiEma_4";
extern int ExpertID = 15445631;
extern bool UseMM = false;
extern double Risk = 4;
extern int minCrossDistance = 1;
extern bool UseRavi = true;
extern double raviMax = 0.08;
extern double raviMin = -0.08;
extern double raviLowestBorder = -0.4;
extern double raviHighestBorder = 0.4;
//extern int maxCrossDistance = 7;
extern int rsiPeriod = 21; 


extern int fast_maForClose = 5;
extern int slow_maForClose = 8;

extern string ProfitManager = "**************************************";

extern int First_TP_Target = 50;
extern int TP_Target_Increment = 10;
extern double Close_Lots = 0.1;
extern bool Move_Stops = true;
extern int First_Stop_Target = 15;
extern int First_Stop = 1;
extern int Second_Stop_Target = 30;
extern int Second_Stop = 16;
extern int Third_Stop_Target = 49;
extern int Third_Stop = 30;
extern int Trail_Stop_By = 30;
extern bool Use_Max_Loss = true;
extern int Max_Loss = 30;


//=============== VARS internal
int nextTP;
int sl;
int range = 5;
int multiplier;
int Trail_Stop;
int Trail_Trigger;
int temp;
string trailon;
string version="MTP 1.5";

string OrderReliable_Fname = "";

// order reliable close
static int _OR_err      = 0;
int retry_attempts 		= 10; 
double sleep_time 		= 4.0;
double sleep_maximum 	= 25.0;  // in seconds
int stopLoss;
int init()
  {
  
    if(First_Stop==0 && First_Stop_Target !=0) First_Stop=1;
   if(Max_Loss < 0) Max_Loss=(-1*Max_Loss);
   if(Trail_Stop_By < 0) Trail_Stop_By = -1*Trail_Stop_By;
   sl = -1*Max_Loss;
   nextTP = First_TP_Target;
   Trail_Stop = sl;
   trailon = "Off ";
   getMaxLoss();    
   if(Third_Stop!=0) Trail_Trigger=Third_Stop+Trail_Stop_By;
   else if(Second_Stop!=0) Trail_Trigger=Second_Stop+Trail_Stop_By;
   else if(First_Stop!=0) Trail_Trigger=First_Stop+Trail_Stop_By;
   else Trail_Trigger=sl+Trail_Stop_By;
   
   Comment(version, 
  
   "\nClose Lots:  ", Close_Lots,
   "\nTP:   ", First_TP_Target, "  ", TP_Target_Increment,
   "\nSL1:  ", First_Stop_Target, "  ", First_Stop,
   "\nSL2:  ", Second_Stop_Target, "  ", Second_Stop,
   "\nSL3:  ", Third_Stop_Target,  "  ", Third_Stop,
   "\nTSL:  ", Trail_Stop_By,
   "\nMax Loss:  ", Max_Loss);
  
   GlobalVariableSet("allowLong" + Symbol() ,1); 
   GlobalVariableSet("allowShort"  + Symbol(),1); 
   Comment(ExpertName + " is waiting for the next tick to begin.");	
   return(0);
  }

int deinit()
  {
        sl = -1*Max_Loss;
   nextTP = First_TP_Target;
   Trail_Stop = sl;     
       return(0);
  }

 static int isCrossed  = 0;
 static int isCrossedBig = 0;
 
 
int start()
  {
     
     // don't trade on holidays and fridays 
     if (!tradeOnHolidays)
     {
       if(DayOfWeek()==0 || DayOfWeek()==6 || DayOfWeek()==5) return(0);
     } 
     
     if (useATRStopLoss)
     {
         
         stopLoss = calcAtrStopLoss();
         Print("atr= " + stopLoss);
         if (stopLoss > Max_Loss)
         {
            stopLoss = Max_Loss;
         } 
     }
        
     
     int total=OrdersTotal(),
         i,
         cnt;
      
      
   if (UseMM)
   {
      lots = CalculateLotSize();
   } 
   

        
   bool longOk=false;   
   bool shortOk=false;
   bool orderIsOpen = isOrderOpened();   
   
   double ema3 = iMA(NULL,0,ema3_period,0,MODE_EMA,PRICE_CLOSE,0);
   double ema5 = iMA(NULL,0,ema5_period,0,MODE_EMA,PRICE_OPEN,0);
   double ema13 = iMA(NULL,0,ema13_period,0,MODE_EMA,PRICE_CLOSE,0);
   double ema21 = iMA(NULL,0,ema21_period,0,MODE_EMA,PRICE_OPEN,0);
   double ema80 = iMA(NULL,0,ema80_period,0,MODE_EMA,PRICE_CLOSE,0);
   double rsi = iRSI(NULL, 0, rsiPeriod, PRICE_CLOSE, 0);
   double ravi = iCustom(NULL,0,"ravifisher",0,0);    
   bool raviTest = (ravi > raviMax || ravi < raviMin);
   
   
   if (!UseRavi)
   {
      raviTest = true;
   }
   
   if(ema3 > ema5 && ema3 > ema80 && ema13 > ema21 && rsi >= 50 && raviTest && rsi < 70 && ravi < raviHighestBorder)
   {
     longOk = true;
     shortOk = false;
   
   }
    
  
    if(ema21 > ema13  && ema5 > ema3 && ema80 > ema3 && rsi <= 50 && raviTest && rsi > 30 && ravi > raviLowestBorder) 
    {
      shortOk = true;
      longOk = false;
      
    }
  
   int Distance      = MathFloor(MathAbs((ema3-ema5)/Point));
   int Distance2     = MathFloor(MathAbs((ema13-ema21)/Point)); //maxCrossDistance
   
  
  
    isCrossed = Crossed(ema3,ema5);
    isCrossedBig = Crossed(ema13,ema21); 
   
    Print("isCrossed= " + isCrossed);
    if (orderIsOpen)
    { 
       
       if (UseProfitManager)
      {
          getOpenOrders();
          getSpread();
      }
      else
      {
           trailOrders();
      } 
         
    }
    else
    {
       
       if (isCrossedBig == 1 &&  Distance2 >= minCrossDistance) 
       {
          GlobalVariableSet("allowShort" + Symbol(),1); 
         
          Comment("allowShort = true" + " " + "Distance = " + Distance2 + " mincrossDistance = " + minCrossDistance);
       } 
      
      if (isCrossedBig == 2 && Distance2 >= minCrossDistance) 
      {
          GlobalVariableSet("allowLong" + Symbol(),1); 
         
         
      }  
      
       Comment(ExpertName + " : allowShort = " +  GlobalVariableGet("allowShort"+ Symbol()) + " " + "Distance = " + Distance2 + " mincrossDistance = " + minCrossDistance + " isCrossed = " + isCrossed + " shortok = " +shortOk + " longOk = " + longOk);  
       Print("Distance2= "+ Distance2);
       Print("maxCrossDistance= "+ Distance2);
      
      if  (longOk && isCrossed == 1 && Distance >= minCrossDistance && GlobalVariableGet("allowLong"+ Symbol()) == 1 )
      {
         
         
         int ticketBuy = OrderSendSafe(Symbol(), OP_BUY, lots, Ask, slippage, Ask-stopLoss*Point,Ask+takeProfit*Point ,ExpertName, ExpertID, 0, Lime);
        if (ticketBuy > 0)
        {
           
           
            GlobalVariableSet("allowLong"+ Symbol(),0); 
            //allowLong = false;
        }
      }
      
      
      if (shortOk && isCrossed ==2 && Distance >= minCrossDistance &&  GlobalVariableGet("allowShort"+ Symbol()) == 1)
      {
          
          int ticketSell = OrderSendSafe(Symbol(), OP_SELL, lots, Bid, slippage, Bid+stopLoss*Point,Bid - takeProfit*Point ,ExpertName, ExpertID, 0, Red);
         
          if (ticketSell > 0)
          {
         
           
            Comment("set allowShort = false");
            GlobalVariableSet("allowShort" + Symbol(),0);
           
          }
      }
          
    }  
 
  }


bool isOrderOpened()
{
    int cnt;
   bool orderIsOpen = false;
   int total = OrdersTotal();  // Currently open or pending orders
 
  for(cnt = 0; cnt < total; cnt++)
  {
    OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
    if( (OrderSymbol() == Symbol()) && (OrderMagicNumber() == ExpertID) )
    {
      orderIsOpen = true;
      break;
    }
    else
      continue; 
  }  
  
  return (orderIsOpen);
}

int EMAsCrossing()
{
      int result;
      double fastma1 = iMA(NULL,0,fast_maForClose,0,MODE_EMA,PRICE_CLOSE,0);
      double slowma1 = iMA(NULL,0,slow_maForClose,0,MODE_SMA,PRICE_CLOSE,0);      
      int Distance = MathFloor(MathAbs((fastma1-slowma1)/Point));
      static int isCrossed = 0;
      isCrossed = Crossed(fastma1,slowma1);
      if(isCrossed == 1 && Distance >= minCrossDistance)
      {
        result = 1;
      }
      if(isCrossed == 2 && Distance >= minCrossDistance)
      {
       result = 2;
      }
      return(result);
}

int Crossed (double short , double long)
  {
    static int last_direction = 0;
    static int current_direction = 0;
    //Don't work in the first load, wait for the first cross!
    static bool first_time = true;
    if(first_time == true)
      {
        first_time = false;
        return (0);
      }

    if(short > long)
        current_direction = 1;  //up
    if(short < long)
        current_direction = 2;  //down

    /*  
    if(current_direction != last_direction)  //changed 
      {
        last_direction = current_direction;
        return(last_direction);
      }
    else
      {
        return (0);  //not changed
      }
   */
   
    return (current_direction);
   }
  
  
  void trailOrders()
  {
      int cnt;
      int total = OrdersTotal();
       int iEmasCrossing = EMAsCrossing();
        for(cnt = 0; cnt < total; cnt++)
      {
        OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
        if(OrderType() <= OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == ExpertID )
          {
            if(OrderType() == OP_BUY)   // long position is opened
              {
                
                
            
                if (isCrossedBig==2)
                {
                  OrderCloseReliable(OrderTicket(),OrderLots(),Bid,slippage,Yellow); 
                }
             
                 
            
                   if(iEmasCrossing == 2)
                   {
                      OrderCloseReliable(OrderTicket(),OrderLots(),Bid,slippage,MediumVioletRed); 
                   }

             
                // check for trailing stop
                if(trailingStop > 0)  
                  {                 
                    if(Bid - OrderOpenPrice() > Point*trailingStop)
                      {
                        if(OrderStopLoss() < Bid - Point*trailingStop)
                          {       
                            OrderModifySafe(OrderTicket(), OrderOpenPrice(), Bid - Point*trailingStop, OrderTakeProfit(), 0, Green);                            
                            return(0);
                          }
                      }
                  }
              }
            else // go to short position
              {
                 
                  if (isCrossedBig==1)
                  {
                      OrderCloseReliable(OrderTicket(),OrderLots(),Ask,slippage,Yellow); 
                  }
                   
            
                   if(iEmasCrossing == 1)
                   {
                      OrderCloseReliable(OrderTicket(),OrderLots(),Ask,slippage,MediumVioletRed);
                   }

                 
                // check for trailing stop
                if(trailingStop > 0)  
                  {                 
                    if((OrderOpenPrice() - Ask) > (Point*trailingStop))
                      {
                        if((OrderStopLoss() > (Ask + Point*trailingStop)) || 
                           (OrderStopLoss() == 0))
                          {        
                            OrderModifySafe(OrderTicket(), OrderOpenPrice(), Ask + Point*trailingStop, OrderTakeProfit(), 0, Green);
                            return(0);
                          }
                      }
                  }
              }
          }
      }
      
   
  }
  
  int OrderSendSafe(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)
 {
	int ticket;
	bool cont = true;
	
	int sleepMin = 2;
	int sleepMax = 10;
	MathSrand(TimeLocal());
	int errCode; 
	while(cont)
	{
		ticket = OrderSend(symbol, cmd, volume, price, slippage, stoploss, takeprofit, comment, magic, expiration, arrow_color);
		
		if(ticket < 0)
   		{
   		errCode = HandleLastError();
			if(errCode ==6)
			{
			   bool connect = false;
            int iteration = 0;
           
           while((!connect) || (iteration > 60))
             {
               Sleep(10000);        
               connect = IsConnected();
               if(connect)
                 {  
                   return(2);
                 }
               iteration++;
             }	
			}
			else if (errCode==129 || errCode==130 || errCode==135 || errCode==138)
			{
			   RefreshRates();
				
				int randomSeconds = MathRand() % (sleepMax - sleepMin) + sleepMin;
				Sleep(randomSeconds * 1000);
			}
			else
				cont = false;
		}
		else
			cont = false;
	}
	
	
	return (ticket);
}

void OrderModifySafe(int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color=Yellow)
{
	bool cont = true;
	
	int sleepMin = 2;
	int sleepMax = 10;
	MathSrand(TimeLocal());
	int errCode; 
	while(cont)
	{	
		bool result = OrderModify(ticket, price, stoploss, takeprofit, expiration, arrow_color);
	
		if(!result)
		{
			errCode = HandleLastError();
			if(errCode == 6) //== ERR_TRADE_CONTEXT_BUSY
			{
			  bool connect = false;
           int iteration = 0;
          
           while((!connect) || (iteration > 60))
             {
               Sleep(10000);
        
                
               connect = IsConnected();
               if(connect)
                 {  
                   return;
                 }
               iteration++;
             }
			}
			else if (errCode==129 || errCode==130 || errCode==135 || errCode==138)
			{
				
				RefreshRates();
				int randomSeconds = MathRand() % (sleepMax - sleepMin) + sleepMin;
				Sleep(randomSeconds * 1000);
			}
			else
				cont = false;
		}
		else
			cont = false;
	}
}

int HandleLastError(bool printInfo = true)
{
	int error = GetLastError();
	
	if(error > 0 && printInfo)
	{
	
	   Print("Error #", error, ": ", error);  
	}
	
	return (error);
}


double CalculateLotSize()
{

	//double pipValue = MarketInfo(Symbol(), MODE_TICKVALUE);
	//double lots = AccountFreeMargin() * Risk / (stopLoss * pipValue);
	double lots = MathCeil(AccountFreeMargin() *  Risk / 1000) / 100;
	
	double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
	int digits = 0;
	if(lotStep <= 0.01)
		digits = 2;
	else if(lotStep <= 0.1)
		digits = 1;
	lots = NormalizeDouble(lots, digits);
  	
  	double minLots = MarketInfo(Symbol(), MODE_MINLOT);
  	if(lots < minLots)
  		lots = minLots;
  	
  	double maxLots = MarketInfo(Symbol(), MODE_MAXLOT);
  	if(lots > maxLots)
  		lots = maxLots;
  	
  	return (lots);
}

//********Calculate ATR stop loss (thanks to Banzai)

int calcAtrStopLoss()
{

   datetime TimeArray[];
   int ind=0; 
   int stoplosses=0;
   
   ArrayCopySeries(TimeArray,MODE_TIME,Symbol(),240); 
   
   if (Time[0]<TimeArray[ind]) ind++; 
   
   double atr=iATR(NULL,240,100,ind);
   
   int findsymbol = StringFind(Symbol(),"JPY",0);
   
   if (findsymbol > 0) {
   
      if (Symbol() == "GBPJPY" || Symbol() == "GBPJPYm") 
      {
         stoplosses = (atr *100)/2;
      }
      else stoplosses = (atr *100);
   }
   else if (Symbol() == "USDMXN" || Symbol() == "USDMXNm") 
   {
         stoplosses = (atr *10000)/2;
   }
   else stoplosses = (atr *10000);
   
   return  (stoplosses);
   
 }




bool OrderCloseReliable(int ticket, double lots, double price, 
						int slippage, color arrow_color = CLR_NONE) 
{
	OrderReliable_Fname = "OrderCloseReliable";

	OrderReliablePrint(" attempted close of #" + ticket + " price:" + price + 
						" lots:" + lots + " slippage:" + slippage); 

	if (!IsConnected()) 
	{
		OrderReliablePrint("error: IsConnected() == false");
		_OR_err =  6; 
		return(false);
	}
	
	if (IsStopped()) 
	{
		OrderReliablePrint("error: IsStopped() == true");
		return(false);
	}
	
	int cnt = 0;
	while(!IsTradeAllowed() && cnt < retry_attempts) 
	{
		OrderReliable_SleepRandomTime(sleep_time,sleep_maximum); 
		cnt++;
	}
	if (!IsTradeAllowed()) 
	{
		OrderReliablePrint("error: no operation possible because IsTradeAllowed()==false, even after retries.");
		_OR_err = 146; 
		return(false);  
	}


	int err = GetLastError(); // so we clear the global variable.  
	err = 0; 
	_OR_err = 0; 
	bool exit_loop = false;
	cnt = 0;
	bool result = false;
	
	while (!exit_loop) 
	{
		if (IsTradeAllowed()) 
		{
			result = OrderClose(ticket, lots, price, slippage, arrow_color);
			err = GetLastError();
			_OR_err = err; 
		} 
		else 
			cnt++;

		if (result == true) 
			exit_loop = true;

		switch (err) 
		{
			case 0:
				exit_loop = true;
				break;
				
			case  4:
			case 6:
			case 129:
			case 136:
			case 137:
			case 146: 
			case 128:		// for modify this is a retryable error, I hope. 
				cnt++; 	// a retryable error
				break;
				
			case 135:
			case 138:
				RefreshRates();
				continue; 	// we can apparently retry immediately according to MT docs.
				
			default:
				// an apparently serious, unretryable error.
				exit_loop = true;
				break; 
				
		}  // end switch 

		if (cnt > retry_attempts) 
			exit_loop = true; 
			
		if (!exit_loop) 
		{
			OrderReliablePrint("retryable error (" + cnt + "/" + retry_attempts + 
								"): "  +  OrderReliableErrTxt(err)); 
			OrderReliable_SleepRandomTime(sleep_time,sleep_maximum); 
			RefreshRates(); 
		}
		
		if (exit_loop) 
		{
			if ((err != 0) && (err != 1)) 
				OrderReliablePrint("non-retryable error: "  + OrderReliableErrTxt(err)); 

			if (cnt > retry_attempts) 
				OrderReliablePrint("retry attempts maxed at " + retry_attempts); 
		}
	}  
	
	// we have now exited from loop. 
	if ((result == true) || (err == 0)) 
	{
		OrderReliablePrint("apparently successful modification order, updated trade details follow.");
		OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES); 
		OrderPrint(); 
		return(true); // SUCCESS! 
	} 
	
	OrderReliablePrint("failed to execute close after " + cnt + " retries");
	OrderReliablePrint("failed close: Ticket #" + ticket + ", Price: " + 
						price + ", Slippage: " + slippage); 
	OrderReliablePrint("last error: " + OrderReliableErrTxt(err)); 
	
	return(false);  
}

void OrderReliable_SleepRandomTime(double mean_time, double max_time) 
{
	if (IsTesting()) 
		return; 	// return immediately if backtesting.

	double tenths = MathCeil(mean_time / 0.1);
	if (tenths <= 0) 
		return; 
	 
	int maxtenths = MathRound(max_time/0.1); 
	double p = 1.0 - 1.0 / tenths; 
	  
	Sleep(1000); 	// one tenth of a second
	
	for(int i=0; i < maxtenths; i++)  
	{
		if (MathRand() > p*32768) 
			break; 
			
		// MathRand() returns in 0..32767
		Sleep(1000); 
	}
}  
string OrderReliableErrTxt(int err) 
{
	return ("" + err + ":" +err); 
}
void OrderReliablePrint(string s) 
{
	// Print to log prepended with stuff;
	Print(OrderReliable_Fname + " : " + s);
}

//***** Profit Manager ****************************** */

//========== FUNCTION getPipValue
double getPipValue(double ord,int dir)
{
   double val;
   RefreshRates();
   if(dir == 1) val=(NormalizeDouble(ord,Digits) - 
NormalizeDouble(Ask,Digits));
   else val=(NormalizeDouble(Bid,Digits) - NormalizeDouble(ord,Digits));
   val = val/Point;
   return(val);
}
//== end function

int getSpread()
{
   int spread=MarketInfo(Symbol(),MODE_SPREAD);
   return(spread);
}


int getMaxLoss()
{
   int calcMaxLoss;
   calcMaxLoss = Max_Loss;
   return(calcMaxLoss);
}
//========== FUNCTION getOpenOrders
void getOpenOrders()
{
   int nsl, nsd;
   string mngMagic;
   int totalorders = OrdersTotal();
   for(int j=0; j<totalorders;j++)
     {
         OrderSelect(j, SELECT_BY_POS, MODE_TRADES);
         if((OrderType() == OP_BUY || OrderType() == OP_SELL) && OrderSymbol() == Symbol()&&(OrderMagicNumber() == ExpertID ))
         {

            double val=getPipValue(OrderOpenPrice(),OrderType());
            //int val = OrderProfit()/(OrderLots()*10);
            if(Move_Stops) checkStops(val,OrderTicket());
            if(First_TP_Target !=0) takeProfit(val,OrderTicket());

         }

        
         mngMagic = "Trades with magic number = "+ExpertID;


         if(sl==-1*Max_Loss)
            {
               nsl = First_Stop_Target;
               nsd = First_Stop;
            }
         else if(sl==First_Stop)
            {
               nsl = Second_Stop_Target;
               nsd = Second_Stop;
            } 
         else if(sl==Second_Stop)
            {
               nsl = Third_Stop_Target;
               nsd = Third_Stop;
            }
         else if(Trail_Stop_By != 0 && val >= Trail_Trigger)
            {
               nsl = val + 1;
               nsd = val + 1 - Trail_Stop_By; 
               trailon = " On";  
            }
         //RefreshRates();
         Comment(version, 
        
         "\nClose Lots:  ", Close_Lots,
         "\nTP:   ", First_TP_Target, "  ", TP_Target_Increment,
         "\nSL1:  ", First_Stop_Target, "  ", First_Stop,
         "\nSL2:  ", Second_Stop_Target, "  ", Second_Stop,
         "\nSL3:  ", Third_Stop_Target,  "  ", Third_Stop,
         "\nTSL:  ", Trail_Stop_By,
         "\nMax Loss:  ", Max_Loss,
         "\n----------------------------",
         "\nOrder Open: ",OrderOpenPrice(),
         "\nPip Count: ", val,
         "\nNext TP:   ", nextTP,
         "\nCurr  SL:   ", sl,
         "\nTSL Trigger:  ", Trail_Trigger, "   ", trailon,
         "\nManaging:  ", mngMagic);


     }
}

//========== FUNCTION takeProfit
void takeProfit(int pips, int ticket)
{
   if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
   {
      if(pips >= nextTP)
      {
       
         if(OrderType()==1)    // 1 = OP_Sell
         {
            if(OrderCloseReliable(ticket, Close_Lots, Ask, 3, Lime))
            nextTP+=TP_Target_Increment;
            else
            Print("Error closing order : ",GetLastError());
         }
         else
         {
            if(OrderCloseReliable(ticket, Close_Lots, Bid, 3, Lime))
            nextTP+=TP_Target_Increment;
            else
            Print("Error closing order : ",GetLastError());
         }

      }

   }
}

//== end function



//========== FUNCTION moveStops
void checkStops(int pips,int ticket)
{
   if(sl==-1*Max_Loss && First_Stop != 0 && pips >= First_Stop_Target)
   {
      moveStops(ticket, First_Stop);
   }
   else if(sl==First_Stop && First_Stop != 0 && pips >= Second_Stop_Target && Second_Stop !=0)
   {
      moveStops(ticket,Second_Stop);
   }
   else if(sl==Second_Stop && Second_Stop != 0 && pips >= Third_Stop_Target && Third_Stop !=0)
   {
      moveStops(ticket,Third_Stop);
   }
   else if(Trail_Stop_By != 0 && pips >= Trail_Trigger && pips - Trail_Stop_By > sl)
   {
      Trail_Stop = pips - Trail_Stop_By;
      sl = Trail_Stop;
      trailon = " ON";  
   }
   if(pips <= sl) stopTrade(pips,OrderTicket());  
}

//== end function

//========== FUNCTION moveStops
void moveStops(int ticket,int stopDiff)
{
   if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
   {
      Print("moveStops called ",ticket, " ",stopDiff);
      if(OrderType()==1)     // 1 = OP_Sell
      {
      OrderModifySafe(ticket,OrderOpenPrice(),OrderOpenPrice()-stopDiff*Point, OrderTakeProfit(),0,Plum);
      sl=stopDiff;
      }
      else
      {
      OrderModifySafe(ticket,OrderOpenPrice(),OrderOpenPrice()+stopDiff*Point, OrderTakeProfit(),0,Plum);
      sl=stopDiff;
      }
   }
}

//== end function

//========== FUNCTION killTrades
void stopTrade(int pips, int ticket)
{
   if(OrderSelect(ticket, SELECT_BY_TICKET)==true)
   {
       if(OrderType()==1) OrderCloseReliable(ticket,OrderLots(),Ask,3,DarkViolet);
       else OrderCloseReliable(ticket,OrderLots(),Bid,3,DarkViolet);
       
    
   }
}
//== end function


