//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2012, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
enum po_multips
  {
   _1=1,_10=10,_100=100,_1000=1000
  };

extern string emp0="Lots and Stops settings/";
extern double Lot=0.01;
extern bool use_percent_of_deposit=false;
extern double percent_of_deposit=1;
extern bool use_martini_on_opened_order=true;
extern double Lot_add_opened=0.01;
extern int StopLoss=0;
extern int TakeProfit=0;
extern bool use_auto_tp=true;

extern string emp1="Profitmultipsettings/";
extern bool use_profitAll_multip=false;
extern double profitAll_multip=15;

extern string emp11="Virtual_SL_TP/";
extern bool use_Virtual_Stops=false;
extern int v_StopLoss=42;
extern int v_TakeProfit=28;

extern string emp2="Additionalsettings/";
extern int Max_orders=1000;
extern po_multips point_multip=_10;
extern bool use_reverse_enter_way=false;
extern bool use_opposite_signal_to_exit=true;
extern int Slippage=2;
extern int Magic=74335;
extern string comment="Shabl";
int MaxAttempts=64;
double pause_if_busy=0.2;

extern string emp3="//Work time settings/";
extern bool Use_work_time=false;
extern string start_time_1= "08:00";
extern string stop_time_1 = "16:00";
extern string start_time_2= "";
extern string stop_time_2 = "";
extern string start_time_3= "";
extern string stop_time_3 = "";

extern string emp4="//Martini";
extern bool use_martini=false;
extern double CloseProfit=22;
extern double CloseLose=47;
extern double Lot_multip=1.6;
extern uint step=40;

extern string emp5="//Martini on closed order//";
extern bool use_martini_on_lose_order=false;
extern double Lose_to_on_martini=0;
extern bool use_martini_on_SL=false;
extern double Lot_multip_closed=2.2;

extern string emp6="//BreakEven";
extern bool   use_breakEven=false;
extern int    breakEven_level= 8;
extern int    breakEven_Size = 1;

extern string emp7="//Trailing stop/";
extern bool use_traling_stop=false;
extern int TrailingStart=0;
extern int TrailingStop = 20;
extern int TrailingStep =10;

extern string emp8="";
extern string ind1_name="x_3_semafor";
extern int period1 = 5;
extern int period2 = 12;
extern int period3 = 23;
extern double devi1 = 1.3;
extern double devi2 = 1.3;
extern double devi3 = 1.3;


extern string emp9="/NEWS settings//";
extern bool use_news=false;
extern int no_trade_before_news_minutes= 30;
extern int no_trade_after_news_minutes = 30;
extern int      ShowEventsNum=6;
extern bool ReportAllPairs= true;
extern bool    IncludeHigh= true;
extern bool    IncludeMedium       = true;
extern bool    IncludeLow          = false;
extern bool    IncludeSpeaks       = true;
extern bool     SkipSameNews_Pair_Time_Impact=false;
extern int old_news_time_minute_stay=5;
extern int refresh_minutes=4;

extern bool draw_news=true;
extern int       TxtSize=7;
extern color    TxtColorOldNews     = clrGray;
extern color    TxtColorImpactHigh  = clrRed;
extern color    TxtColorImpactMed   = clrOrange;
extern color    TxtColorImpactLow   = clrKhaki;
extern ENUM_BASE_CORNER      TxtCorner=CORNER_LEFT_LOWER;
extern string TxtFont="Arial Bold";
extern int X=10;
extern int Y_start= 10;
extern int Y_step = 13;
extern string site= "http://www.forexfactory.com/ffcal_week_this.xml";

#define TITLE     0
#define COUNTRY   1
#define DATE      2
#define TIME      3
#define IMPACT    4
#define FORECAST  5
#define PREVIOUS  6
#define EVENTMAX 256

datetime mainDataGMT[EVENTMAX];
string    mainData[EVENTMAX][7];
//string    sTags[7] = { "<title>", "<country>", "<date><![CDATA[", "<time><![CDATA[", "<impact><![CDATA[", "<forecast><![CDATA[", "<previous><![CDATA[" };
//string    eTags[7] = { "</title>", "</country>", "]]></date>", "]]></time>", "]]></impact>", "]]></forecast>", "]]></previous>" };

