//+------------------------------------------------------------------+
//|                                                      news ea.mq4 |
//|                                             Copyright © 2017 SVS |
//|                            https://www.mql5.com/ru/users/svs1996 |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2017 SVS, Copyright © 2016 Tor, Lucky$ & KimIV"
#property link      "https://www.mql5.com/ru/users/svs1996"
#property version   "1.0"
#property description "Этот советник загружает новости с сайта Investing.com без использования .dll\nНеобходимо добавить в доверенные URL:\nhttp://ec.forexprostools.com/?columns=exc_currency,exc_importance&importance=1,2,3&calType=week&timeZone=15&lang=1"
#property strict
#include <stdlib.mqh>
#include <WinUser32.mqh>
//--- enum parameters

enum AutoMM
  {
   Fixed=0,//Fixed - Автоматика отключена
   Risk_Control=1,//Расчет лота по риску
  };
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum AutoStopLoss
  {
   Fixed_SL=0,//Fixed - Классический фиксированый Stop Loss
   ATR_SL=1,//ATR - Расчет Stop Loss по ATR * множитель
  };
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum AutoTakeProfit
  {
   Fixed_TP=0,//Fixed - Классический фиксированный Take Profit
   ATR_TP=1,//ATR - Расчет Take Profit по ATR * множитель
  };
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum AutoDistancSet
  {
   Fixed_DistanceSet=0,//Fixed - Фиксированая дистанция расстановки ордеров от рынка
   ATR_DistanceSet=1,//ATR - Расчет дистанции растановки ордеров от рынка по ATR * множитель
  };
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum AutoTrailingStopLoss
  {
   Fixed_TrailingSL=0,//Fixed - После подтягивания Stop Loss будет на указанном расстоянии от рыночной цены
   ATR_TrailingSL=1,//ATR - После подтягивания Stop Loss будет на расстояние ATR * множитель от рыночной цены.
  };
//------- Внешние параметры советника --------------------------------
input  int BeforeNewsStop=5; // За сколько минут до наступления новости открывать отложки.
input  int AfterNewsStop=60; // Через сколько минут закрывать несработавшие отложки и опционально позицию.
input bool ClosePos=False;//Закрывать ли позицию (открытый ордер) по истечении сигнала
input bool NewsLight= false; // Включить слабые новости
input bool NewsMedium=false; // Включить средние новости
input bool NewsHard=true; // Включить сильные новости
input int  offset=3;     // Часовой пояс торгового сервера, GMT (for news)
input string NewsSymb=""; //Валюта для отображения новостей (пусто - только текущие валюты)(пример USD,EUR,GBP,CHF,CAD,AUD,NZD,JPY)
input bool  DrawLines=true;       // Отрисовка линий новостей на графике
input bool  Next           = false;      // Рисовать только будущие новости
input bool  Signal         = false;      // Сигналы о предстоящих новостях

extern string _Parameters_Trade="----- Параметры торговли";
input AutoMM Type_Calculation=Risk_Control; //AutoMM - Включать Money Management
input double Risk=5.0;//Risk - Максимальный риск на сделку
extern double Lots=0.1;     // Размер торгуемого лота
input AutoStopLoss Type_SL=ATR_SL;  // Тип стопа
extern int    StopLoss=15;      // Размер фиксированного стопа
input int PATR_SL=96;        // Период ATR стопа
input double XATR_SL=7.0;      // Можитель ATR стопа
input AutoTakeProfit Type_TP=ATR_TP;   // Тип тэйка
extern int    TakeProfit=0;       // Размер фиксированного тэйка
input int PATR_TP=96;        // Период ATR тэйка
input double XATR_TP=8.0;      // Можитель ATR тэйка
/*extern string TimeSetOrders  = "10:30"; // Время установки ордеров
extern string TimeDelOrders  = "22:30"; // Время удаления ордеров
extern string TimeClosePos   = "22:30"; // Время закрытия позиций*/
input AutoDistancSet Type_DistanceSet=ATR_DistanceSet;//Вариант расчета расстояния от рынка
extern int    DistanceSet=20;      // Расстояние от рынка
input int PATR_DistanceSet=96;        // Период ATR рассчета расстояния от рынка
input double XATR_DistanceSet= 1.5;     // Можитель ATR рассчета расстояния от рынка
extern bool   UseTrailing    = True;    // Использовать трал
extern bool   ProfitTrailing = True;    // Тралить только профит
input AutoTrailingStopLoss Type_TrailingStop=ATR_TrailingSL; //Тип размера трала
extern int    TrailingStop=25;      // Фиксированный размер трала
input int PATR_TrailingSL=96;        // Период ATR размера трала
input double XATR_TrailingSL= 2.0;      // Можитель ATR размера трала
extern int    TrailingStep   = 5;       // Шаг трала
extern int    Slippage       = 6;       // Проскальзывание цены

