//+------------------------------------------------------------------+
//|                                                    LastOrder.mqh |
//|                                                   A.Lopatin 2014 |
//|                                              diver.stv@gmail.com |
//+------------------------------------------------------------------+
#property copyright "A.Lopatin 2014"
#property link      "diver.stv@gmail.com"
//#property strict
#property version   "1.00"
//+------------------------------------------------------------------+
//|    get_last_order() returns ticket number of the last order.     |
//|    The function returns -1 value when it havent found last order.|
//|    Arguments: yourmagic - Magic Number ID filtering orders. When 0   |
//|    it is not used.                                               |
//|    type - type order (buy, sell, sell limit, buy limit,          |
//|    sell stop, buy stop) for filtering orders.                    |
//|    mode - pool of orders: MODE-TRADES - trade orders,            |
//|    MODE_HISTORY - closed orders.                                 |
//+------------------------------------------------------------------+
int get_last_order_live(int yourmagic,int mode=MODE_TRADES)
  {
   int     orders_total  = 0, ticket  = -1;
   string  symbol        = Symbol();
   datetime opn_time     = 0, ord_time = 0;

   if(mode==MODE_HISTORY)
      orders_total=OrdersHistoryTotal();
   else
      orders_total=OrdersTotal();

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,mode))
        {
         if(OrderSymbol()!=symbol)
            continue;
         if(OrderType()==OP_BUY || OrderType()==OP_SELL)
           {
            if(OrderMagicNumber()==yourmagic || yourmagic==0)
              {
               if(mode==MODE_TRADES)
                  ord_time=OrderOpenTime();
               else
                  ord_time=OrderCloseTime();

               if(ord_time>opn_time)
                 {
                  opn_time=ord_time;
                  ticket=OrderTicket();
                 }
              }
           }
        }
     }//end for

   return(ticket);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+


int get_last_order(int yourmagic,int type=-1,int mode=MODE_TRADES)
  {
   int     orders_total  = 0, ticket  = -1;
   string  symbol        = Symbol();
   datetime opn_time     = 0, ord_time = 0;

   if(mode==MODE_HISTORY)
      orders_total=OrdersHistoryTotal();
   else
      orders_total=OrdersTotal();

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,mode))
        {
         if(OrderSymbol()!=symbol)
            continue;
         if(OrderType()==type || type==-1)
           {
            if(OrderMagicNumber()==yourmagic || yourmagic==0)
              {
               if(mode==MODE_TRADES)
                  ord_time=OrderOpenTime();
               else
                  ord_time=OrderCloseTime();

               if(ord_time>opn_time)
                 {
                  opn_time=ord_time;
                  ticket=OrderTicket();
                 }
              }
           }
        }
     }//end for

   return(ticket);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int get_last_order4(int yourmagic,string sym,int mode=MODE_TRADES)
  {
   int     orders_total  = 0, ticket  = -1;
   string  symbol        = Symbol();
   datetime opn_time     = 0, ord_time = 0;

   if(mode==MODE_HISTORY)
      orders_total=OrdersHistoryTotal();
   else
      orders_total=OrdersTotal();

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,mode))
        {
         //if(OrderSymbol()!=symbol)
         //continue;
         if(OrderType()==OP_BUY || OrderType()==OP_SELL)
           {
            if(OrderMagicNumber()==yourmagic)
              {
               if(OrderSymbol()==sym)
                 {
                  if(mode==MODE_TRADES)
                     ord_time=OrderOpenTime();
                  else
                     ord_time=OrderCloseTime();

                  if(ord_time>opn_time)
                    {
                     opn_time=ord_time;
                     ticket=OrderTicket();
                    }
                 }

              }
           }
        }
     }//end for

   return(ticket);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int get_last_order3(int yourmagic,string sym,int type=-1,int mode=MODE_TRADES)
  {
   int     orders_total  = 0, ticket  = -1;
   string  symbol        = Symbol();
   datetime opn_time     = 0, ord_time = 0;

   if(mode==MODE_HISTORY)
      orders_total=OrdersHistoryTotal();
   else
      orders_total=OrdersTotal();

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,mode))
        {
         //if(OrderSymbol()!=symbol)
         //continue;
         if(OrderType()==type || type==-1)
           {
            if(OrderMagicNumber()==yourmagic)
              {
               if(OrderSymbol()==sym)
                 {
                  if(mode==MODE_TRADES)
                     ord_time=OrderOpenTime();
                  else
                     ord_time=OrderCloseTime();

                  if(ord_time>opn_time)
                    {
                     opn_time=ord_time;
                     ticket=OrderTicket();
                    }
                 }

              }
           }
        }
     }//end for

   return(ticket);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int get_last_order_Any(int type=-1,int mode=MODE_TRADES)
  {
   int     orders_total  = 0, ticket  = -1;
   string  symbol        = Symbol();
   datetime opn_time     = 0, ord_time = 0;

   if(mode==MODE_HISTORY)
      orders_total=OrdersHistoryTotal();
   else
      orders_total=OrdersTotal();

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,mode))
        {
         if(OrderSymbol()!=symbol)
            continue;
         if(OrderType()==type || type==-1)
           {
            //if(OrderMagicNumber()==yourmagic || yourmagic==0)
              {
               if(mode==MODE_TRADES)
                  ord_time=OrderOpenTime();
               else
                  ord_time=OrderCloseTime();

               if(ord_time>opn_time)
                 {
                  opn_time=ord_time;
                  ticket=OrderTicket();
                 }
              }
           }
        }
     }//end for

   return(ticket);
  }
