//+------------------------------------------------------------------+
//| EA_1Click_12Pairs_OnChart_V04.mq4
//+------------------------------------------------------------------+
#property strict

#define INTERVAL   10        //--- OnTick loop interval in seconds
#define MAXSIZE    12        //--- Max number of Symbols
#define MAXTRY     10        //--- Max number of Order Functions retries

extern int    ECN_BROKER  = 0;
extern int    MAGIC       = 20161001;
extern string SYMBOL_00   = "EURUSD";
extern string SYMBOL_01   = "AUDUSD";
extern string SYMBOL_02   = "USDCAD";
extern string SYMBOL_03   = "USDCHF";
extern string SYMBOL_04   = "USDJPY";
extern string SYMBOL_05   = "EURCHF";
extern string SYMBOL_06   = "EURJPY";
extern string SYMBOL_07   = "EURAUD";
extern string SYMBOL_08   = "EURCAD";
extern string SYMBOL_09   = "EURGBP";
extern string SYMBOL_10   = "GBPUSD";
extern string SYMBOL_11   = "GBPJPY";

extern double SLIP        = 2.5;                 // slippage in pips
extern double TP          = 25.0;                // target profit in pips
extern double SL          = 50.0;                // stoploss in pips
extern double GAP         = 15.0;                // gap for pending orders in pips 
extern double TRAIL       = 20.0;                // trailing stop in pips (to be implemented)
extern double LOT         = 0.02;                // trading min lot size
extern int    TIMEFRAME   = PERIOD_M15;          // Signal Timeframe

string A_Symbols[MAXSIZE];
int    A_SignalBars[MAXSIZE];
int    A_Signals[MAXSIZE][2];

int    aidx,i_Digits,i_Slippage,i_Ticket=0;
double d_Pip2Double,d_Bid,d_Ask;
string s_BuyB,s_SellB,s_BuyStopB,s_SellStopB,s_CloseB,s_AbortB;
string s_Symbol,s_SymbolLabel,s_SignalLabel;
int    i_BarCounter=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Show Basic Data on Chart
   if(ECN_BROKER==0) DisplayLabel("fixed_label_ecn",250,10,9,"Fixedsys",clrAqua,"ECN Broker      = No");
   else if(ECN_BROKER==1) DisplayLabel("fixed_label_ecn",250,10,9,"Fixedsys",clrAqua,"ECN Broker      = Yes");
   DisplayLabel("fixed_label_lot",20,10,9,"Fixedsys",clrAqua,"Lot Size  = "+DoubleToString(LOT,2));
   DisplayLabel("fixed_label_slip",20,30,9,"Fixedsys",clrAqua,"Slippage  = "+DoubleToString(SLIP,1)+" pips");
   DisplayLabel("fixed_label_tp",20,50,9,"Fixedsys",clrAqua,"T/P       = "+DoubleToString(TP,1)+" pips");
   DisplayLabel("fixed_label_sl",20,70,9,"Fixedsys",clrAqua,"S/L       = "+DoubleToString(SL,1)+" pips");
   DisplayLabel("fixed_label_gap",20,90,9,"Fixedsys",clrAqua,"Limit Gap = "+DoubleToString(GAP,1)+" pips");
   DisplayLabel("fixed_label_trail",20,110,9,"Fixedsys",clrAqua,"Trailing  = "+DoubleToString(TRAIL,1)+" pips");

//--- Init Symbol Array
   A_Symbols[0]  = SYMBOL_00;
   A_Symbols[1]  = SYMBOL_01;
   A_Symbols[2]  = SYMBOL_02;
   A_Symbols[3]  = SYMBOL_03;
   A_Symbols[4]  = SYMBOL_04;
   A_Symbols[5]  = SYMBOL_05;
   A_Symbols[6]  = SYMBOL_06;
   A_Symbols[7]  = SYMBOL_07;
   A_Symbols[8]  = SYMBOL_08;
   A_Symbols[9]  = SYMBOL_09;
   A_Symbols[10] = SYMBOL_10;
   A_Symbols[11] = SYMBOL_11;

   A_SignalBars[0]  = 0;
   A_SignalBars[1]  = 0;
   A_SignalBars[2]  = 0;
   A_SignalBars[3]  = 0;
   A_SignalBars[4]  = 0;
   A_SignalBars[5]  = 0;
   A_SignalBars[6]  = 0;
   A_SignalBars[7]  = 0;
   A_SignalBars[8]  = 0;
   A_SignalBars[9]  = 0;
   A_SignalBars[10] = 0;
   A_SignalBars[11] = 0;