extern string _Parameters_Expert="----- Параметры советника";
extern string Name_Expert   = "News EA by SVS";
extern bool   UseSound      = True;         // Использовать звуковой сигнал
extern string NameFileSound = "expert.wav"; // Наименование звукового файла
extern color  clOpenBuy     = LightBlue;    // Цвет открытия покупки
extern color  clOpenSell    = LightCoral;   // Цвет открытия продажи
extern color  clModifyBuy   = Aqua;         // Цвет модификации покупки
extern color  clModifySell  = Tomato;       // Цвет модификации продажи
extern color  clCloseBuy    = Blue;         // Цвет закрытия покупки
extern color  clCloseSell   = Red;          // Цвет закрытия продажи
input int MAGIC=20170303;
//---- Глобальные переменные советника -------------------------------
int prevBar;
double Free,Tick,Spread,StopLevel,MinLot,MaxLot,LotStep;
bool FlagOrder=False;

color highc          = clrRed;     // Colour important news
color mediumc        = clrBlue;    // Colour medium news
color lowc           = clrLime;    // The color of weak news
int   Style          = 2;          // Line style
int   Upd            = 86400;      // Period news updates in seconds

bool  Vhigh          = false;
bool  Vmedium        = false;
bool  Vlow           = false;
int   MinBefore=0;
int   MinAfter=0;