//+------------------------------------------------------------------+
//|    get_first_order() returns ticket number of the first order.   |
//|    The function returns -1 value when it havent found first order|
//|    Arguments: yourmagic - Magic Number ID filtering orders. When 0   |
//|    it is not used.                                               |
//|    type - type order (buy, sell, sell limit, buy limit,          |
//|    sell stop, buy stop) for filtering orders.                    |
//|    mode - pool of orders: MODE-TRADES - trade orders,            |
//|    MODE_HISTORY - closed orders.                                 |
//+------------------------------------------------------------------+
int get_first_order(int yourmagic,int type=-1,int mode=MODE_TRADES)
  {
   int     orders_total  = 0, ticket  = -1;
   string  symbol        = Symbol();
   datetime opn_time     = 2*TimeCurrent(), ord_time = 0;

   if(mode==MODE_HISTORY)
      orders_total=OrdersHistoryTotal();
   else
      orders_total=OrdersTotal();

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,mode))
        {
         if(OrderSymbol()!=symbol)
            continue;
         if(OrderType()==type || type==-1)
           {
            if(OrderMagicNumber()==yourmagic || yourmagic==0)
              {
               if(mode==MODE_TRADES)
                  ord_time=OrderOpenTime();
               else
                  ord_time=OrderCloseTime();

               if(ord_time<opn_time)
                 {
                  opn_time=ord_time;
                  ticket=OrderTicket();
                 }
              }
           }
        }
     }//end for

   return(ticket);
  }
//+------------------------------------------------------------------+
//|   order_lots() returns trade volume by ticket number.            |
//|   Arguments: ticket - ticket number of the order.                |
//|    mode - pool of orders: MODE-TRADES - trade orders,            |
//|    MODE_HISTORY - closed orders.                                 |
//+------------------------------------------------------------------+
double order_lots(int ticket,int mode=MODE_TRADES)
  {
   double _Lots=0;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      _Lots=OrderLots();

   return(_Lots);
  }
//+----------------------------------------------------------------------+
//| order_comment() returns string comment of the order by ticket number |
//|   Arguments: ticket - ticket number of the order.                    |
//|    mode - pool of orders: MODE-TRADES - trade orders,                |
//|    MODE_HISTORY - closed orders.                                     |
//+----------------------------------------------------------------------+
string order_comment(int ticket,int mode=MODE_TRADES)
  {
   string str="";

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      str=OrderComment();

   return(str);
  }
//+----------------------------------------------------------------------+
//| order_type() returns type of the order by ticket number              |
//|   Arguments: ticket - ticket number of the order.                    |
//|    mode - pool of orders: MODE-TRADES - trade orders,                |
//|    MODE_HISTORY - closed orders.                                     |
//+----------------------------------------------------------------------+
int order_type(int ticket,int mode=MODE_TRADES)
  {
   int type=-1;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      type=OrderType();

   return(type);
  }
//+----------------------------------------------------------------------+
//| order_open_price() returns open price of the order by ticket number. |
//|   Arguments: ticket - ticket number of the order.                    |
//|    mode - pool of orders: MODE-TRADES - trade orders,                |
//|    MODE_HISTORY - closed orders.                                     |
//+----------------------------------------------------------------------+
double order_open_price(int ticket,int mode=MODE_TRADES)
  {
   double price=-1;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      price=OrderOpenPrice();

   return(price);
  }
//+-----------------------------------------------------------------------+
//| order_close_price() returns close price of the order by ticket number.|
//|   Arguments: ticket - ticket number of the order.                     |
//|    mode - pool of orders: MODE-TRADES - trade orders,                 |
//|    MODE_HISTORY - closed orders.                                      |
//+-----------------------------------------------------------------------+
double order_close_price(int ticket,int mode=MODE_TRADES)
  {
   double price=-1;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      price=OrderClosePrice();

   return(price);
  }
//+-----------------------------------------------------------------------+
//| order_open_time() returns open time of the order by ticket number.    |
//|   Arguments: ticket - ticket number of the order.                     |
//|    mode - pool of orders: MODE-TRADES - trade orders,                 |
//|    MODE_HISTORY - closed orders.                                      |
//+-----------------------------------------------------------------------+
datetime order_open_time(int ticket,int mode=MODE_TRADES)
  {
   datetime time=0;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      time=OrderOpenTime();

   return(time);
  }
//+-----------------------------------------------------------------------+
//| order_close_time() returns close time of the order by ticket number.  |
//|   Arguments: ticket - ticket number of the order.                     |
//|    mode - pool of orders: MODE-TRADES - trade orders,                 |
//|    MODE_HISTORY - closed orders.                                      |
//+-----------------------------------------------------------------------+
datetime order_close_time(int ticket,int mode=MODE_TRADES)
  {
   datetime time=0;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
      time=OrderCloseTime();

   return(time);
  }

// --- Triggers of the closing the orders
#define CLOSE_BY_TP        1   // by takeprofit    
#define CLOSE_BY_SL        -1  // by stoploss
#define CLOSE_BY_MANUAL    0   // manual
//+--------------------------------------------------------------------------+
//| close_by() returns the trigger of closing the order:by takeprofit (1),   |
//| by stoploss (-1), manual(0).It is defined based on comment of the order. |
//| Arguments: ticket - ticket number of the order.                          |
//|            mode - pool of orders: MODE-TRADES - trade orders,            |
//|            MODE_HISTORY - closed orders.                                 |
//+--------------------------------------------------------------------------+
int close_by(int ticket,int mode=MODE_TRADES)
  {
   int retn=CLOSE_BY_MANUAL;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
     {

      if(-1!=StringFind(OrderComment(),"[sl]",0))
        {
         retn=CLOSE_BY_SL;
        }
      else if(-1!=StringFind(OrderComment(),"[tp]",0))
        {
         retn=CLOSE_BY_TP;
        }
     }

   return(retn);
  }