string    sTags[7] = { "<title>", "<country>", "<date>", "<time>", "<impact>", "<forecast>", "<previous>" };
string    eTags[7] = { "</title>", "</country>", "</date>", "</time>", "</impact>", "</forecast>", "</previous>" };

string  identif="mFFCal_evi";
int cou=0;
datetime time_PC;
bool News_ok=true;
datetime last_update_time;
datetime news_times_id[];

//demo
bool use_demo=false;

int buys_,sells_,buys_S,sells_S,buys_L,sells_L,Orders_Total;
int Sig_en;
double  point=Point*point_multip;
int nor_lot=2;
int CC;
int prevbars;
double prev_bid;
datetime last_buy_time;
datetime last_sell_time;
//
int OnInit()
  {
   prevbars=Bars;

   if(MarketInfo(Symbol(),MODE_LOTSTEP)==0.1) nor_lot=1;

//martini-other off
   if(use_martini) {use_breakEven=false;use_traling_stop=false;use_percent_of_deposit=false;use_opposite_signal_to_exit=false;}

//offline chart
   if(ChartGetInteger(0,CHART_IS_OFFLINE))
     {
      prev_bid=Close[0];

      while(!IsStopped())
        {
         RefreshRates();
         if(prev_bid!=Close[0]) {prev_bid=Close[0];OnTick();}
         Sleep(100);
        }
     }//end offline chart

   if(use_news)
     {
      EventSetTimer(1);
      ArrayResize(news_times_id,ShowEventsNum);
      last_update_time=0;
      delete_prev_objects_f();
     }

   return(INIT_SUCCEEDED);
  }
