RSI_Tester_News_Example118

Price Data Components
Series array that contains open time of each bar
Orders Execution
It automatically opens orders when conditions are reachedChecks for the total of open ordersIt Closes Orders by itself
Indicators Used
Relative strength index
Miscellaneous
Uses files from the file systemIt reads information from a fileIt writes information to file
0 Views
0 Downloads
0 Favorites
RSI_Tester_News_Example118
//+------------------------------------------------------------------+
//|                                      RSI_Tester_News_Example.mq4 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                            https://www.mql5.com/ru/users/progman |
//+------------------------------------------------------------------+
#property copyright   "https://www.mql5.com/ru/users/progman"
#property version     "1.18"
#property link        "https://www.mql5.com/ru/users/progman"
#property description "RSI_Tester_News_Example"
#property strict

extern string a01="=== GMT & Daylight saving time ===";

extern int GMT=2;
int GMT_Correct;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum DSTtype
  {
   e1 = 1, // Off DST
   e2 = 2, // Europe DST
   e3 = 3, // USA DST
  };
extern DSTtype DST_choice=2;

extern bool Fix_GMT_2011_05_01=true;

extern string a02="===== News Filter =====";

extern bool Use_NewsFilter=true;

extern bool   High_news=true;
extern int  Before_High_minutes  = 120;
extern int  After_High_minutes   = 120;

extern bool Medium_news=true;
extern int  Before_Medium_minutes= 90;
extern int  After_Medium_minutes = 90;

extern bool   Low_news=false;
extern int  Before_Low_minutes= 30;
extern int  After_Low_minutes = 30;

extern bool Speaks_news          = true;
extern int  Before_Speaks_minutes= 90;
extern int  After_Speaks_minutes = 90;

extern bool Auto_Select_News     = true;
extern bool All_Symbols_news     = false;
extern bool USD_news             = false;
extern bool EUR_news             = false;
extern bool GBP_news             = false;
extern bool NZD_news             = false;
extern bool JPY_news             = false;
extern bool AUD_news             = false;
extern bool CAD_news             = false;
extern bool CHF_news             = false;
extern bool CNY_news             = false;

extern bool ControlNewsFile=false;
extern bool InfoPanel=true;

extern string a03="==== RSI ====";
extern int                 RSI_Period=14;
extern ENUM_APPLIED_PRICE  RSI_AplPrice=PRICE_CLOSE;
extern double              RSI_Level=30;
extern double              Lots=0.1;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+

datetime NewsTime[];
string   NewsSymbol[];
string   NewsImpact[];
string   NewsText[];

string File_Name="Calendar.txt";

datetime Summer_Time_switch,Winter_Time_switch;

int CountUpNews;

bool Trade=true;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

   if(Use_NewsFilter)
     {
      if(IsTesting() || IsOptimization())
        {
         if(!FilesCompare())
           {
            Trade=false; // allow or disallow trade

            return(INIT_SUCCEEDED);
           }

         int Array_Res=GlobVarArrResize(); //To count or not count the number of news file

         Print("OnInit() Array_Res= ",Array_Res);

         ArrayResize(NewsTime,Array_Res);
         ArrayResize(NewsSymbol,Array_Res);
         ArrayResize(NewsImpact,Array_Res);
         ArrayResize(NewsText,Array_Res);

         Print("OnInit() LoadNewsArray(true)= ",LoadNewsArray(true)); // Loading news in array         
        }
     }

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

   bool StopTradeNews=false;

   if(Use_NewsFilter)
     {
      if(IsTesting() || IsOptimization())
        {
         int Fix2011_GMT=0;
         
         // Example broker Alpari until May 2011 had GMT +1, and after the May 2011 GMT +2 
         if(Fix_GMT_2011_05_01 && TimeCurrent()<D'2011.05.01') 
           {
            Fix2011_GMT=-1;
           }

         StopTradeNews=HistoryNews(GMT+DSTfun(DST_choice)+Fix2011_GMT);

        }
     }

