//+------------------------------------------------------------------+
//|                     Adjust open order when pending triggered.mq4 |
//|                                                            Keith |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Keith"
#property link      "http://www.metaquotes.net"

//--- input parameters
extern string    MagicLetters=" ";

extern bool      AdjustSL=true;
extern bool      AdjustTP=true;
extern int       OpenTicket=0 ;
extern double    Step ;
extern string    StopOrLimit ;

extern double    LotSizePT1;

extern double    LotSizePT2;

extern double    LotSizePT3;

extern double    LotSizePT4;

extern double    LotSizePT5;


#include <WinUser32.mqh>               // Needed to MessageBox

 bool   RunCode = true; 
 int PT;    // Counts how many pending orders.
 int NUM [6];
 double LS [6];
 
 
 
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
 int ERR; 
 int Check[6];
 string message;
 int y=0;
 int x;
 int ret;
 PT =0;
 NUM[0] = OpenTicket;
 
 if(MagicLetters==" ")
   {
   message = "No character input for MagicLetters. Please input again. Make sure that the MagicLetters are not being used on another chart";
    ret=MessageBox(message,"Error!", MB_OK|MB_ICONWARNING|MB_OK); // Message box
   }
if(Step==0)
   {
   message = "No input input for Step. Please input again.";
    ret=MessageBox(message,"Error!", MB_OK|MB_ICONWARNING|MB_OK); // Message box
   }

if(StopOrLimit =="S"||StopOrLimit =="s"||StopOrLimit =="stop") StopOrLimit ="Stop";
if(StopOrLimit =="L"||StopOrLimit =="l"||StopOrLimit =="limit") StopOrLimit ="Limit";

if(StopOrLimit=="Stop" || StopOrLimit=="Limit") {} else
 {
  message = "Wrong or no character input for StopOrLimit. Please input again.";
    ret=MessageBox(message,"Error!", MB_OK|MB_ICONWARNING|MB_OK); // Message box
    return(0);
 }