//+-------------------------------------------------------------------------+
//| close_by2() returns the trigger of closing the order:by takeprofit (1), |
//| by stoploss (-1), manual(0).                                            |
//| It is defined based on the close price and open price of the order.     |
//| Arguments: ticket - ticket number of the order.                         |
//|            mode - pool of orders: MODE-TRADES - trade orders,           |
//|            MODE_HISTORY - closed orders.                                |
//+-------------------------------------------------------------------------+
int close_by2(int ticket,int mode=MODE_TRADES)
  {
   int retn=CLOSE_BY_MANUAL;

   if(ticket>0 && OrderSelect(ticket,SELECT_BY_TICKET,mode))
     {
      if(MathAbs(OrderClosePrice()-OrderStopLoss())<=1*Point)
         retn=CLOSE_BY_SL;
      else if(MathAbs(OrderClosePrice()-OrderTakeProfit())<=1*Point)
                                                            retn=CLOSE_BY_TP;
     }

   return(retn);
  }
//+-----------------------------------------------------------------------------+
//| orders_count() returns the count of the opened orders.                      |
//| Arguments: yourmagic - Magic Number ID filtering orders. When 0 it is not used. |
//| type - orders type (buy, sell, sell limit, buy limit, sell stop, buy stop)  |
//| for filtering orders. When -1 is not used.                                  |
//| comment - comment string of the orders. When "" (empty) is not used.        |
//+-----------------------------------------------------------------------------+
int orders_count(int yourmagic,int type=-1,string comment="")
  {
   int orders_total=OrdersTotal(),count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()!=Symbol())
            continue;
         if((OrderMagicNumber()==yourmagic || yourmagic==0)
            && (OrderType()==type || type==-1))
           {
            if(comment=="" || OrderComment()==comment)
               count++;
           }
        }
     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_symbol(int yourmagic,string symb)
  {
   int orders_total=OrdersTotal(),count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && OrderMagicNumber()==yourmagic)
           {
            count++;
           }
        }

     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_symbol_anyLive(string symb)
  {
   int orders_total=OrdersTotal(),count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && (OrderType()==OP_BUY || OrderType()==OP_SELL))
           {
            count++;
           }
        }

     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_symbol_anyPending(string symb)
  {
   int orders_total=OrdersTotal(),count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT))
           {
            count++;
           }
        }

     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double profit_symbol(string symb)
  {
   int orders_total=OrdersTotal();
   double count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && (OrderType()==OP_BUY || OrderType()==OP_SELL))
           {
            count=count+OrderProfit();
           }
        }

     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double commission_array_magic(int &magic[])
  {
   double count=0;
   for(int y=0;y<ArraySize(magic);y++)
     {
      for(int i=0; i<OrdersTotal(); i++)
        {
         if(OrderSelect(i,SELECT_BY_POS))
           {
            if(OrderMagicNumber()==magic[y])
              {
               count=count+OrderCommission();
              }
           }

        }
     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double profit_symbol2(string symb,int yourmagic)
  {
   int orders_total=OrdersTotal();
   double count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && OrderMagicNumber()==yourmagic && (OrderType()==OP_BUY || OrderType()==OP_SELL))
           {
            count=count+OrderProfit()+OrderCommission();
           }
        }

     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double commission_symbol2(string symb,int yourmagic)
  {
   int orders_total=OrdersTotal();
   double count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && OrderMagicNumber()==yourmagic && (OrderType()==OP_BUY || OrderType()==OP_SELL))
           {
            count=count+OrderCommission();
           }
        }

     }

   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double lots_symbolLive(string symb,int side)
  {
   int orders_total=OrdersTotal();
   double count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && OrderType()==side)
           {
            count=count+OrderLots();
           }
        }

     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double lots_symbolLive2(string symb,int side,int yourmagic)
  {
   int orders_total=OrdersTotal();
   double count=0;

   for(int i=0; i<orders_total; i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderSymbol()==symb && OrderType()==side && OrderMagicNumber()==yourmagic)
           {
            count=count+OrderLots();
           }
        }

     }
   return(count);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| no any order, no live order and no pending order                 |
//+------------------------------------------------------------------+

bool is_no_order(int &yourmagic)
  {
   if(orders_count(yourmagic)==0)
     {
      return(true);
     }
   else
     {
      return(false);
     }

  }
//+------------------------------------------------------------------+
bool is_market_order(int &yourmagic) //either buy or sell
  {
   if((orders_count(yourmagic,OP_BUY)==1 && orders_count(yourmagic,OP_SELL)==0)
      || (orders_count(yourmagic,OP_BUY)==0 && orders_count(yourmagic,OP_SELL)==1)
      )
     {
      return(true);
     }
   else
     {
      return(false);
     }

  }
//+------------------------------------------------------------------+