//------------------------- RSI Open Close
   static datetime IST_Time;
   static double IST_RSI=50;

   if(IST_Time!=iTime(NULL,PERIOD_M1,0))
     {
      IST_Time=iTime(NULL,PERIOD_M1,0);

      if(!Trade)
        {
         Print("!Trade  Disallow!");

         return;
        }

      double RSI_ind=iRSI(NULL,0,RSI_Period,RSI_AplPrice,0);

      bool Buy_Open=0,Sell_Open=0,Contr;

      int Ticket;

      if(RSI_ind>=RSI_Level && IST_RSI<RSI_Level) Buy_Open=true; // Signal Open Buy

      if(RSI_ind<=100-RSI_Level && IST_RSI>100-RSI_Level) Sell_Open=true; // Signal Open Sell


      if(OrdersTotal()==0 && !StopTradeNews) // open an order, if not news 
        {
         if(Buy_Open) Ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,20,0,0,"RSI",111,0,Blue);

         if(Sell_Open) Ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,20,0,0,"RSI",111,0,Red);
        }


      if(OrdersTotal()==1)
        {
         if(Buy_Open && OrderSelect(0,SELECT_BY_POS,MODE_TRADES) && OrderType()==OP_SELL)
           {
            Contr=OrderClose(OrderTicket(),OrderLots(),Ask,20,Blue);

            if(!StopTradeNews) Ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,20,0,0,"RSI",111,0,Blue); // open an order, if not news
           }

         if(Sell_Open && OrderSelect(0,SELECT_BY_POS,MODE_TRADES) && OrderType()==OP_BUY)
           {
            Contr=OrderClose(OrderTicket(),OrderLots(),Bid,20,Blue);

            if(!StopTradeNews) Ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,20,0,0,"RSI",111,0,Blue); // open an order, if not news
           }

        }



      IST_RSI=RSI_ind;
     } // if(IST_Time != iTime(NULL, PERIOD_M1, 0) )

  }
//+------------------------------------------------------------------+

//=============================== Files Compare  folder  Common and tester\files
bool FilesCompare()
  {

   int HandleCommon=-1,HandleTerminal=-1,ErrorF=0,cc;
   bool CheckFiles=true;

//------------ Find files 
   if(!FileIsExist(File_Name,FILE_COMMON) && !FileIsExist(File_Name))
     {
      Print("FilesCompare()   ",File_Name,"  not found!");

      return(false); // Error File
     }

//----------- Copy from Common in tester\files
   if(FileIsExist(File_Name,FILE_COMMON) && !FileIsExist(File_Name))
     {
      Print("FilesCompare()   tester\\files\\",File_Name,"  not found. Copy from ",TerminalInfoString(TERMINAL_COMMONDATA_PATH),"  in   tester\\files\\");

      for(cc=1; cc<5; cc++)
        {
         FileCopy(File_Name,FILE_COMMON,File_Name,FILE_REWRITE);

         ErrorF=GetLastError();

         Print("FilesCompare()  FileCopy GetLastError= ",ErrorF);

         if(ErrorF==0) break;

         Sleep(1000);
        }

      if(ErrorF != 0) return(false);
     }

//------------ Compare files. Update or not update
   if(FileIsExist(File_Name,FILE_COMMON) && FileIsExist(File_Name))
     {

      HandleCommon=FileOpen(File_Name,FILE_SHARE_READ|FILE_COMMON);

      HandleTerminal=FileOpen(File_Name,FILE_SHARE_READ);

      datetime DateCommon=datetime(FileGetInteger(HandleCommon,FILE_MODIFY_DATE));

      datetime DateTerminal=datetime(FileGetInteger(HandleTerminal,FILE_MODIFY_DATE));

      FileClose(HandleTerminal);

      FileClose(HandleCommon);

      Print("FilesCompare()    ",File_Name,"  Date Common= ",DateCommon,"   Date tester\\files\\= ",DateTerminal);

      if(DateCommon>DateTerminal)
        {
         Print("FilesCompare()    ",File_Name," Update Copy from ",TerminalInfoString(TERMINAL_COMMONDATA_PATH),"  in   tester\\files\\");

         for(cc=1; cc<5; cc++)
           {
            FileCopy(File_Name,FILE_COMMON,File_Name,FILE_REWRITE);

            ErrorF=GetLastError();

            Print("FilesCompare()   FileCopy GetLastError= ",ErrorF);

            if(ErrorF==0) break;

            Sleep(1000);
           }

         if(ErrorF != 0) return(false);
        }

     }

   return(CheckFiles);
  }