ObjectCreate("Message", OBJ_LABEL, 0, 0, 0);// Creating obj.
   ObjectSet("Message", OBJPROP_CORNER, 1);    // Reference corner
   ObjectSet("Message", OBJPROP_XDISTANCE, 10);// X coordinate
   ObjectSet("Message", OBJPROP_YDISTANCE, 20);// Y coordinate
  string text;
  
  ObjectCreate("Message2", OBJ_LABEL, 0, 0, 0);// Creating obj.
   ObjectSet("Message2", OBJPROP_CORNER, 1);    // Reference corner
   ObjectSet("Message2", OBJPROP_XDISTANCE, 10);// X coordinate
   ObjectSet("Message2", OBJPROP_YDISTANCE, 35);// Y coordinate
  string text2="Hello";
  
  ObjectCreate("Message3", OBJ_LABEL, 0, 0, 0);// Creating obj.
   ObjectSet("Message3", OBJPROP_CORNER, 1);    // Reference corner
   ObjectSet("Message3", OBJPROP_XDISTANCE, 10);// X coordinate
   ObjectSet("Message3", OBJPROP_YDISTANCE, 50);// Y coordinate
  string text3;
  
  ObjectSetText("Message","-",8,"Arial",CLR_NONE);  // Empty Labels
  ObjectSetText("Message2","-",8,"Arial",CLR_NONE);  // Empty Labels
  ObjectSetText("Message3","-",8,"Arial",CLR_NONE);  // Empty Labels
  
 
 
  //  Check internet connection
  if(!IsConnected())
    {
     message = "No connection to the broker's server. Please check your internet connection. If you are sure that your internet is connected, click on OK";
    ret=MessageBox(message,"Error!", MB_OK|MB_ICONWARNING|MB_OK); // Message box
    
    }
   if(!IsConnected())
    {
    message = "Still unable to connect to the server.No pending orders can be placed at this time";
    ret=MessageBox(message,"Error!", MB_OK|MB_ICONWARNING|MB_OK); // Message box
    }
 
  //  Check OpenTicket is valid

  OrderSelect(OpenTicket,SELECT_BY_TICKET);
  ERR = GetLastError();
  if(ERR!=0) Alert("Unable to identify Ticket number for OpenTrade");
  if(OrderCloseTime( ) !=0 || OpenTicket==0)
    {
    message = StringConcatenate("Ticket Number ", OpenTicket," is not valid as it has already been closed or does not exist. Please click on the smiley face and re-enter a valid ticket number") ;
    ret=MessageBox(message,"Error!", MB_OK|MB_ICONWARNING|MB_OK); // Message box
    RunCode = false;
    return(0); 
    }
  
 
 if(LotSizePT1!=0) {PT++; LS[1]= LotSizePT1;} //Count Pending Orders PT
 if(LotSizePT2!=0) {PT++; LS[2]= LotSizePT2;} //and set LS array
 if(LotSizePT3!=0) {PT++; LS[3]= LotSizePT3;}
 if(LotSizePT4!=0) {PT++; LS[4]= LotSizePT4;}
 if(LotSizePT5!=0) {PT++; LS[5]= LotSizePT5;}
 
 //Check if Global Variable exists, if it does assign value to NUM array
 int cnt = 0;
 for(x=1;x<=PT;x++)
  {
  string gv =StringConcatenate("NUM",MagicLetters,x); // First GV will be "NUMEURUSD1"
  if(GlobalVariableCheck(gv))
    {
    NUM[x]=GlobalVariableGet(gv) ;
    cnt++;
    }
  }
   
  
  if(cnt>0)
    {
    message="Click on No if pending orders have already been opened";
    ret=MessageBox(message,"Do you wish to open pending orders?", MB_YESNO); // Message box
    if(ret ==IDNO){RunCode=true; return(0);}
    }
  
 for(x=1;x<=PT;x++)
  {
  
  OrderSelect(NUM[x],SELECT_BY_TICKET);
  ERR = GetLastError();
  
  //if(OrderCloseTime( ) !=0 || ERR!=0) Check[x]=1; else Check[x]=0; //if Check=0,GV already has an open trade associated
  //Alert("Check ",x," = ",Check[x]);
  }
  
 //GlobalVariableSet("NUMEURUSD3",44380644);
 
 //------------Check if magicnumber already in use
 
 

 
 

  
  

 OrderSelect(OpenTicket,SELECT_BY_TICKET);
 string Pair =OrderSymbol( );
  if( OrderType( )==OP_BUY )
 string BuyOrSell ="Buy" ;
  if( OrderType( )==OP_SELL )
        BuyOrSell ="Sell" ;
 double OpenPrice =OrderOpenPrice( ) ;
 double OSL =OrderStopLoss( ) ;
 if(OSL!=0) {double SLpoints = MathAbs(OpenPrice-OSL);} else {SLpoints =0;}
 double OTP =OrderTakeProfit( ) ;
 if(OTP!=0) {double TPpoints = MathAbs(OpenPrice-OTP);} else {TPpoints =0;}
 

 if(BuyOrSell =="Buy" && StopOrLimit == "Limit")
 {int OType = 2; double SL = -SLpoints; double TP= TPpoints;
 double StepDir =-Step;} //code for OP_BUYLIMIT, SL , TP & Step + or -
 if(BuyOrSell =="Buy" && StopOrLimit == "Stop")
  {OType = 4;    SL = -SLpoints; TP= TPpoints;
  StepDir =Step;} //code for OP_BUYSTOP, SL , TP & Step + or -
 if(BuyOrSell =="Sell" && StopOrLimit == "Limit")
  {OType = 3;    SL = SLpoints; TP= -TPpoints;
  StepDir =Step;} //code for OP_SELLLIMIT, SL , TP & Step + or -
 if(BuyOrSell =="Sell" && StopOrLimit == "Stop")
  {OType = 5;    SL = SLpoints;  TP= -TPpoints;
  StepDir =-Step;} //code for OP_SELLLIMIT, SL , TP & Step + or -
  /*
  if(AdjustSL==true) {SL=SL;} else {SL=0;}
  if(AdjustTP==true) {TP=TP;} else {TP=0;}
  */
  //  Place pending Orders
  
 int ticket = 0;
 GetLastError();    //Make sure that last error is set to 0
 
  for(x=1;x<= PT; x++) //  PT is total of pending orders calculated earlier
   {
   double EPrice = OpenPrice+StepDir*x;
   if(SL==0) double ESL=0; else ESL =EPrice+SL;
   if(TP==0) double ETP=0; else ETP =EPrice+TP;  
   ticket = OrderSend( Pair,OType,LS[x],EPrice, 50,ESL,ETP,NULL,0,0,CLR_NONE) ;
   NUM[x]=ticket;
   gv =StringConcatenate("NUM",MagicLetters,x); // First GV will be "NUMEURUSD1"
   GlobalVariableSet(gv,ticket);
   ERR = GetLastError();
   
   if(ERR==4109)
     {
     ret=MessageBox("Trading is not allowed. Enable Checkbox 'Allow live trading' in the expert properties","ALERT", MB_OK|MB_ICONQUESTION|MB_OK); // Message box Alert();
     return(0);
     }
   }
  
  
   
   
  
   //-------------------------------------------------------------------
   
   
   
   
   
   

   
   
   
  
   
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   ObjectDelete("Message") ;
  ObjectDelete("Message2") ;
  ObjectDelete("Message3") ;
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
                                    
  if(RunCode == false)
  return(0) ;
  
 