int NomNews=0;
string NewsArr[4][1000];
int Now=0;
datetime LastUpd;
string str1;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {

   if(StringLen(NewsSymb)>1)str1=NewsSymb;
   else str1=Symbol();

   Vhigh=NewsHard;
   Vmedium=NewsMedium;
   Vlow=NewsLight;

   MinBefore=BeforeNewsStop;
   MinAfter=AfterNewsStop;

   if(Digits==3 || Digits==5) //проверка на 4х, 5-и знаковый счет
     {
      Slippage*=10; TakeProfit*=10; StopLoss*=10; TrailingStop*=10; TrailingStep*=10;
     }

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0,OBJ_VLINE);
   Comment("");
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int LotCorrection()
  {
   Lots=MathRound(Lots/LotStep)*LotStep; // округление объема до ближайшего допустимого
   if(Lots<MinLot || Lots>MaxLot) // объем сделки не меньше MinLot и не больше MaxLot
     {
      Alert("Параметром Lots был задан неправильный объем сделки!");
      return(0);
     }
   else return(1);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void MarketAnalysis()
  {
   Free=ND(AccountFreeMargin());
   Tick=MarketInfo(Symbol(),MODE_TICKSIZE);                         // минимальный тик    
   Spread=ND(MarketInfo(Symbol(),MODE_SPREAD)*Point);                  // текщий спрэд
   StopLevel=ND(MarketInfo(Symbol(),MODE_STOPLEVEL)*Point);  // текущий уровень стопов 
   MinLot = MarketInfo(Symbol(),MODE_MINLOT);    // минимальный разрешенный объем сделки
   MaxLot = MarketInfo(Symbol(), MODE_MAXLOT);   // максимальный разрешенный объем сделки
   LotStep=MarketInfo(Symbol(),MODE_LOTSTEP);          // шаг приращения объема сделки
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double ND(double A)
  {
   return(NormalizeDouble(A, Digits));
  }
//+-------------------------------------------------------------------------------------+
//| Приведение значений к точности одного тика                                          |
//+-------------------------------------------------------------------------------------+
double NP(double A)
  {
   return(MathFloor(A/Tick)*Tick);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

   double CheckNews=0;
   if(AfterNewsStop>0)
     {
      if(TimeCurrent()-LastUpd>=Upd){Comment("News Loading...");Print("News Loading...");UpdateNews();LastUpd=TimeCurrent();Comment("");}
      WindowRedraw();
      //---Draw a line on the chart news--------------------------------------------
      if(DrawLines)
        {
         for(int i=0;i<NomNews;i++)
           {
            string Name=StringSubstr(TimeToStr(TimeNewsFunck(i),TIME_MINUTES)+"_"+NewsArr[1][i]+"_"+NewsArr[3][i],0,63);
            if(NewsArr[3][i]!="")if(ObjectFind(Name)==0)continue;
            if(StringFind(str1,NewsArr[1][i])<0)continue;
            if(TimeNewsFunck(i)<TimeCurrent() && Next)continue;

            color clrf=clrNONE;
            if(Vhigh && StringFind(NewsArr[2][i],"High")>=0)clrf=highc;
            if(Vmedium && StringFind(NewsArr[2][i],"Moderate")>=0)clrf=mediumc;
            if(Vlow && StringFind(NewsArr[2][i],"Low")>=0)clrf=lowc;

            if(clrf==clrNONE)continue;

            if(NewsArr[3][i]!="")
              {
               ObjectCreate(Name,0,OBJ_VLINE,TimeNewsFunck(i),0);
               ObjectSet(Name,OBJPROP_COLOR,clrf);
               ObjectSet(Name,OBJPROP_STYLE,Style);
               ObjectSetInteger(0,Name,OBJPROP_BACK,true);
              }
           }
        }
      //---------------event Processing------------------------------------
      int i;
      CheckNews=0;
      for(i=0;i<NomNews;i++)
        {
         int power=0;
         if(Vhigh && StringFind(NewsArr[2][i],"High")>=0)power=1;
         if(Vmedium && StringFind(NewsArr[2][i],"Moderate")>=0)power=2;
         if(Vlow && StringFind(NewsArr[2][i],"Low")>=0)power=3;
         if(power==0)continue;
         if(TimeCurrent()+MinBefore*60>TimeNewsFunck(i) && TimeCurrent()-MinAfter*60<TimeNewsFunck(i) && StringFind(str1,NewsArr[1][i])>=0)
           {
            CheckNews=1;
            break;
           }
         else CheckNews=0;

        }
      if(CheckNews==1 && i!=Now && Signal) { Alert("In ",(int)(TimeNewsFunck(i)-TimeCurrent())/60," minutes released news ",NewsArr[1][i],"_",NewsArr[3][i]);Now=i;}
/***  ***/
     }
   ATRcalc();
   if(CheckNews>0)
     {
      /////  We are doing here if we are in the framework of the news
      Comment("News time");
      if(ExistOrder(1) && ExistOrder(2)) FlagOrder=True;
      if(!FlagOrder)SetOrders();
      if(prevBar!=Bars && ExistOrder(1) && ExistOrder(2)) ModifyOrders();
     }
   else
     {
      // We are out of scope of the news release (No News)
      Comment("No news");
      DeleteAllOrders();
      if(ClosePos)CloseAllPositions();
      FlagOrder=False;

     }
   DeleteOppositeOrders();
   TrailingPositions();
   prevBar=Bars;

  }
//+------------------------------------------------------------------+
//////////////////////////////////////////////////////////////////////////////////
// Download CBOE page source code in a text variable
// And returns the result
//////////////////////////////////////////////////////////////////////////////////
string ReadCBOE()
  {

   string cookie=NULL,headers;
   char post[],result[];     string TXT="";
   string subfolder="NewsEA";
   string NameFile=StringConcatenate("\\Symbol-",Symbol(),"_Chart-ID-",ChartID(),"_news-log.html");
   int res;
//--- to work with the server, you must add the URL "https://www.google.com/finance"  
//--- the list of allowed URL (Main menu-> Tools-> Settings tab "Advisors"): 
   string google_url="http://ec.forexprostools.com/?columns=exc_currency,exc_importance&importance=1,2,3&calType=week&timeZone=15&lang=1";
//--- 
   ResetLastError();
//--- download html-pages
   int timeout=5000; //--- timeout less than 1,000 (1 sec.) is insufficient at a low speed of the Internet
   res=WebRequest("GET",google_url,cookie,NULL,timeout,post,0,result,headers);
//--- error checking
   if(res==-1)
     {
      Print("WebRequest error, err.code  =",GetLastError());
      MessageBox("You must add the address ' "+google_url+"' in the list of allowed URL tab 'Advisors' "," Error ",MB_ICONINFORMATION);
      //--- You must add the address ' "+ google url"' in the list of allowed URL tab 'Advisors' "," Error "
     }
   else
     {
      //--- successful download
      PrintFormat("File successfully downloaded, the file size in bytes  =%d.",ArraySize(result));
      //--- save the data in the file
      int filehandle=FileOpen(subfolder+NameFile,FILE_WRITE|FILE_BIN);
      //--- проверка ошибки 
      if(filehandle!=INVALID_HANDLE)
        {
         //---save the contents of the array result [] in file 
         FileWriteArray(filehandle,result,0,ArraySize(result));
         //--- close file 
         FileClose(filehandle);

         int filehandle2=FileOpen(subfolder+NameFile,FILE_READ|FILE_BIN);
         TXT=FileReadString(filehandle2,ArraySize(result));
         FileClose(filehandle2);
        }
      else
        {
         Print("Error in FileOpen. Error code =",GetLastError());
        }
     }

   return(TXT);
  }
//+------------------------------------------------------------------+
datetime TimeNewsFunck(int nomf)
  {
   string s=NewsArr[0][nomf];
   string time=StringConcatenate(StringSubstr(s,0,4),".",StringSubstr(s,5,2),".",StringSubstr(s,8,2)," ",StringSubstr(s,11,2),":",StringSubstr(s,14,4));
   return((datetime)(StringToTime(time) + offset*3600));
  }
//////////////////////////////////////////////////////////////////////////////////
void UpdateNews()
  {
   string TEXT=ReadCBOE();
   int sh = StringFind(TEXT,"pageStartAt>")+12;
   int sh2= StringFind(TEXT,"</tbody>");
   TEXT=StringSubstr(TEXT,sh,sh2-sh);

   sh=0;
   while(!IsStopped())
     {
      sh = StringFind(TEXT,"event_timestamp",sh)+17;
      sh2= StringFind(TEXT,"onclick",sh)-2;
      if(sh<17 || sh2<0)break;
      NewsArr[0][NomNews]=StringSubstr(TEXT,sh,sh2-sh);

      sh = StringFind(TEXT,"flagCur",sh)+10;
      sh2= sh+3;
      if(sh<10 || sh2<3)break;
      NewsArr[1][NomNews]=StringSubstr(TEXT,sh,sh2-sh);
      if(StringFind(str1,NewsArr[1][NomNews])<0)continue;

      sh = StringFind(TEXT,"title",sh)+7;
      sh2= StringFind(TEXT,"Volatility",sh)-1;
      if(sh<7 || sh2<0)break;
      NewsArr[2][NomNews]=StringSubstr(TEXT,sh,sh2-sh);
      if(StringFind(NewsArr[2][NomNews],"High")>=0 && !Vhigh)continue;
      if(StringFind(NewsArr[2][NomNews],"Moderate")>=0 && !Vmedium)continue;
      if(StringFind(NewsArr[2][NomNews],"Low")>=0 && !Vlow)continue;

      sh=StringFind(TEXT,"left event",sh)+12;
      int sh1=StringFind(TEXT,"Speaks",sh);
      sh2=StringFind(TEXT,"<",sh);
      if(sh<12 || sh2<0)break;
      if(sh1<0 || sh1>sh2)NewsArr[3][NomNews]=StringSubstr(TEXT,sh,sh2-sh);
      else NewsArr[3][NomNews]=StringSubstr(TEXT,sh,sh1-sh);

      NomNews++;
      if(NomNews==300)break;
     }
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
/*void start()
  {
   if(TimeToStr(CurTime(),TIME_MINUTES)==TimeSetOrders) SetOrders();
   if(prevBar!=Bars && ExistOrder(1) && ExistOrder(2)) ModifyOrders();
   DeleteOppositeOrders();
   TrailingPositions();
   if(TimeToStr(CurTime(), TIME_MINUTES)==TimeDelOrders) DeleteAllOrders();
   if(TimeToStr(CurTime(), TIME_MINUTES)==TimeClosePos) CloseAllPositions();
   prevBar=Bars;
  }*/
//+------------------------------------------------------------------+
//| Установка ордеров                                                |
//+------------------------------------------------------------------+
void SetOrders()
  {
   double ldStop=0,ldTake=0;
   int    spr=(int)MarketInfo(Symbol(),MODE_SPREAD);
   double pAsk=Ask+(DistanceSet+spr)*Point;
   double pBid=Bid-DistanceSet*Point;

   if(!ExistOrder(1))
     {
      if(StopLoss!=0 || (Type_SL==1 && XATR_SL>0)) ldStop=pAsk-StopLoss*Point;
      if(TakeProfit!=0 || (Type_TP==1 && XATR_TP>0)) ldTake=pAsk+TakeProfit*Point;
      SetOrder(OP_BUYSTOP,pAsk,ldStop,ldTake,1);
     }
   if(!ExistOrder(2))
     {
      if(StopLoss!=0 || (Type_SL==1 && XATR_SL>0)) ldStop=pBid+StopLoss*Point;
      if(TakeProfit!=0 || (Type_TP==1 && XATR_TP>0)) ldTake=pBid-TakeProfit*Point;
      SetOrder(OP_SELLSTOP,pBid,ldStop,ldTake,2);
     }
  }
//+------------------------------------------------------------------+
//| Модификация ордеров                                              |
//+------------------------------------------------------------------+
void ModifyOrders()
  {
   bool   fm;
   double ldStop=0,ldTake=0;
   int    spr=(int)MarketInfo(Symbol(),MODE_SPREAD);
   double pAsk=Ask+(DistanceSet+spr)*Point;
   double pBid=Bid-DistanceSet*Point;

   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+1)
           {
            if(StopLoss!=0 || (Type_SL==1 && XATR_SL>0)) ldStop=pAsk-StopLoss*Point;
            if(TakeProfit!=0 || (Type_TP==1 && XATR_TP>0)) ldTake=pAsk+TakeProfit*Point;
            fm=OrderModify(OrderTicket(),pAsk,ldStop,ldTake,0,clModifyBuy);
           }
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+2)
           {
            if(StopLoss!=0 || (Type_SL==1 && XATR_SL>0)) ldStop=pBid+StopLoss*Point;
            if(TakeProfit!=0 || (Type_TP==1 && XATR_TP>0)) ldTake=pBid-TakeProfit*Point;
            fm=OrderModify(OrderTicket(),pBid,ldStop,ldTake,0,clModifySell);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Возвращает флаг существования ордера или позиции по номеру       |
//+------------------------------------------------------------------+
bool ExistOrder(int mn)
  {
   bool Exist=False;
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+mn)
           {
            Exist=True; break;
           }
        }
     }
   return(Exist);
  }