//=============================== Load News from file in Arrays
int LoadNewsArray(bool loadingF)
  {

//------------ Open File
   int po=1; int HandleTerminal=INVALID_HANDLE;

   while(!IsStopped())
     {
      HandleTerminal=FileOpen(File_Name,FILE_CSV|FILE_SHARE_READ,';');

      if(HandleTerminal==INVALID_HANDLE)
        {
         Print("LoadNewsArray()   ",po,"   ",Symbol());

         int GL_ERR=GetLastError();

         if(GL_ERR==4103)
            Print("LoadNewsArray()    ",GL_ERR,"  Historic calendar file ",File_Name," not found!");
         else
            Print("LoadNewsArray()    ",GL_ERR,"  Historic calendar file Error opening (",File_Name,")");

         Sleep(po*500);

        }
      else
        {
         break;
        }

      if(po >= 5) return(-100);

      po++;

     }

//---------------- Load in array

   CountUpNews=0;

   while(!FileIsEnding(HandleTerminal))
     {
      bool ActivateSym=false,ActiveImp=false;

      datetime Date_news = FileReadDatetime(HandleTerminal);
      string Symbol_news = FileReadString(HandleTerminal);
      string Impact_news = FileReadString(HandleTerminal);
      string Text_news   = FileReadString(HandleTerminal);


      //---Skip old date
      if(Date_news<TimeCurrent()-2678400) continue; // 1 month

      //--- Include Impact and Speaks
      if(High_news) if(StringFind(Impact_news,"H")==0) ActiveImp=true;
      if(Medium_news) if(StringFind(Impact_news,"M")==0) ActiveImp=true;
      if(Low_news) if(StringFind(Impact_news,"L")==0) ActiveImp=true;

      if(Speaks_news) if(StringFind(Text_news,"Speaks")>=0) ActiveImp=true;

      if(!ActiveImp) continue;

      //--- Include symbol
      if(All_Symbols_news)
        {
         ActivateSym=true;
        }
      else
        {
         if(Auto_Select_News)
           {
            if(StringFind(Symbol(),Symbol_news)>=0) ActivateSym=true;

            if(USD_news) if(StringFind(Symbol_news, "USD") >= 0 ) ActivateSym = true;
            if(EUR_news) if(StringFind(Symbol_news, "EUR") >= 0 ) ActivateSym = true;
            if(GBP_news) if(StringFind(Symbol_news, "GBP") >= 0 ) ActivateSym = true;
            if(NZD_news) if(StringFind(Symbol_news, "NZD") >= 0 ) ActivateSym = true;
            if(JPY_news) if(StringFind(Symbol_news, "JPY") >= 0 ) ActivateSym = true;
            if(AUD_news) if(StringFind(Symbol_news, "AUD") >= 0 ) ActivateSym = true;
            if(CAD_news) if(StringFind(Symbol_news, "CAD") >= 0 ) ActivateSym = true;
            if(CHF_news) if(StringFind(Symbol_news, "CHF") >= 0 ) ActivateSym = true;
            if(CNY_news) if(StringFind(Symbol_news, "CNY") >= 0 ) ActivateSym = true;
           }
         else
           {
            if(USD_news) if(StringFind(Symbol_news, "USD") >= 0 ) ActivateSym = true;
            if(EUR_news) if(StringFind(Symbol_news, "EUR") >= 0 ) ActivateSym = true;
            if(GBP_news) if(StringFind(Symbol_news, "GBP") >= 0 ) ActivateSym = true;
            if(NZD_news) if(StringFind(Symbol_news, "NZD") >= 0 ) ActivateSym = true;
            if(JPY_news) if(StringFind(Symbol_news, "JPY") >= 0 ) ActivateSym = true;
            if(AUD_news) if(StringFind(Symbol_news, "AUD") >= 0 ) ActivateSym = true;
            if(CAD_news) if(StringFind(Symbol_news, "CAD") >= 0 ) ActivateSym = true;
            if(CHF_news) if(StringFind(Symbol_news, "CHF") >= 0 ) ActivateSym = true;
            if(CNY_news) if(StringFind(Symbol_news, "CNY") >= 0 ) ActivateSym = true;
           }

        }

      if(!ActivateSym) continue;

      if(loadingF)
        {
         NewsTime[CountUpNews]   = Date_news;
         NewsSymbol[CountUpNews] = Symbol_news;
         NewsImpact[CountUpNews] = Impact_news;
         NewsText[CountUpNews]   = Text_news;
        }

      CountUpNews++;
     } // while

   FileClose(HandleTerminal);


   if(ControlNewsFile && loadingF)
     {
      Print("LoadNewsArray()   ControlNews CountUpNews= ",CountUpNews,"     ArraySize(NewsTime)= ",ArraySize(NewsTime));

      int HHH=FileOpen("ControlNews.csv",FILE_CSV|FILE_WRITE);

      for(int rr=0; rr<CountUpNews; rr++)
        {
         string VV=StringConcatenate(TimeToString(NewsTime[rr],TIME_DATE|TIME_MINUTES),";",NewsSymbol[rr],";",NewsImpact[rr],";",NewsText[rr]);

         FileWrite(HHH,VV);
        }

      FileClose(HHH);
     }

   return(CountUpNews);
  }