void ftx2(int ticket,int markingtrailingpoints=60,int trailingpoints=20)
  {
   double spread;
   spread=(Ask-Bid);
   double stoppoint=MarketInfo(Symbol(),MODE_STOPLEVEL);
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      double newstop=0;
      bool ok=false;
      if(OrderType()==OP_BUY)
        {
         if((OrderStopLoss()<OrderOpenPrice() || OrderStopLoss()==0) && Bid>OrderOpenPrice()+((20+stoppoint)*Point))
           {
            newstop=OrderOpenPrice()+spread;
            if(OrderStopLoss()==0)
              {
               ok=true;
              }
            else if(OrderStopLoss()!=0 && newstop>OrderStopLoss())
              {
               ok=true;
              }

           }
         if(OrderStopLoss()!=0 && OrderStopLoss()>=OrderOpenPrice() && Bid>=OrderStopLoss()+markingtrailingpoints*Point)
           {
            newstop=OrderStopLoss()+trailingpoints*Point;
            if(newstop>OrderStopLoss())
               ok=true;
           }
        }
      else
      if(OrderType()==OP_SELL)
        {
         if((OrderStopLoss()<OrderOpenPrice() || OrderStopLoss()==0) && Ask<OrderOpenPrice()-((20+stoppoint)*Point))
           {
            newstop=OrderOpenPrice()-spread;
            if(OrderStopLoss()==0)
              {
               ok=true;
              }
            else if(OrderStopLoss()!=0 && newstop<OrderStopLoss())
              {
               ok=true;
              }

           }
         if(OrderStopLoss()!=0 && OrderStopLoss()>=OrderOpenPrice() && Ask<=OrderStopLoss()-markingtrailingpoints*Point && newstop<OrderStopLoss())
           {
            newstop=OrderStopLoss()-trailingpoints*Point;
            if(newstop<OrderStopLoss())
               ok=true;
           }
        }

      if(newstop!=0 && ok)
        {
         //newstop=NormalizeDouble(newstop,digits);
         //ModStopLoss(OrderTicket(),newstop,clrLightBlue);
         if(OrderModify(OrderTicket(),OrderOpenPrice(),newstop,OrderTakeProfit(),OrderExpiration(),clrLightBlue))
           {
            Print("Mod Done");
           }

        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_simple()
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         //if(OrderSymbol()==Symbol())
         //{
         count++;
         //}
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count1(int yourmagic)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic && OrderSymbol()==Symbol())
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count2(int yourmagic,int type)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic && OrderType()==type && OrderSymbol()==Symbol())
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_live(int yourmagic)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic && (OrderType()==OP_BUY || OrderType()==OP_SELL) && OrderSymbol()==Symbol())
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_pending_this(int yourmagic)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic
            && (OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT)
            && OrderSymbol()==Symbol())
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void delete_pending(int yourmagic)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==yourmagic && OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUYLIMIT
               ||OrderType()==OP_BUYSTOP
               ||OrderType()==OP_SELLSTOP
               ||OrderType()==OP_SELLLIMIT)
              {
               int delok=OrderDelete(OrderTicket(),clrAntiqueWhite);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void delete_pending_bycomment(int yourmagic,string ordcomment)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==yourmagic && OrderSymbol()==Symbol() && OrderComment()==ordcomment)
           {
            if(OrderType()==OP_BUYLIMIT
               ||OrderType()==OP_BUYSTOP
               ||OrderType()==OP_SELLSTOP
               ||OrderType()==OP_SELLLIMIT)
              {
               int delok=OrderDelete(OrderTicket(),clrAntiqueWhite);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_live2(int yourmagic,int type)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic && OrderType()==type && OrderSymbol()==Symbol())
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_live3(int yourmagic,int type,string sym)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic && OrderType()==type && OrderSymbol()==sym)
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_live_type(int type)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderType()==type && OrderSymbol()==Symbol())
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int order_count_live_type2(int _magic,int type)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderType()==type && OrderSymbol()==Symbol() && OrderMagicNumber()==_magic)
           {
            count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+

int order_period_seconds(int ticket)
  {
   datetime age=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      datetime open;

      open=OrderOpenTime();
      age=TimeCurrent()-open;
     }

   return((int)age);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double order_profit(int ticket)
  {
   double profit=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      profit=OrderProfit();
     }
   return(profit);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double order_profitHistory(int ticket)
  {
   double profit=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_HISTORY))
     {
      profit=OrderProfit();
     }
   return(profit);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double order_lotsHistory(int ticket)
  {
   double _Lots=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_HISTORY))
     {
      _Lots=OrderLots();
     }
   return(_Lots);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double order_stoploss(int ticket)
  {
   double stop=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      stop=OrderStopLoss();
     }
   return(stop);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void close_order_immediate(int ticket)
  {
   double price=Bid;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      if(OrderType()==OP_BUY)
        {
         price=MarketInfo(OrderSymbol(),MODE_BID);
        }
      if(OrderType()==OP_SELL)
        {
         price=MarketInfo(OrderSymbol(),MODE_ASK);
        }
      Print(__FUNCTION__,", ",OrderClose(OrderTicket(),OrderLots(),price,2));
      while(IsTradeContextBusy())
        {
         Sleep(100);
        }
     }
  }
//+------------------------------------------------------------------+
double getBreakEven(int yourmagic,int ordertype)
  {
   double sumWeight=0;
   double sumProduct=0;

   int count=0;

   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
        {
         if(OrderType()==ordertype && OrderMagicNumber()==yourmagic)
           {
            count++;
            sumWeight=sumWeight+OrderLots();
            sumProduct=sumProduct+(OrderLots()*OrderOpenPrice());
           }
        }
     }

   if(count>1 && sumWeight>0)
     {
      return(NormalizeDouble(sumProduct/sumWeight,
             (int)MarketInfo(OrderSymbol(),MODE_DIGITS))
             );
     }
   else return(-1);
  }
//+------------------------------------------------------------------+
bool order_modify_stoploss(int ticket,double stops,color yourcolor=clrPink)
  {
   bool modok=false;
   if(OrderSelect(ticket,SELECT_BY_TICKET)==true)
     {

      modok=OrderModify(OrderTicket(),OrderOpenPrice(),stops,OrderTakeProfit(),OrderExpiration(),yourcolor);

     }
   return(modok);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool order_modify_takeprofit(int ticket,double take,color yourcolor=clrPink)
  {
   bool modok=false;
   if(OrderSelect(ticket,SELECT_BY_TICKET)==true)
     {

      modok=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),take,OrderExpiration(),yourcolor);

     }
   return(modok);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void order_modify_takeprofit2(int ticket,double offset,color yourcolor=clrPink)
  {
   double newtp=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      if(OrderType()==OP_BUY || OrderType()==OP_BUYLIMIT || OrderType()==OP_BUYSTOP)
        {
         newtp=OrderOpenPrice()+NormalizeDouble(offset,Digits);
        }
      if(OrderType()==OP_SELL || OrderType()==OP_SELLLIMIT || OrderType()==OP_SELLSTOP)
        {
         newtp=OrderOpenPrice()-NormalizeDouble(offset,Digits);
        }
      if(newtp!=OrderOpenPrice())
        {
         bool modok=OrderModify(OrderTicket(),
                                OrderOpenPrice(),
                                OrderStopLoss(),
                                newtp,
                                OrderExpiration(),yourcolor);
        }

     }
  }