//+------------------------------------------------------------------+
//| Возвращает флаг существования позиции по номеру                  |
//+------------------------------------------------------------------+
bool ExistPosition(int mn)
  {
   bool Exist=False;
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGIC+mn)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               Exist=True; break;
              }
           }
        }
     }
   return(Exist);
  }
//+------------------------------------------------------------------+
//| Установка ордера                                                 |
//| Параметры:                                                       |
//|   op     - операция                                              |
//|   pp     - цена                                                  |
//|   ldStop - уровень стоп                                          |
//|   ldTake - уровень тейк                                          |
//|   mn     - добавить к MAGIC                                      |
//+------------------------------------------------------------------+
void SetOrder(int op,double pp,double ldStop,double ldTake,int mn)
  {
   bool fc;
   color  clOpen;
   string lsComm=GetCommentForOrder();
   Money_Management();
   if(op==OP_BUYSTOP) clOpen=clOpenBuy;
   else clOpen=clOpenSell;
   fc=OrderSend(Symbol(),op,Lots,pp,Slippage,ldStop,ldTake,lsComm,MAGIC+mn,0,clOpen);
   if(fc && UseSound) PlaySound(NameFileSound);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Money_Management()
  {
   switch(Type_Calculation)
     {
      case 0:
         break;
      case 1:
        {
         double TickValue=(MarketInfo(Symbol(),MODE_TICKVALUE)==0 ? 1 : MarketInfo(Symbol(),MODE_TICKVALUE));
         double Balance=(AccountEquity()>AccountBalance() ? AccountBalance() : AccountEquity());
         Lots=((Balance-AccountCredit()) *(Risk/100))/StopLoss/TickValue;
         if(MarketInfo(Symbol(),MODE_LOTSTEP)!=0) Lots=MathFloor(Lots/MarketInfo(Symbol(),MODE_LOTSTEP)) *MarketInfo(Symbol(),MODE_LOTSTEP); //округление полученного лота вниз
         Lots=MathMin(MathMax(Lots,MarketInfo(Symbol(),MODE_MINLOT)),MarketInfo(Symbol(),MODE_MAXLOT)); //сравнение полученнго лота с минимальным/максимальным.
         break;
        }
     }
  }
//+------------------------------------------------------------------+
//| Генерирует и возвращает строку коментария для ордера или позиции |
//+------------------------------------------------------------------+
string GetCommentForOrder()
  {
   return(Name_Expert);
  }
//+------------------------------------------------------------------+
//| Удаление всех ордеров                                            |
//+------------------------------------------------------------------+
void DeleteAllOrders()
  {
   bool fd;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2)
           {
            if(OrderSymbol()==Symbol())
              {
               if(OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP)
                 {
                  fd=OrderDelete(OrderTicket());
                  if(fd && UseSound) PlaySound(NameFileSound);
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Закрытие всех позиций по рыночной цене                           |
//+------------------------------------------------------------------+
void CloseAllPositions()
  {
   bool fc;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2)
           {
            if(OrderSymbol()==Symbol())
              {
               fc=False;
               if(OrderType()==OP_BUY)
                 {
                  fc=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,clCloseBuy);
                 }
               if(OrderType()==OP_SELL)
                 {
                  fc=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,clCloseSell);
                 }
               if(fc && UseSound) PlaySound(NameFileSound);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Удаление противоположных ордеров                                 |
//+------------------------------------------------------------------+
void DeleteOppositeOrders()
  {
   bool fd,fep1,fep2;

   fep1=ExistPosition(1);
   fep2=ExistPosition(2);

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol())
           {
            fd=False;
            if(OrderType()==OP_BUYSTOP && OrderMagicNumber()==MAGIC+1)
              {
               if(fep2) fd=OrderDelete(OrderTicket());
              }
            if(OrderType()==OP_SELLSTOP && OrderMagicNumber()==MAGIC+2)
              {
               if(fep1) fd=OrderDelete(OrderTicket());
              }
            if(fd && UseSound) PlaySound(NameFileSound);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Сопровождение позиции простым тралом                             |
//+------------------------------------------------------------------+
void TrailingPositions()
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()>MAGIC && OrderMagicNumber()<=MAGIC+2)
           {
            if(OrderSymbol()==Symbol())
              {
               if(OrderType()==OP_BUY)
                 {
                  if(!ProfitTrailing || (Bid-OrderOpenPrice())>TrailingStop*Point)
                    {
                     if(OrderStopLoss()<Bid-(TrailingStop+TrailingStep-1)*Point)
                       {
                        ModifyStopLoss(Bid-TrailingStop*Point,clModifyBuy);
                       }
                    }
                 }
               if(OrderType()==OP_SELL)
                 {
                  if(!ProfitTrailing || OrderOpenPrice()-Ask>TrailingStop*Point)
                    {
                     if(OrderStopLoss()>Ask+(TrailingStop+TrailingStep-1)*Point || OrderStopLoss()==0)
                       {
                        ModifyStopLoss(Ask+TrailingStop*Point,clModifySell);
                       }
                    }
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Перенос уровня StopLoss                                          |
//| Параметры:                                                       |
//|   ldStopLoss - уровень StopLoss                                  |
//|   clModify   - цвет модификации                                  |
//+------------------------------------------------------------------+
void ModifyStopLoss(double ldStop,color clModify)
  {
   bool   fm;
   double ldOpen=OrderOpenPrice();
   double ldTake=OrderTakeProfit();

   fm=OrderModify(OrderTicket(),ldOpen,ldStop,ldTake,0,clModify);
   if(fm && UseSound) PlaySound(NameFileSound);
  }
//+------------------------------------------------------------------+
void ATRcalc()
  {
   if(Type_SL==1)StopLoss=(int)(iATR(NULL,0,PATR_SL,0)/Point*XATR_SL);
   if(Type_TP==1)TakeProfit=(int)(iATR(NULL,0,PATR_TP,0)/Point*XATR_TP);
   if(Type_DistanceSet==1)DistanceSet=(int)(iATR(NULL,0,PATR_DistanceSet,0)/Point*XATR_DistanceSet);
   if(Type_TrailingStop==1)TrailingStop=(int)(iATR(NULL,0,PATR_TrailingSL,0)/Point*XATR_TrailingSL);
   return;
  }
//+------------------------------------------------------------------+