//================================= History News
bool HistoryNews(int gmtF)
  {
   static datetime IST_TimeM1;
   static int PosMas=0;
   static bool pauseF;

   if(IST_TimeM1!=iTime(NULL,PERIOD_M1,0))
     {
      IST_TimeM1=iTime(NULL,PERIOD_M1,0);
      //Print("M1");

      int AfterMinutes,BeforeMinutes,Step;

      datetime Time_GMT_0;

      pauseF=false;

      Time_GMT_0=TimeCurrent() -(gmtF*60*60);

      for(Step=PosMas; Step<CountUpNews; Step++)
        {
         PosMas=Step;

         if(NewsTime[Step]>Time_GMT_0) break;
        }

      //------------ Before
      BeforeMinutes=12345;

      if(Step<CountUpNews)
        {
         BeforeMinutes=int(NewsTime[Step]-Time_GMT_0)/60;
         if(NewsImpact[Step]== "H") if(BeforeMinutes <= Before_High_minutes) pauseF = true;
         if(NewsImpact[Step]== "M") if(BeforeMinutes <= Before_Medium_minutes) pauseF = true;
         if(NewsImpact[Step]== "L") if(BeforeMinutes <= Before_Low_minutes) pauseF = true;
         if(StringFind(NewsText[Step],"Speaks")>=0) if(BeforeMinutes<=Before_Speaks_minutes) pauseF=true;
        }

      //------------ After News
      AfterMinutes=12345;

      if(Step!=0)
        {
         AfterMinutes=int(Time_GMT_0-NewsTime[Step-1])/60;
         if(NewsImpact[Step - 1]== "H") if(AfterMinutes <= After_High_minutes) pauseF = true;
         if(NewsImpact[Step - 1]== "M") if(AfterMinutes <= After_Medium_minutes) pauseF = true;
         if(NewsImpact[Step - 1]== "L") if(AfterMinutes <= After_Low_minutes) pauseF = true;
         if(StringFind(NewsText[Step-1],"Speaks")>=0) if(AfterMinutes<=Before_Speaks_minutes) pauseF=true;
        }


      if(InfoPanel && IsVisualMode())
        {
         string com1="",com2="";

         if(Step<CountUpNews)
           {
            com1=StringConcatenate(
                                   "\n",
                                   "\n      NewsTime next= ",NewsTime[Step],
                                   "\n      NewsSymbol next= ",NewsSymbol[Step],
                                   "\n      NewsImpact next= ",NewsImpact[Step],
                                   "\n      NewsText next= ",NewsText[Step]
                                   );
           }

         if(Step!=0)
           {
            com2=StringConcatenate(
                                   "\n",
                                   "\n      NewsTime old= ",NewsTime[Step-1],
                                   "\n      NewsSymbol old= ",NewsSymbol[Step-1],
                                   "\n      NewsImpact old= ",NewsImpact[Step-1],
                                   "\n      NewsText old= ",NewsText[Step-1]
                                   );
           }

         Comment(
                 "\n      Summer_Time_switch= ",Summer_Time_switch,
                 "\n      Winter_Time_switch= ",Winter_Time_switch,
                 "\n      TimeCurrent()= ",TimeCurrent(),"     Time_GMT_0= ",Time_GMT_0,"    gmtF= ",gmtF,
                 com1,
                 "\n      BeforeMinutes= ",BeforeMinutes,
                 com2,
                 "\n      AfterMinutes= ",AfterMinutes,
                 "\n",
                 "\n      pauseF= ",pauseF

                 );
        }

     }

   return(pauseF);
  }