//
void OnDeinit(const int reason)
  {
   delete_prev_objects_f();

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTimer()
  {
   time_PC=TimeLocal();

//no bars
   if(Bars<20) return;

//trading is not allowed
   if(!IsTradeAllowed() || !IsTradeAllowed(Symbol(),TimeCurrent())) return;

//update news
   news_update_f();

//sig
   News_ok=News_ok_f();

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//no bars
   if(Bars<20) return;

//trading is not allowed
   if(!IsTradeAllowed() || !IsTradeAllowed(Symbol(),TimeCurrent())) return;

//martini
   if(use_martini)
     {
      martini_f();
      double prof=Profit_f();
      if((CloseProfit!=0 && prof>=CloseProfit) || (CloseLose!=0 && prof<=-CloseLose)) Close_all_f();
     }

//trailing
   if(use_traling_stop) Traling_Stop_f();

//breakeven
   if(use_breakEven) BreakEven_f();

//SL && TP 
   if(StopLoss!=0 || TakeProfit!=0) SL_TP_f();

//
   if(use_auto_tp) tp_prev_f();

//virtual stops
   if(use_Virtual_Stops) Virtual_stops_chek_f();

//signal to enter
   Sig_en=Sig_f();

//revers
   if(use_reverse_enter_way)
     {
      if(Sig_en==1) Sig_en=-1;
      else
         if(Sig_en==-1) Sig_en=1;

     }

//exit
   if(use_opposite_signal_to_exit && Sig_en!=0) close_f();

//exit2
   if(use_profitAll_multip)
     {
      if(Profit_f()>=Lots_Total_f()*profitAll_multip) Close_all_f();
     }
//time filter
   if(Use_work_time && !work_time_f()) return;


//enter
   if(Sig_en!=0) open_f();

//new bar
   if(Bars==prevbars) return;
   prevbars=Bars;
//exit3
   if(Profit_f()>0) Close_all_f();

  }
//func

char Sig_f()
  {
//indicators
   double up=iCustom(Symbol(),PERIOD_CURRENT,ind1_name,period1,period2,period3,devi1,devi2,devi3,4,CC);
   double down=iCustom(Symbol(),PERIOD_CURRENT,ind1_name,period1,period2,period3,devi1,devi2,devi3,5,CC);
//signal buy
   if(up!=0 && last_buy_time!=Time[0]) return(1);
   if(down!=0 && last_sell_time!=Time[0]) return(-1);

   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void open_f()
  {
//max orders
   CountOpenedPositions_f();
   if(Orders_Total>=Max_orders) return;

//news
   if(!News_ok) return;

   double Lotss=Lot;
//lot from % of depo
   if(use_percent_of_deposit) Lotss=GetLot_f();
//martini on last order
   if(use_martini_on_lose_order) Lotss=chek_prev_order_f();
//martini on opened order
   if(use_martini_on_opened_order) Lotss=Lot*(Orders_Total+1);
//chek lots correct
   if(Lotss>MarketInfo(Symbol(),MODE_MAXLOT)) Lotss=MarketInfo(Symbol(),MODE_MAXLOT);
   if(Lotss<MarketInfo(Symbol(),MODE_MINLOT)) Lotss=MarketInfo(Symbol(),MODE_MINLOT);
   if(MarketInfo(Symbol(),MODE_MARGINREQUIRED)*Lotss>AccountFreeMargin()) {Alert("Not enouth money to open order "+string(Lotss)+" lots!");return;}
   Lotss=NormalizeDouble(Lotss,nor_lot);

   int ticket_op=-1;
   for(int j_op = 0; j_op < MaxAttempts; j_op++)
     {
      while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
      RefreshRates();

      if(Sig_en>0) ticket_op=OrderSend(Symbol(),OP_BUY,Lotss,Ask,Slippage,0,0,comment,Magic,0,clrNONE);
      else
         if(Sig_en<0) ticket_op=OrderSend(Symbol(),OP_SELL,Lotss,Bid,Slippage,0,0,comment,Magic,0,clrNONE);
      else
         break;

      if(ticket_op>-1)
        {
         if(Sig_en>0) last_buy_time=Time[0];
         if(Sig_en<0) last_sell_time=Time[0];
         break;
        }
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void close_f()
  {
   int type;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      bool ticket_ex=false;
      for(int j_ex=0;j_ex<MaxAttempts; j_ex++)
        {
         while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
         RefreshRates();

         if(type==OP_BUY && use_opposite_signal_to_exit && Sig_en<0) ticket_ex=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,clrNONE);
         else
            if(type==OP_SELL && use_opposite_signal_to_exit && Sig_en>0) ticket_ex=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,clrNONE);
         else
            break;
         if(ticket_ex==true)break;
        }
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double GetLot_f()
  {
   double Free    =AccountFreeMargin();
   double One_Lot =MarketInfo(Symbol(),MODE_MARGINREQUIRED);
   double Step    =MarketInfo(Symbol(),MODE_LOTSTEP);
   double Loto=MathFloor(Free*percent_of_deposit/100/One_Lot/Step)*Step;

   double Min_Lot =MarketInfo(Symbol(),MODE_MINLOT);
   double Max_Lot =MarketInfo(Symbol(),MODE_MAXLOT);
   if(Loto<Min_Lot) Loto=Min_Lot;
   if(Loto>Max_Lot) Loto=Max_Lot;

   return(NormalizeDouble(Loto,nor_lot));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void BreakEven_f()
  {
   int type;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
      RefreshRates();

      if(type==OP_BUY)
        {
         if(Bid>=OrderOpenPrice()+breakEven_level*point && (OrderStopLoss()<OrderOpenPrice() || OrderStopLoss()==0))
           {
            if(OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+NormalizeDouble(breakEven_Size*point,Digits),OrderTakeProfit(),0,clrNONE)) continue;
           }
        }
      else
      if(type==OP_SELL)
        {
         if(Ask<=OrderOpenPrice()-breakEven_level*point && (OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0))
           {
            if(OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-NormalizeDouble(breakEven_Size*point,Digits),OrderTakeProfit(),0,clrNONE)) continue;
           }
        }

     }
  }
//
void tp_prev_f()
  {
   int type;
   double prev_price=-1;
   double prev_tp=-1;
   bool first=false;

   for(int i=0; i<OrdersTotal(); i++)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;
      if(!first)
        {
         first=true;
         prev_price=OrderOpenPrice();
         prev_tp=OrderTakeProfit();
         continue;
        }

      type=OrderType();

      if(type==OP_BUY)
        {
         if(Bid>=prev_price && OrderTakeProfit()<prev_tp)
           {
            if(OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),prev_tp,0,clrNONE)) continue;
           }
        }
      else
      if(type==OP_SELL)
        {
         if(Ask<=prev_price && OrderTakeProfit()>prev_tp)
           {
            if(OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),prev_tp,0,clrNONE)) continue;
           }
        }

     }

   prev_price=OrderOpenPrice();
   prev_tp=OrderTakeProfit();

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Traling_Stop_f()
  {
   int type;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      if(type==OP_BUY)
        {
         if(Bid>=NormalizeDouble(OrderOpenPrice()+TrailingStart*point+TrailingStop*point,Digits))
           {
            if(NormalizeDouble(OrderStopLoss(),Digits)<NormalizeDouble(Bid-(TrailingStop+TrailingStep)*point,Digits))
              {
               if(NormalizeDouble(OrderStopLoss(),Digits)!=NormalizeDouble(Bid-TrailingStop*point,Digits))
                 {
                  while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
                  RefreshRates();
                  if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid-TrailingStop*point,Digits),OrderTakeProfit(),0,clrNONE)) continue;
                 }
              }
           }
        }
      else
      if(type==OP_SELL)
        {
         if(Ask<=NormalizeDouble(OrderOpenPrice()-TrailingStart*point-TrailingStop*point,Digits))
           {
            if((NormalizeDouble(OrderStopLoss(),Digits)>NormalizeDouble(Ask+(TrailingStop+TrailingStep)*point,Digits)) || OrderStopLoss()==0)
              {
               if(NormalizeDouble(OrderStopLoss(),Digits)!=NormalizeDouble(Ask+TrailingStop*point,Digits))
                 {
                  while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
                  RefreshRates();
                  if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Ask+TrailingStop*point,Digits),OrderTakeProfit(),0,clrNONE)) continue;
                 }
              }
           }
        }

     }

  }