// select pending order and see if it has triggered

/* If Pending ticket1 has triggered apply its TP and SL to OpenOrder
   If Pending ticket2 has triggered apply its TP and SL to OpenOrder + Pending ticket1
   If Pending ticket3 has triggered apply its TP and SL to OpenOrder + Pending tickets 1 + 2
   If Pending ticket4 has triggered apply its TP and SL to OpenOrder + Pending tickets 1 ,2 and 3

*/
 //----------------------  // Check if PendingTicket  exists and if has triggered 
                           //   PT is number of pending orders

 for (int Tr = PT; Tr>0; Tr--)   //Only process from number of pending orders backwards to 1
 {

  if(OrderSelect(NUM[Tr], SELECT_BY_TICKET) &&( OrderType() == OP_SELL || OrderType() == OP_BUY))
         {
         double TP = OrderTakeProfit( );     //Get values of SL and TP on triggered order
         double SL = OrderStopLoss( )  ;
         
         string text = StringConcatenate ("Pending 0rder ",NUM[Tr]," @ ",DoubleToStr(OrderOpenPrice(),Digits)," has triggered");
         
         ObjectSetText("Message3",text,8,"Arial",Red);  // Changing label
         
         
   //----Nested operation to modify TP and SL on  previously triggered orders and Open order 
   
          
             for(int mod = Tr-1; mod>=0;mod--)
               {        
                OrderSelect(NUM[mod], SELECT_BY_TICKET);
                int CHK =0 ;
                if(AdjustTP==true && OrderTakeProfit( )!= TP)    //need to modify TP
                CHK++ ;
                if(AdjustSL==true && OrderStopLoss( )!= SL)     //need to modify SL 
                CHK++ ;
          
                if(CHK >0 )
                 {
                 if(AdjustSL==true) {double TSL=SL;} else {TSL=0;}
                 if(AdjustTP==true) {double TTP=TP;} else {TTP=0;}
                 OrderModify( NUM[mod],OrderOpenPrice(),TSL,TTP,0,CLR_NONE); //Modify open Order
                 
                 }
               }
            break;
         }
 }

  //If OpenTicket has been closed delete all remaining pending orders

   if(OrderSelect(OpenTicket,SELECT_BY_TICKET) && OrderCloseTime( ) !=0) //order closed so delete all remaining pending orders.
      {
      for (Tr = PT; Tr>0; Tr--)   //Only process from number of pending orders backwards to 1
       {
        OrderSelect(NUM[Tr],SELECT_BY_TICKET);
         
         if(((OrderType( )== OP_SELLLIMIT || OrderType( )== OP_SELLSTOP)
            || (OrderType( )== OP_BUYLIMIT || OrderType( )== OP_BUYSTOP))
            &&  (OrderCloseTime( ) ==0))     
          OrderDelete(NUM[Tr]);
           else
           {
           if(OrderType() == OP_BUY) double Price = Bid;
           if(OrderType() == OP_SELL) Price = Ask;
           if(OrderCloseTime( ) ==0) OrderClose(NUM[Tr],OrderLots(),Price,50,CLR_NONE);
           }
       }
      }   
    
     





 
 
 
 
 
    
   
    


     
     
     
       
      
  
  
   
//----
   return(0);
  }
//+------------------------------------------------------------------+