//+------------------------------------------------------------------+
double order_loss_point(int ticket,int mode=0)
                                            /*mode 0 = return in point, mode 1=return in decimal*/
  {
   int retVal=0;
   double k=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)==true)
     {
      if(OrderType()==OP_BUY && OrderOpenPrice()>Bid)
        {
         k=OrderOpenPrice()-Bid;
        }
      else if(OrderType()==OP_SELL && OrderOpenPrice()<Ask)
        {
         k=Ask-OrderOpenPrice();
        }
      else return(0);
     }

   if(k>0)
     {
      retVal=(int)(k*MathPow(10,MarketInfo(OrderSymbol(),MODE_DIGITS)));
     }
   else return(-1);

   switch(mode)
     {
      case  0:
         return(NormalizeDouble(retVal,0));
         break;
      case  1:
         return(NormalizeDouble(k,(int)MarketInfo(OrderSymbol(),MODE_DIGITS)));
         break;
      default:
         return(NormalizeDouble(retVal,0));
         break;
     }

  }
//+------------------------------------------------------------------+
bool IsAnOrder(int yourmagic)
  {
   if((order_count2(yourmagic,OP_BUY)==1 && order_count2(yourmagic,OP_SELL)==0)
      && (order_count2(yourmagic,OP_BUY)==0 && order_count2(yourmagic,OP_SELL)==1)
      )
     {
      return(true);
     }
   else return(false);
  }
//+------------------------------------------------------------------+
int HowManyOrder(int yourmagic)
  {
   int order=0;
   order=order_count2(yourmagic,OP_BUY)+order_count2(yourmagic,OP_SELL);
   return(order);
  }
//+------------------------------------------------------------------+
double order_takeprofit(int ticket)
  {
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      return(OrderTakeProfit());
     }
   else return(0);
  }
//+------------------------------------------------------------------+
//double order_stoploss(int ticket)
//  {
//   if(OrderSelect(ticket,SELECT_BY_TICKET))
//     {
//      return(OrderStopLoss());
//     }
//   else return(0);
//  }

double order_loss(int ticket,int mode=0)
                                      /*mode 0 = return in point, mode 1=return in decimal*/
  {
//int retVal=0;
   double k=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)==true)
     {
      if(OrderType()==OP_BUY && OrderOpenPrice()>Bid)
        {
         k=OrderOpenPrice()-Bid;
        }
      else if(OrderType()==OP_SELL && OrderOpenPrice()<Ask)
        {
         k=Ask-OrderOpenPrice();
        }
      else return(0);
     }
   return(k);
  }
//+------------------------------------------------------------------+
bool GroupModifyTargetPrice(int __MN,int type,double price,double additionProfit)
  {
   bool modok=true;
//---
   if(type==OP_BUY)
     {
      price=price+additionProfit;
     }
//---
   if(type==OP_SELL)
     {
      price=price-additionProfit;
     }
//---
   price=NormalizeDouble(price,Digits);
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {

         //---
         if(OrderMagicNumber()==__MN && OrderSymbol()==Symbol() && OrderType()==type)
           {

            if(price!=OrderTakeProfit())
              {
               modok=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),price,OrderExpiration(),clrDarkKhaki);
               while(IsTradeContextBusy())
                 {
                  Sleep(200);
                 }
               if(GetLastError()>0)
                 {
                  Print(__FUNCTION__,":: error modifying order");
                 }
              }
           }
        }

     }
   return(modok);
  }
//+------------------------------------------------------------------+
bool GroupModifyStoploss(int __MN,int type,double price)
  {
   bool modok=true;
//---
//if(type==OP_BUY)
//     {
//      price=price+additionProfit;
//     }
////---
//   if(type==OP_SELL)
//     {
//      price=price-additionProfit;
//     }
//---
   price=NormalizeDouble(price,Digits);
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {

         //---
         if(OrderMagicNumber()==__MN && OrderSymbol()==Symbol() && OrderType()==type)
           {

            if(price!=OrderStopLoss())
              {
               modok=OrderModify(OrderTicket(),OrderOpenPrice(),price,OrderTakeProfit(),OrderExpiration(),clrDarkGreen);
               while(IsTradeContextBusy())
                 {
                  Sleep(200);
                 }
               if(GetLastError()>0)
                 {
                  Print(__FUNCTION__,":: error modifying order");
                 }
              }
           }
        }

     }
   return(modok);
  }
//+------------------------------------------------------------------+
bool GroupCheckTargetPrice(int __MN,int type,double checkprice=0)
  {
   bool modok=true;
   double sametp=0;
   if(checkprice==0)
     {
      sametp=0;
     }
   else
     {
      sametp=NormalizeDouble(checkprice,Digits);
     }
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         //price=NormalizeDouble(price,Digits);
         if(OrderMagicNumber()==__MN && OrderSymbol()==Symbol() && OrderType()==type)
           {
            if(sametp==0)
              {
               sametp=OrderTakeProfit();
              }
            else
              {
               modok=modok && OrderTakeProfit()==sametp;
              }

           }
        }

     }
   return(modok);
  }
//+------------------------------------------------------------------+
double order_sum_profit(int __MN)
  {
   double sprofit=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         sprofit=sprofit+OrderProfit();
        }
     }
   return(sprofit);
  }