// 
void martini_f()
  {
   CountOpenedPositions_f();
   int order_type=-1;
//!83=0; =0 2E>4
   Sig_en=Sig_f();

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      order_type=OrderType();
      break;
     }

   if(order_type==OP_BUY)
     {
      //
      if(Ask<=OrderOpenPrice()-step*point)
        {
         int ticket_op_m=-1;

         for(int j_op_b=0; j_op_b<MaxAttempts; j_op_b++)
           {
            while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
            RefreshRates();

            if(Sig_en>0 && buys_>0) ticket_op_m=OrderSend(Symbol(),OP_BUY,NormalizeDouble(OrderLots()*Lot_multip,nor_lot),Ask,Slippage,0,0,comment,Magic,0,clrNONE);
            else
               break;
            if(ticket_op_m>-1)break;
           }

        }
     }

   if(order_type==OP_SELL)
     {
      if(Bid>=OrderOpenPrice()+step*point)
        {
         ticket_op_m=-1;

         for(int j_op_s=0; j_op_s<MaxAttempts; j_op_s++)
           {
            while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
            RefreshRates();

            if(Sig_en<0 && sells_>0) ticket_op_m=OrderSend(Symbol(),OP_SELL,NormalizeDouble(OrderLots()*Lot_multip,nor_lot),Bid,Slippage,0,0,comment,Magic,0,clrNONE);
            else
               break;
            if(ticket_op_m>-1)break;
           }

        }
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double Profit_f()
  {
   double prof=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      prof+=OrderProfit()+OrderSwap()+OrderCommission();
     }

   return(prof);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double Lots_Total_f()
  {
   double loto=0;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;
      if(OrderType()!=OP_BUY && OrderType()!=OP_SELL) continue;

      loto+=OrderLots();
     }

   return(loto);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CountOpenedPositions_f()
  {
   buys_=0;
   sells_=0;
   buys_S=0;
   sells_S=0;
   buys_L=0;
   sells_L=0;
   Orders_Total=0;
   int type=-1;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      if(type==OP_BUY) buys_++;
      else
         if(type==OP_SELL) sells_++;
      else
         if(type==OP_BUYSTOP) buys_S++;
      else
         if(type==OP_SELLSTOP) sells_S++;
      else
         if(type==OP_BUYLIMIT) buys_L++;
      else
         if(type==OP_SELLLIMIT) sells_L++;
     }

   Orders_Total=buys_+sells_+buys_S+sells_S+buys_L+sells_L;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Close_all_f()
  {
   int type;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      bool ticket_ex=false;
      for(int j_ex=0;j_ex<MaxAttempts; j_ex++)
        {
         while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
         RefreshRates();

         if(type==OP_BUY) ticket_ex=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,clrYellow);
         else
            if(type==OP_SELL) ticket_ex=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,clrYellow);
         else
            if(type==OP_SELLSTOP || type==OP_BUYSTOP || type==OP_SELLLIMIT || type==OP_BUYLIMIT) ticket_ex=OrderDelete(OrderTicket(),clrBrown);
         else
            break;
         if(ticket_ex==true)break;
        }
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void SL_TP_f()
  {
   double modify_price_SL;
   double modify_price_TP;
   int type;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
      RefreshRates();

      if(type==OP_BUY)
        {
         modify_price_SL=OrderOpenPrice()-StopLoss*point;
         if(StopLoss==0) modify_price_SL=OrderStopLoss();
         modify_price_TP=OrderOpenPrice()+TakeProfit*point;
         if(TakeProfit==0) modify_price_TP=OrderTakeProfit();

         if(((StopLoss>0 && OrderStopLoss()==0) || StopLoss==0)
            && ((TakeProfit>0 && OrderTakeProfit()==0) || TakeProfit==0))
            if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(modify_price_SL,Digits),NormalizeDouble(modify_price_TP,Digits),0,clrNONE)) continue;
         else
         if(OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,clrNONE)) {Alert("Order "+string(OrderTicket())+" closed via stops are out of price!");continue;}
        }

      if(type==OP_SELL)
        {
         modify_price_SL=OrderOpenPrice()+StopLoss*point;
         if(StopLoss==0) modify_price_SL=OrderStopLoss();
         modify_price_TP=OrderOpenPrice()-TakeProfit*point;
         if(TakeProfit==0) modify_price_TP=OrderTakeProfit();

         if(((StopLoss>0 && OrderStopLoss()==0) || StopLoss==0)
            && ((TakeProfit>0 && OrderTakeProfit()==0) || TakeProfit==0))
            if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(modify_price_SL,Digits),NormalizeDouble(modify_price_TP,Digits),0,clrNONE)) continue;
         else
         if(OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,clrNONE)) {Alert("Order "+string(OrderTicket())+" closed via stops are out of price!");continue;}
        }

     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Virtual_stops_chek_f()
  {
   int type;
   bool ticket_ex;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      ticket_ex=false;
      for(int j_ex=0;j_ex<MaxAttempts; j_ex++)
        {
         while(IsTradeContextBusy()) Sleep(int(pause_if_busy*1000));
         RefreshRates();

         if(type==OP_BUY && (Bid>=OrderOpenPrice()+v_TakeProfit*point || Bid<=OrderOpenPrice()-v_StopLoss*point)) ticket_ex=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,clrNONE);
         else
            if(type==OP_SELL && (Ask<=OrderOpenPrice()-v_TakeProfit*point || Ask>=OrderOpenPrice()+v_StopLoss*point)) ticket_ex=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,clrNONE);
         else
            break;

         if(ticket_ex==true)break;
        }
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double chek_prev_order_f()
  {
   double lt=Lot;
   int type;

   for(int i=OrdersHistoryTotal()-1; i>=0; i--)
     {
      if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
      if(OrderMagicNumber()!=Magic || OrderSymbol()!=Symbol()) continue;

      type=OrderType();

      if(type==OP_SELL)
        {
         if((!use_martini_on_SL && OrderProfit()+OrderSwap()+OrderCommission()<=-Lose_to_on_martini) || (use_martini_on_SL && OrderClosePrice()>=OrderStopLoss()))
            lt=OrderLots()*Lot_multip_closed;
         break;
        }

      if(type==OP_BUY)
        {
         if((!use_martini_on_SL && OrderProfit()+OrderSwap()+OrderCommission()<=-Lose_to_on_martini) || (use_martini_on_SL && OrderClosePrice()<=OrderStopLoss()))
            lt=OrderLots()*Lot_multip_closed;
         break;
        }
     }

   return(NormalizeDouble(lt,nor_lot));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool work_time_f()
  {
   string TC_s=TimeToString(TimeCurrent(),TIME_MINUTES);

   if(
      (start_time_1+stop_time_1=="" || ((start_time_1<stop_time_1 && (TC_s<start_time_1 || TC_s>=stop_time_1)) || (start_time_1>stop_time_1 && (TC_s<start_time_1 && TC_s>=stop_time_1))))
      && (start_time_2+stop_time_2=="" || ((start_time_2<stop_time_2 && (TC_s<start_time_2 || TC_s>=stop_time_2)) || (start_time_2>stop_time_2 && (TC_s<start_time_2 && TC_s>=stop_time_2))))
      && (start_time_3+stop_time_3=="" || ((start_time_3<stop_time_3 && (TC_s<start_time_3 || TC_s>=stop_time_3)) || (start_time_3>stop_time_3 && (TC_s<start_time_3 && TC_s>=stop_time_3))))
      )  return(false);



   return (true);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool News_ok_f()
  {
   datetime news1_time=news_times_id[0];

   if(time_PC<news1_time-no_trade_before_news_minutes*60 || time_PC>news1_time+no_trade_after_news_minutes*60) return(true);



   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void news_update_f()
  {
   if(time_PC-last_update_time<refresh_minutes*60) return;
   last_update_time=time_PC;
   delete_prev_objects_f();

//web
   char post[],result[];
   string headers;
   int request=WebRequest("GET",site,NULL,NULL,1000,post,0,result,headers);
//if(request==-1) {Alert("Allow site "+site+" in terminal settings!");ExpertRemove();}

//all text
   string all_text=CharArrayToString(result);

//news to buffs
   int events=ParseXML(all_text);

//start buf index to chek news
   datetime time_loca=time_PC;
   datetime time_GMT=TimeGMT();
   datetime final_time;
   int x;
   for(x=0;x<events;x++)
     {
      final_time=mainDataGMT[x]+(time_loca-time_GMT);
      if(final_time>=time_loca-old_news_time_minute_stay*60) break;
     }

//draw
   delete_prev_objects_f();
   cou=0;
   int Y=Y_start;
   for(int i=x;i<events;i++)
     {
      OutputToChartTextOneLine(i,Y); Y+=Y_step;
      if(cou>=ShowEventsNum) break;
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OutputToChartTextOneLine(int id,int curY)
  {

   datetime CurrentGMT=TimeGMT();
   datetime timeLoca=time_PC;

   string title   = mainData[id][TITLE];
   string country = mainData[id][COUNTRY];
   string impact  = mainData[id][IMPACT];
   string forecast = mainData[id][FORECAST];
   string previous = mainData[id][PREVIOUS];


   string times=TimeToStr(mainDataGMT[id]+(timeLoca-CurrentGMT),TIME_MINUTES);
   if(mainDataGMT[id]-TimeGMTOffset()>=iTime(Symbol(),PERIOD_D1,0)+60*60*24)
     {
      times   = TimeToStr( mainDataGMT[id] + ( timeLoca - CurrentGMT ), TIME_DATE | TIME_MINUTES );
      times   = StringSubstr( times, 0 );
     }

   color  TxtColorNews_=clrNONE;
   if( impact == "High" )   TxtColorNews_ = TxtColorImpactHigh;
   if( impact == "Low" )    TxtColorNews_ = TxtColorImpactLow;
   if( impact == "Medium" ) TxtColorNews_ = TxtColorImpactMed;
   if(mainDataGMT[id]+(timeLoca-CurrentGMT)<timeLoca) TxtColorNews_=TxtColorOldNews;

//filter
   if(SkipSameNews_Pair_Time_Impact && id>0 && mainDataGMT[id]==mainDataGMT[id-1] && mainData[id][COUNTRY]==mainData[id-1][COUNTRY] && mainData[id][IMPACT]==mainData[id-1][IMPACT]) return;
   news_times_id[cou]=StringToTime(times); //news times in buff
   cou++;

   if(draw_news)
     {
      string name=identif+string(cou);
      if(ObjectFind(name)==-1)
        {
         ObjectCreate(0,name,OBJ_LABEL,0,0,0);
         ObjectSetInteger(0,name,OBJPROP_CORNER,TxtCorner);
         ObjectSetInteger(0,name,OBJPROP_XDISTANCE,X);
         ObjectSetInteger(0,name,OBJPROP_YDISTANCE,curY);
         ObjectSetInteger(0,name,OBJPROP_FONTSIZE,TxtSize);
         ObjectSetInteger(0,name,OBJPROP_COLOR,TxtColorNews_);
         ObjectSetString(0,name,OBJPROP_FONT,TxtFont);
         ObjectSetInteger(0,name,OBJPROP_ANCHOR,ANCHOR_LEFT_LOWER);
         ObjectSetInteger(0,name,OBJPROP_SELECTABLE,false);
         ObjectSetInteger(0,name,OBJPROP_SELECTED,false);
         ObjectSetInteger(0,name,OBJPROP_HIDDEN,true);
         ObjectSetInteger(0,name,OBJPROP_ZORDER,false);
         ObjectSetString(0,name,OBJPROP_TEXT,times+" "+country+" "+title+MakeForecastPreviousTEXT(forecast,previous));
        }
     }

   return;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int ParseXML(string sData)
  {
//Print("Parse XML");
// Get the currency pair, and split it into the two countries
   string pair=Symbol();
   string cntry1 = StringSubstr( pair, 0, 3 );
   string cntry2 = StringSubstr( pair, 3, 3 );


// -------------------------------------------------
// Parse the XML file looking for an event to report
// -------------------------------------------------
   int newsIdx = 0;
   int BoEvent = 0;
   int begin,next,end;
   string PrevNewsTime="";
   while(newsIdx<EVENTMAX)
     {
      BoEvent=StringFind(sData,"<event>",BoEvent);
      if(BoEvent==-1) break;

      BoEvent+=7;
      next=StringFind(sData,"</event>",BoEvent);
      if(next==-1) break;

      string myEvent=StringSubstr(sData,BoEvent,next-BoEvent);
      BoEvent=next;

      begin=0;
      bool skip=false;
      for(int i=0; i<7; i++)
        {
         mainData[newsIdx][i]="";
         next=StringFind(myEvent,sTags[i],begin);

         // Within this event, if tag not found, then it must be missing; skip it
         if(next==-1)
            continue;
         else
           {
            // We must have found the sTag okay...
            begin = next + StringLen( sTags[i] );         // Advance past the start tag
            end = StringFind( myEvent,eTags[i],begin );   // Find start of end tag
            if(end>begin && end!=-1)
              {
               // Get data between start and end tag
               //mainData[newsIdx][i] = StringSubstr(myEvent, begin, end - begin);


               // Get data between start and end tag
               mainData[newsIdx][i]=StringSubstr(myEvent,begin,end-begin);
               //check for CDATA tag - added by euclid
               if(StringSubstr(mainData[newsIdx][i],0,9)=="<![CDATA[")
                 {
                  mainData[newsIdx][i]=StringSubstr(mainData[newsIdx][i],9,StringLen(mainData[newsIdx][i])-12);
                 }
               if(StringSubstr(mainData[newsIdx][i],0,4)=="&lt;")
                 {
                  mainData[newsIdx][i]="<"+StringSubstr(mainData[newsIdx][i],4);
                 }
               if(StringSubstr(mainData[newsIdx][i],0,4)=="&gt;")
                 {
                  mainData[newsIdx][i]=">"+StringSubstr(mainData[newsIdx][i],4);
                 }

               //also needs to check for HTML entities here... (euclid)
              }
           }
        }

      // = - =   = - =   = - =   = - =   = - =   = - =   = - =   = - =   = - =   = - =
      // Test against filters that define whether we want to
      // skip this particular annoucement
      if(cntry1!=mainData[newsIdx][COUNTRY] && cntry2!=mainData[newsIdx][COUNTRY] && 
         (!ReportAllPairs))
         skip=true;

      if( !IncludeHigh && mainData[newsIdx][IMPACT]   == "High" )   skip = true;
      if( !IncludeMedium && mainData[newsIdx][IMPACT] == "Medium" ) skip = true;
      if( !IncludeLow && mainData[newsIdx][IMPACT]    == "Low" )    skip = true;
      if(mainData[newsIdx][IMPACT]=="Holiday") skip=true;

      if(!IncludeSpeaks && (StringFind(mainData[newsIdx][TITLE],"speaks")!=-1 || 
         StringFind(mainData[newsIdx][TITLE],"Speaks")!=-1))
         skip=true;
      if(mainData[newsIdx][TIME]=="All Day" || 
         mainData[newsIdx][TIME] == "Tentative" ||
         mainData[newsIdx][TIME] == "" )
         skip=true;

      //if( SkipSameTimeNews && PrevNewsTime == mainData[newsIdx][DATE] + mainData[newsIdx][TIME] )
      //skip = true;

      PrevNewsTime=mainData[newsIdx][DATE]+mainData[newsIdx][TIME];

      // = - =   = - =   = - =   = - =   = - =   = - =   = - =   = - =   = - =   = - =

      // If not skipping this event, then log it into the draw buffers
      if(!skip)
        {
         mainDataGMT[newsIdx]=StrToTime(MakeDateTime(mainData[newsIdx][DATE],mainData[newsIdx][TIME]));

         newsIdx++;
           } else {
         // delete skipped data.
         mainData[newsIdx][TITLE]="";
        }
     }//while

   return( newsIdx );
  }
//=================================================================================================
string MakeForecastPreviousTEXT(string f,string p)
  {
   if( StringLen( f ) == 0 && StringLen( p ) == 0 ) return( "" );
   if( StringLen( f ) > 0 && StringLen( p ) == 0 ) return( "  (" + f + "/-.-)" );
   if( StringLen( f ) == 0 && StringLen( p ) >  0 ) return( "  (-.-/" + p + ")" );
   return( "  (" + f + "/" + p + ")" );
  }
//=================================================================================================
string MakeDateTime(string strDate,string strTime)
  {
// Print("Converting Forex Factory Time into Metatrader time..."); //added by MN
// Converts forexfactory time & date into yyyy.mm.dd hh:mm
   int n1stDash = StringFind( strDate, "-" );
   int n2ndDash = StringFind( strDate, "-", n1stDash + 1 );

   string strMonth=StringSubstr(strDate,0,2);
   string strDay=StringSubstr(strDate,3,2);
   string strYear=StringSubstr(strDate,6,4);
//	strYear = "20" + strYear;

   int nTimeColonPos=StringFind(strTime,":");
   string strHour=StringSubstr(strTime,0,nTimeColonPos);
   string strMinute= StringSubstr(strTime,nTimeColonPos+1,2);
   string strAM_PM = StringSubstr(strTime,StringLen(strTime)-2);

   int nHour24=StrToInteger(strHour);
   if((strAM_PM == "pm" || strAM_PM == "PM") && nHour24 != 12) {nHour24 += 12;}
   if((strAM_PM == "am" || strAM_PM == "AM") && nHour24 == 12) {nHour24 = 0;}

   string strHourPad="";
   if(nHour24<10)
      strHourPad="0";

   return( StringConcatenate( strYear, ".", strMonth, ".", strDay, " ", strHourPad, nHour24, ":", strMinute ) );
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void delete_prev_objects_f()
  {
   string name_delete;
   for(int i=ObjectsTotal()-1;i>=0;i--)
     {
      name_delete=ObjectName(i);
      if(StringFind(name_delete,identif)!=-1) ObjectDelete(name_delete);
     }

  }

//+------------------------------------------------------------------+