//================================ DST - daylight saving time
int DSTfun(int DSTviborF)
  {
   if(DSTviborF == 1) return(0);

   static datetime DSTtimeIST=0;
   static int PlusGMT=0;
   static datetime Spring=0,iTimeMN=0,Autumn=0;

   int dd;

   while(!IsStopped())
     {
      iTimeMN=iTime(NULL,PERIOD_MN1,0);

      if(iTimeMN==0)
        {
         Print("DSTfun()   DST iTime(NULL, PERIOD_MN1, 0)  Error= ",GetLastError());
         Sleep(1000);
        }
      else
        {
         break;
        }
     }

   if(DSTtimeIST!=iTimeMN)
     {
      DSTtimeIST=iTimeMN;

      PlusGMT=0;

      if(DSTviborF==2) //---- Europe
        {
         for(dd=25; dd<=31; dd++)
           {
            Spring=StrToTime(StringConcatenate(IntegerToString(Year()),".03.",IntegerToString(dd)));

            if(TimeDayOfWeek(Spring)==0)
              {
               Summer_Time_switch=Spring;
               break;
              }
           }


         for(dd=25; dd<=31; dd++)
           {
            Autumn=StrToTime(StringConcatenate(IntegerToString(Year()),".10.",IntegerToString(dd)));

            if(TimeDayOfWeek(Autumn)==0)
              {
               Winter_Time_switch=Autumn;
               break;
              }
           }

        } // if(DSTviborF == 2)


      if(DSTviborF==3) //------ USA
        {
         for(dd=8; dd<=14; dd++)
           {
            Spring=StrToTime(StringConcatenate(IntegerToString(Year()),".03.",IntegerToString(dd)));

            if(TimeDayOfWeek(Spring)==0)
              {
               Summer_Time_switch=Spring;
               break;
              }
           }


         for(dd=1; dd<=7; dd++)
           {
            Autumn=StrToTime(StringConcatenate(IntegerToString(Year()),".11.",IntegerToString(dd)));

            if(TimeDayOfWeek(Autumn)==0)
              {
               Winter_Time_switch=Autumn;
               break;
              }
           }

        } // if(DSTviborF == 3)

      Print("DSTfun()   Summer_Time_switch= ",Summer_Time_switch,"     Winter_Time_switch= ",Winter_Time_switch);

     } // if(DSTtimeIST != iTimeMN)

   if(TimeCurrent()>Summer_Time_switch && TimeCurrent()<Winter_Time_switch) PlusGMT=1;
   else  PlusGMT=0;

   return(PlusGMT);
  }


//==========================  Global Variable Resize Update
int GlobVarArrResize()
  {
   string GlMod="Calendar_Modify",GlSize="Calendar_Size";
   datetime FileTimeModify;
   int HandleTerminal;

   HandleTerminal=FileOpen(File_Name,FILE_SHARE_READ);

   FileTimeModify=datetime(FileGetInteger(HandleTerminal,FILE_MODIFY_DATE));

   FileClose(HandleTerminal);

   if(GlobalVariableCheck(GlMod) && GlobalVariableCheck(GlSize))
     {
      Print("GlobVarArrResize()    GlobalVariableGet(GlMod)= ",datetime(GlobalVariableGet(GlMod)),"    FileTimeModify= ",FileTimeModify);

      if(FileTimeModify==datetime(GlobalVariableGet(GlMod)))
        {
         Print("GlobVarArrResize()    GlobalVariableGet(GlSize)= ",GlobalVariableGet(GlSize));

         return( int(GlobalVariableGet(GlSize) ) );
        }
     }

   int NewResize=0;  // Only Calculates the news on the condition 

   HandleTerminal=FileOpen(File_Name,FILE_TXT|FILE_SHARE_READ);

   while(!FileIsEnding(HandleTerminal))
     {
      FileReadString(HandleTerminal);

      NewResize++;
     }

   FileClose(HandleTerminal);

   Print("GlobVarArrResize()     !Change Global variables NewResize= ",NewResize);

   GlobalVariableSet(GlMod,FileTimeModify);

   GlobalVariableSet(GlSize,NewResize);

   return(NewResize); // 

  }
//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---