//+------------------------------------------------------------------+
void order_close_ALL(int __MN)
  {
   Print(__FUNCTION__+":: start force closing''''''''''''");
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderMagicNumber()==__MN)
        {
         double exe=MarketInfo(Symbol(),MODE_BID);
         if(OrderType()==OP_BUY) exe=MarketInfo(Symbol(),MODE_BID);
         if(OrderType()==OP_SELL) exe=MarketInfo(Symbol(),MODE_ASK);

         bool closeok=OrderClose(OrderTicket(),OrderLots(),exe,10,clrRed);
         while(IsTradeContextBusy())
           {
            Sleep(300);
           }
         if(closeok)
           {
            Print(__FUNCTION__+":: force closing #"+IntegerToString(OrderTicket()));
           }
        }
     }
   Print(__FUNCTION__+":: end force closing''''''''''''");
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void order_close_ALL_SYMBOL()
  {
   Print(__FUNCTION__+":: start force closing''''''''''''");
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         double exe=MarketInfo(Symbol(),MODE_BID);
         if(OrderType()==OP_BUY) exe=MarketInfo(Symbol(),MODE_BID);
         if(OrderType()==OP_SELL) exe=MarketInfo(Symbol(),MODE_ASK);

         bool closeok=OrderClose(OrderTicket(),OrderLots(),exe,10,clrGray);
         while(IsTradeContextBusy())
           {
            Sleep(300);
           }
         if(closeok)
           {
            Print(__FUNCTION__+":: force closing #"+IntegerToString(OrderTicket()));
           }
        }
     }
   Print(__FUNCTION__+":: end force closing''''''''''''");
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void order_close_ALL_SYMBOL2(int _magic)
  {
   Print(__FUNCTION__+":: start force closing''''''''''''");
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {

         if(OrderMagicNumber()==_magic)
           {

            double exe=MarketInfo(Symbol(),MODE_BID);
            if(OrderType()==OP_BUY) exe=MarketInfo(Symbol(),MODE_BID);
            if(OrderType()==OP_SELL) exe=MarketInfo(Symbol(),MODE_ASK);

            bool closeok=OrderClose(OrderTicket(),OrderLots(),exe,10,clrRed);
            while(IsTradeContextBusy())
              {
               Sleep(300);
              }
            if(closeok)
              {
               Print(__FUNCTION__+":: force closing #"+IntegerToString(OrderTicket()));
              }
           }
        }
     }
   Print(__FUNCTION__+":: end force closing''''''''''''");
  }
//+------------------------------------------------------------------+
double order_profit_points(int ticket)
  {
   double gainpoints=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      if(OrderProfit()>0)
        {
         gainpoints=OrderProfit()/(OrderLots()*MarketInfo(OrderSymbol(),MODE_LOTSIZE));
        }
     }
   gainpoints=NormalizeDouble(gainpoints,(int)MarketInfo(OrderSymbol(),MODE_DIGITS));
   return(gainpoints);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double order_points(int ticket)
  {
   double gainpoints=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      //if(OrderProfit()>0)
      //{
      //gainpoints=OrderProfit()/(OrderLots()*MarketInfo(OrderSymbol(),MODE_LOTSIZE));
      if(OrderType()==OP_BUY)
        {
         gainpoints=Bid-OrderOpenPrice();
        }
      if(OrderType()==OP_SELL)
        {
         gainpoints=OrderOpenPrice()-Ask;
        }
      //}
     }
   gainpoints=NormalizeDouble(gainpoints,(int)MarketInfo(OrderSymbol(),MODE_DIGITS));
   return(gainpoints);
  }
//+------------------------------------------------------------------+
double order_profit_points2(int ticket)
  {
   double gainpoints=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      if(OrderProfit()>0)
        {
         gainpoints=OrderProfit()/(OrderLots()*MarketInfo(OrderSymbol(),MODE_LOTSIZE));
        }
     }
   gainpoints=NormalizeDouble(gainpoints,(int)MarketInfo(OrderSymbol(),MODE_DIGITS));
   return(gainpoints*MathPow(10,Digits));
  }
//+------------------------------------------------------------------+
double orderGapToOpenPrice(int ticket)
  {
   double gainpoints=0;
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {

      gainpoints=OrderProfit()/(OrderLots()*MarketInfo(OrderSymbol(),MODE_LOTSIZE));

     }
   gainpoints=NormalizeDouble(gainpoints,(int)MarketInfo(OrderSymbol(),MODE_DIGITS));
   return(gainpoints);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int MyOrdersTotal(int yourmagic)
  {
   int count=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderMagicNumber()==yourmagic && OrderSymbol()==Symbol())
        {
         count++;
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double magic_profit(int yourmagic)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic)
           {
            sum=sum+OrderProfit();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double magic_lotsize(int yourmagic)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderMagicNumber()==yourmagic)
           {
            sum=sum+OrderLots();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double symbol_profit()
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderSymbol()==Symbol())
           {
            sum=sum+OrderProfit();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+-------------------------------------------------------------F-----+
double symbol_profit2(int _magic,int type)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==_magic && OrderType()==type)
           {
            sum=sum+OrderProfit();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double sum_commissions(int _magic,int type)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==_magic && OrderType()==type)
           {
            sum=sum+OrderCommission();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+-------------------------------------------------------------F-----+
double symbol_profit_magic(int _magic)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==_magic)
           {
            sum=sum+OrderProfit();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double type_profit(int side,int yourmagic)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderType()==side && OrderMagicNumber()==yourmagic)
           {
            sum=sum+OrderProfit();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double type_lot(int side,int yourmagic)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderType()==side && OrderMagicNumber()==yourmagic)
           {
            sum=sum+OrderLots();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double order_type_profit(int type)
  {
   double sum=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)==true)
        {
         if(OrderSymbol()==Symbol() && OrderType()==type)
           {
            sum=sum+OrderProfit();
           }
        }
     }
   return(sum);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void close_symbol()
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_BUY || OrderType()==OP_SELL)
           {
            close_order_immediate(OrderTicket());
            while(IsTradeContextBusy())
              {
               Sleep(1000);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
void close_magic(int yourmagic)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()==yourmagic)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               close_order_immediate(OrderTicket());
               while(IsTradeContextBusy())
                 {
                  Sleep(1000);
                 }
              }
           }

        }
     }
  }