//--- Abort Button
   s_AbortB="AbortButton";
   DisplayButton(s_AbortB,200,30,150,30,clrYellow,clrMagenta,10,CORNER_RIGHT_UPPER,"ALL IS LOST !!!");

   for(aidx=0; aidx<MAXSIZE; aidx++)
     {
      s_Symbol=A_Symbols[aidx];

      //--- Display Symbols
      s_SymbolLabel=StringConcatenate("dyn_label_symbol_",IntegerToString(aidx,2,'0'));
      string _display_symbol="";

      if(s_Symbol=="GOLD") _display_symbol="Gold";
      else if(s_Symbol=="XAUUSD") _display_symbol="XAU";
      else if(StringLen(s_Symbol)==5) _display_symbol=s_Symbol;
      else if(StringLen(s_Symbol)==6) _display_symbol=StringSubstr(s_Symbol,0,3)+"/"+StringSubstr(s_Symbol,3,3);

      DisplayLabel(s_SymbolLabel,250,161+aidx*35,14,"Impact",clrAqua,_display_symbol);

      //--- CLOSE Buttons
      s_CloseB=StringConcatenate("CloseButton",IntegerToString(aidx,2,'0'));
      DisplayButton(s_CloseB,350,160+aidx*35,110,25,clrBlack,clrOrange,10,CORNER_LEFT_UPPER,"Close At Market");
      //--- OP_BUY Buttons
      s_BuyB=StringConcatenate("BuyButton",IntegerToString(aidx,2,'0'));
      DisplayButton(s_BuyB,500,160+aidx*35,90,25,clrBlack,clrLime,10,CORNER_LEFT_UPPER,"BUY Market");
      //--- OP_SELL Buttons
      s_SellB=StringConcatenate("SellButton",IntegerToString(aidx,2,'0'));
      DisplayButton(s_SellB,600,160+aidx*35,90,25,clrWhite,clrRed,10,CORNER_LEFT_UPPER,"SELL Market");
      //---OP_BUYSTOP Buttons
      s_BuyStopB=StringConcatenate("BuyStopButton",IntegerToString(aidx,2,'0'));
      DisplayButton(s_BuyStopB,730,160+aidx*35,80,25,clrBlack,clrMediumSeaGreen,10,CORNER_LEFT_UPPER,"Buy STOP");
      //---OP_SELLSTOP Buttons
      s_SellStopB=StringConcatenate("SellStopButton",IntegerToString(aidx,2,'0'));
      DisplayButton(s_SellStopB,820,160+aidx*35,80,25,clrWhite,clrOrangeRed,10,CORNER_LEFT_UPPER,"Sell STOP");
     }

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Delete static labels
   ObjectDelete(0,"fixed_label_ecn");
   ObjectDelete(0,"fixed_label_lot");
   ObjectDelete(0,"fixed_label_slip");
   ObjectDelete(0,"fixed_label_tp");
   ObjectDelete(0,"fixed_label_sl");
   ObjectDelete(0,"fixed_label_gap");
   ObjectDelete(0,"fixed_label_trail");
   ObjectDelete(0,"dyn_label_bal");
   ObjectDelete(0,"dyn_label_eq");
   ObjectDelete(0,"dyn_label_day");
   ObjectDelete(0,"dyn_label_pp");

   ObjectDelete(0,s_AbortB);

//--- Delete dynamic labels and buttons
   for(aidx=0; aidx<MAXSIZE; aidx++)
     {
      string _label1=StringConcatenate("label1_",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,_label1);
      s_SymbolLabel=StringConcatenate("dyn_label_symbol_",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_SymbolLabel);
      s_SignalLabel=StringConcatenate("dyn_label_signal_",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_SignalLabel);
      s_BuyB=StringConcatenate("BuyButton",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_BuyB);
      s_SellB=StringConcatenate("SellButton",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_SellB);
      s_CloseB=StringConcatenate("CloseButton",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_CloseB);
      s_BuyStopB=StringConcatenate("BuyStopButton",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_BuyStopB);
      s_SellStopB=StringConcatenate("SellStopButton",IntegerToString(aidx,2,'0'));
      ObjectDelete(0,s_SellStopB);
     }
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   static datetime CURRENT_TIME;
   if(TimeCurrent()<CURRENT_TIME) return;
   CURRENT_TIME=TimeCurrent()+INTERVAL;

   double _total_pips=0,_total_profits=0,_day_pips=0,_day_profits=0;
   color _clr_up_down=clrNONE;