//+------------------------------------------------------------------+
void close_type(int yourmagic,int side,string sym)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()==yourmagic)
           {
            if(OrderType()==side && OrderSymbol()==sym)
              {
               close_order_immediate(OrderTicket());
               while(IsTradeContextBusy())
                 {
                  Sleep(1000);
                 }
              }
           }

        }
     }
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
int PlaceBuy2(int yourmagic,string comment,double lotsize,int sl=0,int tp=0)
  {
   double stop=0,take=0;
   if(sl>0)
     {
      stop=Ask-sl*Point;
     }
   if(tp>0)
     {
      take=Ask+tp*Point;
     }

   int t=OrderSend(NULL,OP_BUY,lotsize,Ask,2,stop,take,comment,yourmagic);
   while(IsTradeContextBusy())
     {
      Sleep(50);
     }
   int e=GetLastError();
   if(e>0) return(e);
   else return(t);
  }
//+------------------------------------------------------------------+
int PlaceSell2(int yourmagic,string comment,double lotsize,int sl=0,int tp=0)
  {
   double stop=0,take=0;
   if(sl>0)
     {
      stop=Bid+sl*Point;
     }
   if(tp>0)
     {
      take=Bid-tp*Point;
     }

   int t=OrderSend(NULL,OP_SELL,lotsize,Bid,2,stop,take,comment,yourmagic);
   while(IsTradeContextBusy())
     {
      Sleep(50);
     }
   int e=GetLastError();
   if(e>0) return(e);
   else return(t);
  }
//+------------------------------------------------------------------+
void order_delete_AllPending(int magicnumber)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==magicnumber && OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUYSTOP
               ||OrderType()==OP_SELLSTOP
               ||OrderType()==OP_BUYLIMIT
               ||OrderType()==OP_SELLLIMIT
               )
              {
               bool delok=OrderDelete(OrderTicket(),clrPink);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void order_close_custom(int magicnumber,string symb,int type,string statetag="null")
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==magicnumber && OrderSymbol()==symb && OrderType()==type)
           {

            bool delok=order_close_smart(OrderTicket());
            if(delok) Print(__FUNCSIG__,statetag,"::",OrderTicket());
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool order_close_smart(int ticket)
  {
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      if(OrderType()==OP_BUY)
        {
         bool delok=OrderClose(OrderTicket(),OrderLots(),Bid,5,clrGray);
         return(delok);
        }
      else if(OrderType()==OP_SELL)
        {
         bool delok2=OrderClose(OrderTicket(),OrderLots(),Ask,5,clrGray);
         return(delok2);
        }
      else return(false);
     }
   else return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double find_break_even(int side)
  {
   double sumxy=0;
   double sumy=0;
   double weightaverage=-1;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderType()==side && OrderSymbol()==Symbol())
           {
            sumxy=sumxy+(OrderOpenPrice()*OrderLots());
            sumy=sumy+OrderLots();
           }
        }
     }

   if(sumy>0)
     {
      weightaverage=sumxy/sumy;
     }
   return(weightaverage);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void order_count_Array(int &types[],int __MN=0)
  {
   ArrayInitialize(types,0);

   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==__MN)
           {
            types[OrderType()]++;
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void lotsize_count_Array(double &types[],int __MN=0)
  {
   ArrayInitialize(types,0);

   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==__MN)
           {
            types[OrderType()]=+OrderLots();
           }
        }
     }
  }
//+------------------------------------------------------------------+
void Text4Comment(int &order_typeArray[],string &texxt)
  {
   for(int i=0;i<6;i++)
     {
      string t="";
      switch(i)
        {
         case 0 : t="BUY";  break;
         case 1 : t="SELL";  break;
         case 2 : t="BUYLIMIT";  break;

         case 3 : t="SELLLIMIT";  break;

         case 4 : t="BUYSTOP";  break;
         case 5 : t="SELLSTOP";  break;

        }
      StringAdd(texxt,"\n"+t+"=[ "+IntegerToString(order_typeArray[i])+" ]");
     }
  }
//+------------------------------------------------------------------+
int naked_buy(int __MN,string commentsx,double lotsize=0.01)
  {
   int tk=OrderSend(NULL,OP_BUY,lotsize,Ask,3,0,0,commentsx,__MN,0,clrBlue);
   return(tk);
  }