//--- Scan Symbol Array and do calculations/display for each symbol pair 
   for(aidx=0; aidx<MAXSIZE; aidx++)
     {
      int _order_count=0;
      double _pip_sum=0,_prof_sum=0,_pip_sumd=0,_prof_sumd=0;

      s_Symbol=A_Symbols[aidx];
      CountOpenPipsProfits(MAGIC,s_Symbol,_pip_sum,_prof_sum,_order_count);

      string _label1=StringConcatenate("label1_",IntegerToString(aidx,2,'0'));
      string _label1_text=StringConcatenate("Pips [Profit] = ",DoubleToString(_pip_sum,1)," [",DoubleToString(_prof_sum,2),"]");

      if(_order_count>0)
        {
         _total_pips=_total_pips+_pip_sum;
         _total_profits=_total_profits+_prof_sum;

         if(_pip_sum>=0) DisplayLabel(_label1,920,165+aidx*35,9,"Fixedsys",clrLime,_label1_text);
         else DisplayLabel(_label1,920,165+aidx*35,9,"Fixedsys",clrRed,_label1_text);
        }
      else ObjectDelete(_label1);

      CountDailyPipsProfits(MAGIC,s_Symbol,_pip_sumd,_prof_sumd);
      _day_pips=_day_pips+_pip_sumd;
      _day_profits=_day_profits+_prof_sumd;
     }

//--- Trend Signal checks
   if(newBar(TimeCurrent(),TIMEFRAME,false,0,false)==true)
     {
      i_BarCounter++;

      for(aidx=0; aidx<MAXSIZE; aidx++)
        {
         s_Symbol=A_Symbols[aidx];

         if(i_BarCounter==1)
           {
            A_Signals[aidx][1]=0;                                     // prev signal
            A_Signals[aidx][0]=TrendSignalCheck(s_Symbol,TIMEFRAME);  // curr signal
           }
         else
           {
            A_Signals[aidx][1]=A_Signals[aidx][0];                    // prev signal
            A_Signals[aidx][0]=TrendSignalCheck(s_Symbol,TIMEFRAME);  // curr signal
           }

         if(A_Signals[aidx][0]!=A_Signals[aidx][1]) A_SignalBars[aidx]=0;
         else A_SignalBars[aidx]=A_SignalBars[aidx]+1;

         s_SignalLabel=StringConcatenate("dyn_label_signal_",IntegerToString(aidx,2,'0'));

         if(A_Signals[aidx][0]==1) DisplayLabel(s_SignalLabel,100,161+aidx*35,14,"Impact",clrMediumSeaGreen,"WEAK   ["+IntegerToString(A_SignalBars[aidx],2)+" bars]");
         else if(A_Signals[aidx][0]==2) DisplayLabel(s_SignalLabel,100,161+aidx*35,14,"Impact",clrLime,"STRONG  ["+IntegerToString(A_SignalBars[aidx],2)+" bars]");
         else if(A_Signals[aidx][0]==-1) DisplayLabel(s_SignalLabel,100,161+aidx*35,14,"Impact",clrOrangeRed,"WEAK   ["+IntegerToString(A_SignalBars[aidx],2)+" bars]");
         else if(A_Signals[aidx][0]==-2) DisplayLabel(s_SignalLabel,100,161+aidx*35,14,"Impact",clrRed,"STRONG  ["+IntegerToString(A_SignalBars[aidx],2)+" bars]");
         else ObjectDelete(s_SignalLabel);
        }
     }

//--- Show Account Eq/Balance and Total P/L
   DisplayLabel("dyn_label_bal",250,30,9,"Fixedsys",clrAqua,"Account Balance = "+DoubleToString(AccountBalance(),2));
   DisplayLabel("dyn_label_eq",250,50,9,"Fixedsys",clrAqua,"Account Equity  = "+DoubleToString(AccountEquity(),2));

   if(_day_pips>=0) _clr_up_down=clrLime; else _clr_up_down=clrOrangeRed;
   DisplayLabel("dyn_label_day",700,5,14,"Impact",_clr_up_down,"Daily Pips/Profit = "+DoubleToString(_day_pips,1)+" / "+DoubleToString(_day_profits,2));
   if(_total_pips>=0) _clr_up_down=clrLime; else _clr_up_down=clrOrangeRed;
   DisplayLabel("dyn_label_pp",700,25,14,"Impact",_clr_up_down,"Open Pips/Profit = "+DoubleToString(_total_pips,1)+" / "+DoubleToString(_total_profits,2));
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
  {
   double d_SL=0,d_TP=0,d_BuyStop=0,d_SellStop=0;

   RefreshRates();

//--- Check if Abort Close (ALL IS LOST)
   if(sparam==s_AbortB)
     {
      for(aidx=0; aidx<MAXSIZE; aidx++)
        {
         //--- Close ALL open/pending orders for ALL 12 pairs
         s_Symbol=A_Symbols[aidx];
         GetSymbolMarketData(s_Symbol,SLIP,i_Digits,d_Pip2Double,i_Slippage,d_Bid,d_Ask);
         CloseAllPositions(MAGIC,s_Symbol,i_Slippage);
        }
      ObjectSetInteger(0,s_AbortB,OBJPROP_STATE,false);
     }
   else
     {
      for(aidx=0; aidx<MAXSIZE; aidx++)
        {
         //--- Get MarketInfo data for each Symbol
         s_Symbol=A_Symbols[aidx];
         GetSymbolMarketData(s_Symbol,SLIP,i_Digits,d_Pip2Double,i_Slippage,d_Bid,d_Ask);

         //--- Loop through button names
         s_CloseB=StringConcatenate("CloseButton",IntegerToString(aidx,2,'0'));
         s_BuyB=StringConcatenate("BuyButton",IntegerToString(aidx,2,'0'));
         s_SellB=StringConcatenate("SellButton",IntegerToString(aidx,2,'0'));
         s_BuyStopB=StringConcatenate("BuyStopButton",IntegerToString(aidx,2,'0'));
         s_SellStopB=StringConcatenate("SellStopButton",IntegerToString(aidx,2,'0'));

         if(sparam==s_CloseB) //--- Check if Close Button Pressed
           {
            CloseAllPositions(MAGIC,s_Symbol,i_Slippage);
            ObjectSetInteger(0,s_CloseB,OBJPROP_STATE,false);
           }
         else if(sparam==s_BuyB) //--- Check if Buy Button Pressed
           {
            d_SL=NormalizeDouble(d_Bid-SL*d_Pip2Double,i_Digits);
            d_TP=NormalizeDouble(d_Ask+TP*d_Pip2Double,i_Digits);

            i_Ticket=OrderSend(s_Symbol,OP_BUY,LOT,d_Ask,i_Slippage,d_SL,d_TP,"One-Click OP_BUY",MAGIC,0,clrNONE);

            ObjectSetInteger(0,s_BuyB,OBJPROP_STATE,false);
           }
         else if(sparam==s_SellB) //--- Check if Sell Button Pressed
           {
            d_SL=NormalizeDouble(d_Ask+SL*d_Pip2Double,i_Digits);
            d_TP=NormalizeDouble(d_Bid-TP*d_Pip2Double,i_Digits);

            i_Ticket=OrderSend(s_Symbol,OP_SELL,LOT,d_Bid,i_Slippage,d_SL,d_TP,"One-Click OP_SELL",MAGIC,0,clrNONE);

            ObjectSetInteger(0,s_SellB,OBJPROP_STATE,false);
           }
         else if(sparam==s_BuyStopB)
           {
            d_BuyStop=NormalizeDouble(d_Ask+GAP*d_Pip2Double,i_Digits);
            d_SL=NormalizeDouble(d_Ask+GAP*d_Pip2Double-SL*d_Pip2Double,i_Digits);
            d_TP=NormalizeDouble(d_Ask+GAP*d_Pip2Double+TP*d_Pip2Double,i_Digits);

            i_Ticket=OrderSend(Symbol(),OP_BUYSTOP,LOT,d_BuyStop,i_Slippage,d_SL,d_TP,"One-Click OP_BUYSTOP",MAGIC,0,clrNONE);

            ObjectSetInteger(0,s_BuyStopB,OBJPROP_STATE,false);
           }
         else if(sparam==s_SellStopB)
           {
            d_SellStop=NormalizeDouble(d_Bid-GAP*d_Pip2Double,i_Digits);
            d_SL=NormalizeDouble(d_Bid-GAP*d_Pip2Double+SL*d_Pip2Double,i_Digits);
            d_TP=NormalizeDouble(d_Bid-GAP*d_Pip2Double-TP*d_Pip2Double,i_Digits);

            i_Ticket=OrderSend(Symbol(),OP_SELLSTOP,LOT,d_SellStop,i_Slippage,d_SL,d_TP,"One-Click OP_SELLSTOP",MAGIC,0,clrNONE);

            ObjectSetInteger(0,s_SellStopB,OBJPROP_STATE,false);
           }
        }
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void GetSymbolMarketData(string _symbol,double _pip_slippage,int &_digits,double &_p2p,int &_slippage,double &_bid,double &_ask)
  {
   double _point=MarketInfo(_symbol,MODE_POINT);

   _bid=MarketInfo(_symbol,MODE_BID);
   _ask=MarketInfo(_symbol,MODE_ASK);

   _digits=(int)MarketInfo(_symbol,MODE_DIGITS);
   _p2p=_point*MathPow(10,_digits%2);

   if(_point==0.00001 || _point==0.001) _slippage=(int)_pip_slippage*10;
   else _slippage=(int)_pip_slippage;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int TrendSignalCheck(string _symbol,int _timeframe)
  {
   int _up_count=0,_dn_count=0,_trend=0;

   double d_EMA50=iMA(_symbol,_timeframe,50,0,MODE_EMA,PRICE_CLOSE,1);
   double d_EMA200=iMA(_symbol,_timeframe,200,0,MODE_EMA,PRICE_CLOSE,1);

   if(d_EMA50>d_EMA200) _trend=1;
   else if(d_EMA50<d_EMA200) _trend=-1;
   else return(0);

   if(_trend!=0)
     {
      double d_EMA=iMA(_symbol,_timeframe,10,0,MODE_EMA,PRICE_CLOSE,1);
      double d_MACD=iMACD(_symbol,_timeframe,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
      double d_CCI=iCCI(_symbol,_timeframe,50,PRICE_CLOSE,1);
      double d_RSI=iRSI(_symbol,_timeframe,14,PRICE_CLOSE,1);
      double d_STO=iStochastic(_symbol,_timeframe,30,5,5,MODE_SMA,0,MODE_MAIN,1);

      if(d_EMA>d_EMA50) _up_count++;
      else if(d_EMA<d_EMA50) _dn_count++;
      if(d_MACD>0) _up_count++;
      else if(d_MACD<0) _dn_count++;
      if(d_CCI>0) _up_count++;
      else if(d_CCI<0) _dn_count++;
      if(d_RSI>50) _up_count++;
      else if(d_RSI<50) _dn_count++;
      if(d_STO>50) _up_count++;
      else if(d_STO<50) _dn_count++;

      //--- Result: +1 - weak signal up, +2 - strong signal up, -1 - weak signal down, -2 - strong signal down
      if(_trend>0 && _up_count==4) return(1);
      else if(_trend>0 && _up_count==5) return(2);
      else if(_trend<0 && _dn_count==4) return(-1);
      else if(_trend<0 && _dn_count==5) return(-2);
     }

   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseAllPositions(int _magic,string _symbol,int _slippage)
  {
   for(int apos=OrdersTotal()-1; apos>=0; apos--)
     {
      if(OrderSelect(apos,SELECT_BY_POS,MODE_TRADES)==true)
        {
         if(OrderSymbol()==_symbol && OrderMagicNumber()==_magic)
           {
            if(OrderType()<=OP_SELL) //--- Close Open Orders here
              {
               int _ticket=OrderTicket();

               for(int _try=1; _try<=MAXTRY; _try++)
                 {
                  RefreshRates();

                  if(OrderClose(_ticket,OrderLots(),OrderClosePrice(),_slippage,clrYellow)==true)
                    {
                     Print("CloseAllPositions SUCCESS: Magic # ",_magic," Ticket # ",_ticket);
                     break;
                    }
                  else
                    {
                     if(_try==MAXTRY) Print("CloseAllPositions ERROR: Magic # ",_magic," maximum attempts reached # ",MAXTRY);
                     else Print("CloseAllPositions ERROR: Magic # ",_magic," Ticket # ",_ticket," Error # ",GetLastError());
                     Sleep(3000); //--- Wait 3 seconds before retrying to close the open order
                    }
                 }
              }
            else if(OrderType()>OP_SELL) //--- Delete Limit/Pending Orders here
              {
               int _ticket=OrderTicket();

               if(OrderDelete(OrderTicket())==true) Print("CloseAllPositions SUCCESS: Magic # ",_magic," Ticket # ",_ticket);
               else Print("CloseAllPositions Pending ERROR: Magic # ",_magic," Ticket # ",_ticket," Error # ",GetLastError());
              }
           }
        }
     }
  }
//+------------------------------------------------------------------------------------------------+
//| Calculate realized and unrealized pips & profit totals, resulting from all open and closed trades
//| for specific Symbol/MagicNo and including all tickets since specific timestamp. 
//| Includes total number of orders (both BUY/SELL)
//+------------------------------------------------------------------------------------------------+
void CountOpenPipsProfits(int _magic,string _symbol,double &_total_pips,double &_total_profit,int &_orders_total)
  {
   _total_pips=0.0;
   _total_profit=0.0;
   _orders_total=0;

   int DIGITS=(int)MarketInfo(_symbol,MODE_DIGITS);
   double PIP2DBL=MarketInfo(_symbol,MODE_POINT)*MathPow(10,DIGITS%2);

   for(int apos=0; apos<OrdersTotal(); apos++)
     {
      if(OrderSelect(apos,SELECT_BY_POS,MODE_TRADES)==true)
        {
         if(OrderSymbol()==_symbol && OrderMagicNumber()==_magic && OrderType()<=OP_SELL)
           {
            _orders_total++;
            _total_profit=_total_profit+OrderProfit()+OrderSwap()+OrderCommission();

            if(OrderType()==OP_BUY) _total_pips=_total_pips+((OrderClosePrice()-OrderOpenPrice())/PIP2DBL);
            else if(OrderType()==OP_SELL) _total_pips=_total_pips+((OrderOpenPrice()-OrderClosePrice())/PIP2DBL);
           }
        }
     }

   _total_pips=NormalizeDouble(_total_pips,1);
   _total_profit=NormalizeDouble(_total_profit,2);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CountDailyPipsProfits(int _magic,string _symbol,double &_total_pips,double &_total_profit)
  {
   datetime _day_start=iTime(_symbol,PERIOD_D1,0);
   _total_pips=0.0;
   _total_profit=0.0;

   int DIGITS=(int)MarketInfo(_symbol,MODE_DIGITS);
   double PIP2DBL=MarketInfo(_symbol,MODE_POINT)*MathPow(10,DIGITS%2);

//--- Closed Orders
   for(int hpos=0; hpos<OrdersHistoryTotal(); hpos++)
     {
      if(OrderSelect(hpos,SELECT_BY_POS,MODE_HISTORY)==true)
        {
         if(OrderSymbol()==_symbol && OrderMagicNumber()==_magic && OrderType()<=OP_SELL && OrderOpenTime()>_day_start)
           {
            _total_profit=_total_profit+OrderProfit()+OrderSwap()+OrderCommission();

            if(OrderType()==OP_BUY) _total_pips=_total_pips+((OrderClosePrice()-OrderOpenPrice())/PIP2DBL);
            else if(OrderType()==OP_SELL) _total_pips=_total_pips+((OrderOpenPrice()-OrderClosePrice())/PIP2DBL);
           }
        }
     }

//--- Open Orders
   for(int apos=0; apos<OrdersTotal(); apos++)
     {
      if(OrderSelect(apos,SELECT_BY_POS,MODE_TRADES)==true)
        {
         if(OrderSymbol()==_symbol && OrderMagicNumber()==_magic && OrderType()<=OP_SELL && OrderOpenTime()>_day_start)
           {
            _total_profit=_total_profit+OrderProfit()+OrderSwap()+OrderCommission();

            if(OrderType()==OP_BUY) _total_pips=_total_pips+((OrderClosePrice()-OrderOpenPrice())/PIP2DBL);
            else if(OrderType()==OP_SELL) _total_pips=_total_pips+((OrderOpenPrice()-OrderClosePrice())/PIP2DBL);
           }
        }
     }

   _total_pips=NormalizeDouble(_total_pips,1);
   _total_profit=NormalizeDouble(_total_profit,2);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DisplayLabel(string _name,int _XD,int _YD,int _fsize,string _font,color _color,string _text)
  {
   if(ObjectFind(_name)>=0) ObjectDelete(_name);

   ObjectCreate(_name,OBJ_LABEL,0,0,0);
   ObjectSet(_name,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSet(_name,OBJPROP_XDISTANCE,_XD);
   ObjectSet(_name,OBJPROP_YDISTANCE,_YD);
   ObjectSetText(_name,_text,_fsize,_font,_color);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DisplayButton(string _name,int _XD,int _YD,int _XSize,int _YSize,color _front,color _back,int _fontsize,ENUM_BASE_CORNER _corner,string _text)
  {
   if(ObjectFind(0,_name)>=0) ObjectDelete(_name);

   ObjectCreate(0,_name,OBJ_BUTTON,0,0,0);
   ObjectSetInteger(0,_name,OBJPROP_XDISTANCE,_XD);
   ObjectSetInteger(0,_name,OBJPROP_YDISTANCE,_YD);
   ObjectSetInteger(0,_name,OBJPROP_XSIZE,_XSize);
   ObjectSetInteger(0,_name,OBJPROP_YSIZE,_YSize);
   ObjectSetInteger(0,_name,OBJPROP_COLOR,_front);
   ObjectSetInteger(0,_name,OBJPROP_BGCOLOR,_back);
   ObjectSetInteger(0,_name,OBJPROP_BORDER_COLOR,_back);
   ObjectSetInteger(0,_name,OBJPROP_BORDER_TYPE,BORDER_FLAT);
   ObjectSetInteger(0,_name,OBJPROP_BACK,false);
   ObjectSetInteger(0,_name,OBJPROP_HIDDEN,true);
   ObjectSetInteger(0,_name,OBJPROP_STATE,false);
   ObjectSetInteger(0,_name,OBJPROP_FONTSIZE,_fontsize);
   ObjectSetInteger(0,_name,OBJPROP_CORNER,_corner);
   ObjectSetString(0,_name,OBJPROP_TEXT,_text);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
datetime lastBarTime(datetime _currentTime,int _period,bool _period_in_second=false,int _advance=0,bool _advanced_in_second=false)
  {
   int iAdvance=(_advance*60);
   if(_advanced_in_second) iAdvance=_advance;

   datetime iCurrentTime=_currentTime+=iAdvance;

   int iPeriod=(_period*60);
   if(_period_in_second) iPeriod=_period;

   if(_period==PERIOD_W1) return((iCurrentTime-(datetime)MathMod(iCurrentTime,(PERIOD_D1*60)))-(((TimeDayOfWeek(iCurrentTime)-1)*PERIOD_D1)*60));
   else if(_period==PERIOD_MN1) return((iCurrentTime-(datetime)MathMod(iCurrentTime,(PERIOD_D1*60)))-(((TimeDay(iCurrentTime)-1)*PERIOD_D1)*60));
   else
     {
      if(_period>0) return(iCurrentTime-(datetime)MathMod(iCurrentTime,iPeriod));
      else return(iCurrentTime);
     }

   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool newBar(datetime _currentTime,int _period,bool _period_in_second=false,int _advance=0,bool _advanced_in_second=false)
  {
   static datetime gsLastBarTime;

   int iAdvance=(_advance*60);
   if(_advanced_in_second) iAdvance=_advance;

   datetime iCurrentTime=_currentTime+=iAdvance;

   int iPeriod=(_period*60);
   if(_period_in_second) iPeriod=_period;

   if((iCurrentTime-gsLastBarTime)>=iPeriod)
     {
      gsLastBarTime=lastBarTime(_currentTime,_period,_period_in_second,_advance,_advanced_in_second);
      return(true);
     }

   return(false);
  }
//+------------------------------------------------------------------+