//+------------------------------------------------------------------+
int naked_sell(int __MN,string commentsx,double lotsize=0.01)
  {
   int tk=OrderSend(NULL,OP_SELL,lotsize,Bid,3,0,0,commentsx,__MN,0,clrRed);
   return(tk);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int naked_buy2(string symb,int __MN,string commentsx,double lotsize=0.01)
  {
   int tk=OrderSend(symb,OP_BUY,lotsize,SymbolInfoDouble(symb,SYMBOL_ASK),3,0,0,commentsx,__MN,0,clrBlue);
   return(tk);
  }
//+------------------------------------------------------------------+
int naked_sell2(string symb,int __MN,string commentsx,double lotsize=0.01)
  {
   int tk=OrderSend(symb,OP_SELL,lotsize,SymbolInfoDouble(symb,SYMBOL_BID),3,0,0,commentsx,__MN,0,clrRed);
   return(tk);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void MoveStopToSafe(int ticket,int point_move)
  {
   if(OrderSelect(ticket,SELECT_BY_TICKET))
     {
      if(OrderType()==OP_BUY)
        {
         int mod=OrderModify(OrderTicket(),OrderOpenPrice(),
                             OrderOpenPrice()+point_move*Point,OrderTakeProfit(),
                             OrderExpiration(),clrGray);
        }
      if(OrderType()==OP_SELL)
        {
         int mod2=OrderModify(OrderTicket(),OrderOpenPrice(),
                              OrderOpenPrice()-point_move*Point,OrderTakeProfit(),
                              OrderExpiration(),clrGray);
        }
     }
  }
//+------------------------------------------------------------------+
bool IsThisTradeSafe(int ticket)
  {
   bool retval=false;
   bool sel=OrderSelect(ticket,SELECT_BY_TICKET);
   if(!sel)
      return(false);

   if(OrderStopLoss()==0)
      return(false);

   if(OrderType()!=OP_BUY && OrderType()!=OP_SELL)
      return(false);

   if(OrderType()==OP_BUY && OrderStopLoss()>OrderOpenPrice())
     {
      //return(true);
      retval=true;
     }
   if(OrderType()==OP_SELL && OrderStopLoss()<OrderOpenPrice())
     {
      //return(true);
      retval=true;
     }
   return(retval);
  }
//+------------------------------------------------------------------+
bool IsNoLive(int &ledger[])
  {
   if(ledger[OP_BUY]+ledger[OP_SELL]==0)
      return(true);
   else
      return(false);
  }
//+------------------------------------------------------------------+
bool IsMixDirection(int &ledger[])
  {
   if(ledger[OP_BUY]>=1 && ledger[OP_SELL]>=1)
      return(true);
   else
      return(false);
  }
//+------------------------------------------------------------------+
bool WeightOnBuySide(double &lot_ledger[])
  {
   if(lot_ledger[OP_BUY]>lot_ledger[OP_SELL])
      return(true);
   else
      return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool WeightOnSellSide(double &lot_ledger[])
  {
   if(lot_ledger[OP_BUY]<lot_ledger[OP_SELL])
      return(true);
   else
      return(false);
  }
//+------------------------------------------------------------------+
void close_by_specific(int magic,int type,string comment)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==magic
            && OrderType()==type
            && OrderComment()==comment
            && (OrderType()==OP_BUY || OrderType()==OP_SELL))
           {
            double quote=MarketInfo(OrderSymbol(),MODE_BID);
            if(OrderType()==OP_SELL)
              {
               quote=MarketInfo(OrderSymbol(),MODE_ASK);
              }

            int closeok=OrderClose(OrderTicket(),OrderLots(),quote,10,clrDarkGray);
            while(IsTradeContextBusy())
              {
               Sleep(100);
              }
            if(GetLastError()>0)
              {
               Print(__FUNCSIG__,":: closing error, please check");
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
void close_by_specific2(int magic,int type)
  {
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==magic
            && OrderType()==type
            //&&OrderComment==comment
            && (OrderType()==OP_BUY || OrderType()==OP_SELL))
           {
            double quote=MarketInfo(OrderSymbol(),MODE_BID);
            if(OrderType()==OP_SELL)
              {
               quote=MarketInfo(OrderSymbol(),MODE_ASK);
              }

            int closeok=OrderClose(OrderTicket(),OrderLots(),quote,10,clrDarkGray);
            while(IsTradeContextBusy())
              {
               Sleep(100);
              }
            if(GetLastError()>0)
              {
               Print(__FUNCSIG__,":: closing error, please check");
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void FindHighestLowestOpenPrice(double &retvalHighest,double &retvalLowest,int __MN,string sym,int type)
  {
   double highest=0;
   double lowest=0;
   int c=0;
   for(int i=0;i<OrdersTotal();i++)
     {

      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==__MN
            && OrderSymbol()==sym
            && OrderType()==type)
           {

            if(highest==0 || OrderOpenPrice()>highest)
              {
               highest=OrderOpenPrice();
              }

            if(lowest==0 || OrderOpenPrice()<lowest)
              {

               lowest=OrderOpenPrice();
              }

           }
        }
     }
   retvalHighest=highest;
   retvalLowest=lowest;
  }
//+------------------------------------------------------------------+
double sum_all_profit_points(int __MN,int type,string sym)
  {
   double c=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS))
        {
         if(OrderMagicNumber()==__MN
            && OrderSymbol()==sym
            && OrderType()==type)
           {
            c=c+order_points(OrderTicket());
           }
        }
     }
   return(c);
  }
//+------------------------------------------------------------------+
//void stoploss_trailing_loop(int __MN,int type,int mark=35,int move=5)
//  {
//   for(int i=0;i<OrdersTotal();i++)
//     {
//      if(OrderSelect(i,SELECT_BY_POS)==true)
//        {
//         if(OrderMagicNumber()==__MN && OrderType()==type && OrderSymbol()==Symbol())
//           {
//            stoplosswheelbarrel(OrderTicket(),mark*Point,move*Point);
//           }
//        }
//     }
//  }
//+------------------------------------------------------------------+
void get_counter_symbol(string &retCounter,string &retBase,string prefix="")
  {
   string k=Symbol();
   int prefixlength=StringLen(prefix);
   string counter=StringSubstr(k,prefixlength,3);
   string base=StringSubstr(k,prefixlength+3,3);
   retCounter=counter;
   retBase=base;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void get_counter_symbol2(string &retCounter,string &retBase,string &inputsymbol,string prefix="")
  {
   string k=inputsymbol;
   int prefixlength=StringLen(prefix);
   string counter=StringSubstr(k,prefixlength,3);
   string base=StringSubstr(k,prefixlength+3,3);
   retCounter=counter;
   retBase=base;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int ccfpbufferindexvalue(string currency)
  {
   if(currency=="USD")  return(0);
   else if(currency=="EUR")  return(1);
   else if(currency=="GBP")  return(2);
   else if(currency=="CHF")  return(3);
   else if(currency=="JPY")  return(4);
   else if(currency=="AUD")  return(5);
   else if(currency=="CAD")  return(6);
   else if(currency=="NZD")  return(7);
   else return(-1);
  }
//+------------------------------------------------------------------+
string ccfpbufferindexstring(int index)
  {
   if(index==0)  return("USD");
   else if(index==1)  return("EUR");
   else if(index==2)  return("GBP");
   else if(index==3)  return("CHF");
   else if(index==4)  return("JPY");
   else if(index==5)  return("AUD");
   else if(index==6)  return("CAD");
   else if(index==7)  return("NZD");
   else return("");
  }
//+------------------------------------------------------------------+
