[MQL4 Coding Help] Fixing News Filter EA

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
Hello, Currently i am coding a news filter EA and having some errors.

MQL4:
#import "urlmon.dll"
int URLDownloadToFileW(int pCaller,string szURL,string szFileName,int dwReserved,int Callback);
#import
 
#define INAME     "FFCPing"+_Symbol
#define TITLE  0
#define COUNTRY 1
#define DATE  2
#define TIME  3
#define IMPACT  4
#define FORECAST 5
#define PREVIOUS 6
 
input string           NewsFilter="***NEWS FILTER***";              //******** NEWS FILTER ******
input   int  ReCheckMinutes           = 120;                        //. Minutes to re-check calendar
input bool news_High                  =true;                        //. Use High News Filter
input bool News_High_Line             =true;                        //. Use High news line (Red Line)
input int minBefore                    =720;                         //. Minutes Before High impact News
input int minAfter                     =360;                         //. Minutes After High impact News
input bool news_Medium                =false;                        //. Use Medium News Filter
input bool News_Medium_Line           =false;                        //. Use Medium news line (Orange Line)
input int minBefore1                    =60;                          //. Minutes Before Medium impact News
input int minAfter1                     =60;                          //. Minutes After Medium impact News
input bool news_Low                   =false;                        //. Use Low News Filter
input bool News_Low_Line              =false;                        //. Use Low news line (Yellow Line)
input int minBefore2                    =30;                          //. Minutes Before Low impact News
input int minAfter2                     =30;                          //. Minutes After Low impact News
 
string News_Trade_Status = "Undefined";
string NewsURLChecking = "Undefined";
string XMLUpdateTime;
string XMLReadTime;
string XMLDownloadTime;
 
int OnInit()
  {
 
//--- get today time
   TimeOfDay=(int)TimeLocal()%86400;
   Midnight=TimeLocal()-TimeOfDay;
//--- set xml file name ffcal_week_this (fixed name)
   xmlFileName=INAME+"-ffcal_week_this.xml";
//--- checks the existence of the file.
   if(!FileIsExist(xmlFileName))
     {
      xmlDownload();
      xmlRead();
      Print("XML File downloaded and Reading");
     }
//--- else just read it
   else
     {
      xmlRead();
      Print("XML File Reading");
     }
//--- get last modification time
   xmlModifed=(datetime)FileGetInteger(xmlFileName,FILE_MODIFY_DATE,false);
//--- check for updates     
     if(FileIsExist(xmlFileName))
     {
      if(xmlModifed<TimeLocal()-(ReCheckMinutes * 60))
        {
         Print(INAME+": xml file is out of date - Updating New");
         xmlUpdate();
        }
      //--- set timer to update old xml file every x hours
 
      EventSetTimer(ReCheckMinutes * 60);
     }
 
   assignVal=true;
  return(INIT_SUCCEEDED);
}
 
int deinit()
  {
   ObjectsDeleteAll(0,"h_",-1,-1);
   ObjectsDeleteAll(0,"Tr_",-1,-1);
   return (0);
  }
 
Void OnTick()
  {
icomment();
if(!isNewsPause(_Symbol,0))
     {
      News_Trade_Status = "Active";
     }
   else
     {
      News_Trade_Status = "Paused";
     }
}
 
 
void OnTimer()
  {
 
   assignVal=true;
   Print(INAME+": xml file is out of date");
   xmlUpdate();
 
  }
 
//+------------------------------------------------------------------+
//| Create the Verticle line                                         |
//+------------------------------------------------------------------+
bool VLineCreate(const long            chart_ID=0,        // chart's ID
                 const string          name="VLine",      // line name
                 const int             sub_window=0,      // subwindow index
                 datetime              time=0,            // line time
                 const color           clr=clrBlue,        // line color
                 const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
                 const int             width=1,           // line width
                 const bool            back=false,        // in the background
                 const bool            selection=false,   // highlight to move
                 const bool            hidden=true,       // hidden in the object list
                 const long            z_order=0)         // priority for mouse click
  {
//--- create a vertical line
   if(!ObjectCreate(chart_ID,name,OBJ_VLINE,sub_window,time,0))
     {
 
      return(false);
     }
//--- set line color
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot be
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
   return(true);
  }
 
void xmlDownload()
  {
   Sleep(3000);
//---
   ResetLastError();
 
   string cookie=NULL, headers;
   string reqheaders="User-Agent: Mozilla/4.0\r\n";
   char post[],result[];
   int res;
   string url="http://nfs.faireconomy.media/ff_calendar_thisweek.xml";
   ResetLastError();
   int timeout=5000;
   res=WebRequest("GET",url,reqheaders,timeout,post,result,headers);
   if(res==-1)
     {
      Print("Error in WebRequest. Error code  =",GetLastError());
      //--- Perhaps the URL is not listed, display a message about the necessity to add the address
      MessageBox("Add the address '"+url+"' in the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
      NewsURLChecking = "Not Added";
     }
   else
     {
      //--- Load successfully
      NewsURLChecking = "Added";
      XMLDownloadTime = TimeToString(TimeLocal());
      PrintFormat("The file has been successfully loaded, File size =%d bytes.",ArraySize(result));
      //--- Save the data to a file
      int filehandle=FileOpen(xmlFileName,FILE_WRITE|FILE_BIN);
      //--- Checking errors
      if(filehandle!=INVALID_HANDLE)
        {
         //--- Save the contents of the result[] array to a file
         FileWriteArray(filehandle,result,0,ArraySize(result));
         //--- Close the file
         FileClose(filehandle);
        }
      else
         Print("Error in FileOpen. Error code=",GetLastError());
     }
//---
  }
//+------------------------------------------------------------------+
//| Read the XML file                                                |
//+------------------------------------------------------------------+
void xmlRead()
  {
//---
   ResetLastError();
   sData="";
   ulong pos[];
   int   size_;
   Print("Reading file");
   int FileHandle=FileOpen(xmlFileName,FILE_READ|FILE_BIN|FILE_ANSI);
   if(FileHandle!=INVALID_HANDLE)
     {
      //--- receive the file size
      ulong size=FileSize(FileHandle);
      //--- read data from the file
      while(!FileIsEnding(FileHandle))
         sData=FileReadString(FileHandle,(int)size);
      //--- close
      FileClose(FileHandle);
     }
//--- check for errors
   else
      PrintFormat(INAME+": failed to open %s file, Error code = %d",xmlFileName,GetLastError());
   Print("Done.");
   XMLReadTime = TimeToString(TimeLocal());
//---
  }
 
//+------------------------------------------------------------------+
//| Check for update XML                                             |
//+------------------------------------------------------------------+
void xmlUpdate()
  {
   Sleep(3000);
//--- do not download on saturday
   if(TimeDayOfWeek(Midnight)==6)
      return;
   else
     {
      Print(INAME+": check for updates...");
      Print(INAME+": delete old file");
      FileDelete(xmlFileName);
      xmlDownload();
      xmlRead();
      xmlModifed=(datetime)FileGetInteger(xmlFileName,FILE_MODIFY_DATE,false);
      PrintFormat(INAME+": updated successfully! last modified: %s",(string)xmlModifed);
      XMLUpdateTime = TimeToString(TimeLocal());
     }
//---
  }
 
//+------------------------------------------------------------------+
//| Converts ff time & date into yyyy.mm.dd hh:mm - by deVries       |
//+------------------------------------------------------------------+
string MakeDateTime(string strDate,string strTime)
  {
//---
   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);
 
   string tempStr[];
   StringSplit(strTime,StringGetCharacter(":",0),tempStr);
   int nTimeColonPos=StringFind(strTime,":");
   string strHour=tempStr[0];
   string strMinute=StringSubstr(tempStr[1],0,2);
   string strAM_PM=StringSubstr(tempStr[1],2,2);
 
   int nHour24=StringToInteger(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((strYear+"."+strMonth+"."+strDay+" "+strHourPad+nHour24+":"+strMinute));
//---
  }
 
//+------------------------------------------------------------------+
//| Convert day of the week to text                                  |
//+------------------------------------------------------------------+
string DayToStr(datetime time)
  {
   int ThisDay=TimeDayOfWeek(time);
   string day="";
   switch(ThisDay)
     {
      case 0:
         day="Sun";
         break;
      case 1:
         day="Mon";
         break;
      case 2:
         day="Tue";
         break;
      case 3:
         day="Wed";
         break;
      case 4:
         day="Thu";
         break;
      case 5:
         day="Fri";
         break;
      case 6:
         day="Sat";
         break;
     }
   return(day);
  }
//+------------------------------------------------------------------+
//| Convert months to text                                           |
//+------------------------------------------------------------------+
string MonthToStr()
  {
   int ThisMonth=Month();
   string month="";
   switch(ThisMonth)
     {
      case 1:
         month="Jan";
         break;
      case 2:
         month="Feb";
         break;
      case 3:
         month="Mar";
         break;
      case 4:
         month="Apr";
         break;
      case 5:
         month="May";
         break;
      case 6:
         month="Jun";
         break;
      case 7:
         month="Jul";
         break;
      case 8:
         month="Aug";
         break;
      case 9:
         month="Sep";
         break;
      case 10:
         month="Oct";
         break;
      case 11:
         month="Nov";
         break;
      case 12:
         month="Dec";
         break;
     }
   return(month);
  }
 
string nextNews="...";
int total=0;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int UpcomingNewsImpact(string symb,int n)
  {
   nextNews="...";
   string MainSymbol=StringSubstr(symb,0,3);
   string SecondSymbol=StringSubstr(symb,3,3);
//---
   if(assignVal)
     {
      //--- BY AUTHORS WITH SOME MODIFICATIONS
      //--- define the XML Tags, Vars
      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>"};
      int index=0;
      int next=-1;
      int BoEvent=0,begin=0,end=0;
      string myEvent="";
      //--- Minutes calculation
      datetime EventTime=0;
      int EventMinute=0;
      //--- split the currencies into the two parts
 
      //--- loop to get the data from xml tags
      while(true)
        {
         BoEvent=StringFind(sData,"<event>",BoEvent);
         if(BoEvent==-1)
            break;
         BoEvent+=7;
         next=StringFind(sData,"</event>",BoEvent);
         if(next == -1)
            break;
         myEvent = StringSubstr(sData,BoEvent,next-BoEvent);
         BoEvent = next;
         begin=0;
         for(int i=0; i<7; i++)
           {
            Event[index][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...
               //--- Advance past the start tag
               begin=next+StringLen(sTags[i]);
               end=StringFind(myEvent,eTags[i],begin);
               //---Find start of end tag and Get data between start and end tag
               if(end>begin && end!=-1)
                  Event[index][i]=StringSubstr(myEvent,begin,end-begin);
              }
           }
         //--- filters that define whether we want to skip this particular currencies or events
 
         //if(!IsCurrency(Event[index][COUNTRY]))
         //continue;
         /*if(importance!=0 && Event[index][IMPACT]=="High")
            continue;
if(importance!=1 && Event[index][IMPACT]=="Medium")
continue;
if(importance!=2 && Event[index][IMPACT]=="Low")
continue;
if(!IncludeSpeaks && StringFind(Event[index][TITLE],"Speaks")!=-1)
continue;
if(!IncludeHolidays && Event[index][IMPACT]=="Holiday")
continue;*/
         if(Event[index][TIME]=="Tentative" ||
            Event[index][TIME]=="")
            continue;
 
         //--- sometimes they forget to remove the tags :)
         if(StringFind(Event[index][TITLE],"<![CDATA[")!=-1)
            StringReplace(Event[index][TITLE],"<![CDATA[","");
         if(StringFind(Event[index][TITLE],"]]>")!=-1)
            StringReplace(Event[index][TITLE],"]]>","");
         if(StringFind(Event[index][TITLE],"]]>")!=-1)
            StringReplace(Event[index][TITLE],"]]>","");
         //---
         if(StringFind(Event[index][FORECAST],"&lt;")!=-1)
            StringReplace(Event[index][FORECAST],"&lt;","");
         if(StringFind(Event[index][PREVIOUS],"&lt;")!=-1)
            StringReplace(Event[index][PREVIOUS],"&lt;","");
 
         //--- set some values (dashes) if empty
         if(Event[index][FORECAST]=="")
            Event[index][FORECAST]="---";
         if(Event[index][PREVIOUS]=="")
            Event[index][PREVIOUS]="---";
         //--- Convert Event time to MT4 time
         string evD=MakeDateTime(Event[index][DATE],Event[index][TIME]);
         EventTime=datetime(evD);
         index++;
        }
      //--- loop to set arrays/buffers that uses to draw objects and alert
      for(int ii=0; ii<index; ii++)
        {
         if(Event[index][TIME]=="All Day" && Event[ii][IMPACT]=="Holiday" && (MainSymbol==Event[ii][COUNTRY] || SecondSymbol==Event[ii][COUNTRY]))
            return 1;
         eTitle[i][n]    = Event[ii][TITLE];
         eCountry[ii][n]  = Event[ii][COUNTRY];
         eImpact[ii][n]   = Event[ii][IMPACT];
         eTime[ii][n]     = datetime(MakeDateTime(Event[ii][DATE],Event[ii][TIME]))-TimeGMTOffset();
         //Print(eTitle[i]);
        }
      total=index;
     }
 
 
   datetime tn=TimeCurrent();
   for(int qi=0; qi<total; qi++)
     {
      if(MainSymbol!=eCountry[qi][n] && SecondSymbol!=eCountry[qi][n])
         continue;
      if(news_High && (eImpact[qi][n]=="High"))
        {
         if(News_High_Line) {
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrRed,STYLE_SOLID);
            TextCreate(0,"Text"+eTitle[i][n],0,eTime[qi][n],0,eTitle[i][n],clrRed);
            }
        }
      if(news_Medium && (eImpact[qi][n]=="Medium"))
        {
         if(News_Medium_Line)
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrOrange,STYLE_SOLID);
        }
      if(news_Low && (eImpact[qi][n]=="Low"))
        {
         if(News_Low_Line)
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrYellow,STYLE_SOLID);
        }
 
      if(news_High && (eImpact[qi][n]=="High") && eTime[qi][n]<(tn+minAfter*60) && eTime[qi][n]>(tn-minBefore*60))
        {
         return 1;
         if(News_High_Line)
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrRed,STYLE_SOLID);
        }
      if(news_Medium && (eImpact[qi][n]=="Medium") && eTime[qi][n]<(tn+minAfter1*60) && eTime[qi][n]>(tn-minBefore1*60))
        {
         return 1;
         if(News_Medium_Line)
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrOrange,STYLE_SOLID);
        }
      if(news_Low && (eImpact[i][n]=="Low") && eTime[i][n]<(tn+minAfter2*60) && eTime[qi][n]>(tn-minBefore2*60))
        {
         return 1;
         if(News_Low_Line)
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrYellow,STYLE_SOLID);
        }
     }
   return(-1);
  }
//+------------------------------------------------------------------+
//|                     NEWS Values                                          |
//+------------------------------------------------------------------+
bool isNewsPause(string Symb,int n)
  {
   bool res=false;
   res=(UpcomingNewsImpact(Symb,n)==1);
   return res;
  }
void icomment() {
string CommentPartOne = " ---------------------------------------------"
 
                 "\n ------------------------------------------------"
                 "\n :: News Status            : " + News_Trade_Status +
                 "\n :: nfs.faireconomy.media  : " + NewsURLChecking +
                 "\n :: Last News Downloaded   : " + XMLDownloadTime +
                 "\n :: Last News Checked      : " + XMLReadTime +
                 "\n :: Last News Updated      : " + XMLUpdateTime +
                 "\n ------------------------------------------------",
Comment(CommentPartOne); }

Errors :
  1. The function !isNewsPause(_Symbol, 0) is not functioning properly. It should work like this: X minutes before news and X minutes after news = paused. Sometimes it works, and sometimes it does not.
  2. If I provide values greater than 800 minutes (13 hours) for Min_before or Min_after, all the news lines are automatically disabled, and the news filter does not function.
  3. These vertical lines indicate news and display the time label of the news below. I am trying to create a new similar label above, which shows the news title (e.g., FOMC, NFP, etc.). Refer to the example screenshot.


 

Enivid

Administrator
Staff member
Nov 30, 2008
19,168
1,494
144
Odesa
www.earnforex.com
The function !isNewsPause(_Symbol, 0) is not functioning properly. It should work like this: X minutes before news and X minutes after news = paused. Sometimes it works, and sometimes it does not.
There are some issues that I see in your UpcomingNewsImpact function, but I'm not sure they are causing your problem. It's using the TimeCurrent time (server time) to check the current time but it converts the news time to local time (via TimeGMTOffset). If your server time is the same as the local time, it doesn't matter. Otherwise, it could be a problem. There is also a mess with indices here:
Code:
      for(int ii=0; ii
	
Not sure if this is done right. You could probably use some intermediary printing of the data you collect to make sure that everything is fine.
If I provide values greater than 800 minutes (13 hours) for Min_before or Min_after, all the news lines are automatically disabled, and the news filter does not function.
That's strange because your code shows that the lines are drawn independently from those parameters.
These vertical lines indicate news and display the time label of the news below. I am trying to create a new similar label above, which shows the news title (e.g., FOMC, NFP, etc.). Refer to the example screenshot.
Can't see your TextCreate function, but there shouldn't be much problem with that. Just use the OBJ_TEXT objects. There might be some issue with Y to price conversion if you want them to stay at the top of your screen, but it can be solved (see our Candlewicks Length Display indicator for example).
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
There are some issues that I see in your UpcomingNewsImpact function, but I'm not sure they are causing your problem. It's using the TimeCurrent time (server time) to check the current time but it converts the news time to local time (via TimeGMTOffset). If your server time is the same as the local time, it doesn't matter. Otherwise, it could be a problem. There is also a mess with indices here:
My Local PC timezone is different than Broker timezone. Should use like this eTime[ii][n] = datetime(MakeDateTime(Event[ii][DATE],Event[ii][TIME]))-TimeCurrent(); or like this eTime[ii][n] = datetime(MakeDateTime(Event[ii][DATE],Event[ii][TIME]));
Can't see your TextCreate function, but there shouldn't be much problem with that. Just use the OBJ_TEXT objects.
I tried but getting error TextCreate: failed to create "Text" object! Error code = 4200

MQL4:
bool TextCreate(const long            chart_ID=0,               // chart's ID
                const string            name="Text",              // object name
                const int               sub_window=0,             // subwindow index
                datetime                time=0,                   // anchor point time
                double                  price=0,                  // anchor point price
                const string            text="Text",              // the text itself
                const color             clr=clrRed,               // color
                const string            font="Arial",             // font
                const int               font_size=10,             // font size
                const double            angle=0.0,                // text slope
                const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_LOWER, // anchor type
                const bool              back=false,               // in the background
                const bool              selection=false,          // highlight to move
                const bool              hidden=true,              // hidden in the object list
                const long              z_order=0)                // priority for mouse click
  {
 
//--- reset the error value
   ResetLastError();
//--- create Text object
   if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price))
     {
      Print(__FUNCTION__,
            ": failed to create \"Text\" object! Error code = ",GetLastError());
      return(false);
     }
//--- set the text
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the object by mouse
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
   return(true);
  }

Than

MQL4:
  if(news_High && (eImpact[qi][n]=="High"))
        {
         if(News_High_Line) {
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrRed,STYLE_SOLID);
            TextCreate(0,"Text"+TimeToString(eTime[qi][n]),0,eTime[qi][n],0,eTitle[qi][n],clrRed);

That's strange because your code shows that the lines are drawn independently from those parameters.
If i am keeping above value more than 800 (Mins), all the future news veritcle line getting disappeared. Can you check my code ones in your MT4, i can attach me full .mq4 file. Trying to fix this over a week still no solution :(
 

Enivid

Administrator
Staff member
Nov 30, 2008
19,168
1,494
144
Odesa
www.earnforex.com
My Local PC timezone is different than Broker timezone. Should use like this eTime[ii][n] = datetime(MakeDateTime(Event[ii][DATE],Event[ii][TIME]))-TimeCurrent(); or like this eTime[ii][n] = datetime(MakeDateTime(Event[ii][DATE],Event[ii][TIME]));
No, you don't need to change that. It's best to change this to use TimeLocal():
MQL4:
datetime tn=TimeCurrent();
I tried but getting error TextCreate: failed to create "Text" object! Error code = 4200
You are trying to create that object at price = 0. You need to give it the actual price. Text objects appear at some price level on the chart.
If i am keeping above value more than 800 (Mins), all the future news veritcle line getting disappeared. Can you check my code ones in your MT4, i can attach me full .mq4 file. Trying to fix this over a week still no solution :(
Please attach the .mq4 file that causes the lines to disappear at those settings.
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
No, you don't need to change that. It's best to change this to use TimeLocal():
I got now. You want me to keep eTime[ii][n] = datetime(MakeDateTime(Event[ii][DATE],Event[ii][TIME]))-TimeGMTOffset(); as it is and change datetime tn=TimeCurrent(); to datetime tn=TimeLocal();

You are trying to create that object at price = 0. You need to give it the actual price. Text objects appear at some price level on the chart.

Still same error USDJPY,H4: TextCreate: failed to create "Text" object! Error code = 4200

I tried like this

MQL4:
string currentSymbol = Symbol();
double newPrice_object = SymbolInfoDouble(currentSymbol, SYMBOL_BID) + 10000 * Point;
if(News_High_Line) {
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n],clrRed,STYLE_SOLID);
            TextCreate(0,"Text"+TimeToString(eTime[qi][n]),0,eTime[qi][n],newPrice_object,eTitle[i][n],clrRed);
            Print("Error text creating object: ", GetLastError()); }

Please attach the .mq4 file that causes the lines to disappear at those settings.
I am attaching my News filter full code, please check the attachment. I request you to please check !isNewsPause(_Symbol, 0), Text object with news title label at top of the verticle line, News disappread if values is more than 900 min and for common error.
 

Attachments

  • EarnForex - NewsFilter.ex4
    36.1 KB · Views: 4
  • EarnForex - NewsFilter.mq4
    19.6 KB · Views: 14

Enivid

Administrator
Staff member
Nov 30, 2008
19,168
1,494
144
Odesa
www.earnforex.com
Still same error USDJPY,H4: TextCreate: failed to create "Text" object! Error code = 4200
Error 4200 means that there is an existing object with that name. Make sure you are assigning a unique name for each such object.
double newPrice_object = SymbolInfoDouble(currentSymbol, SYMBOL_BID) + 10000 * Point;
This isn't a good idea. Your label might appear well outside the visible range of chart for some currency pairs. It's better to check for the screen's maximum price or something like that.

News disappread if values is more than 900 min and for common error.
As you can see, I set the values to 1500 and it shows the lines just fine:
lines.png
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
As you can see, I set the values to 1500 and it shows the lines just fine:
I mistakenly said News disappeared, I mean to say like 60% of news disappeared if value are above 900

Value Below 900 (Work perfectly) :

1705904620351.png

Value above 900 (Error) :

1705904709255.png

I request you to please check again with value 1500 like you did.

Error 4200 means that there is an existing object with that name. Make sure you are assigning a unique name for each such object.

I tried but similar error. You have the code, can you please add that?. I need like this, it should show news title name

1705904953929.png
 

Enivid

Administrator
Staff member
Nov 30, 2008
19,168
1,494
144
Odesa
www.earnforex.com
Value Below 900 (Work perfectly) :
OK, I've found the issue. The problem is that you are using the same function both to draw the lines and to check whether the news time is too close. In the latter case, the function exits the "checking cycle" by returning the value of 1, so the the cycle doesn't have a chance to finish to draw all the lines.

You have to separate these two features. You can either move the time checking to a completely separate function (I would probably choose this method) or put a separate cycle inside the same function just below the first one and move the time checks there, leaving the first cycle to drawing only.
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
You have to separate these two features.
Your Totally correct. Yesterday, i found this error too. I have finally fixed Line Draw and Trade Pause/Play (Before/After X min).

Now, the Only Error left with News filter is TextObject

I think you need to change "Text"+eTitle[i][n] to "Text"+eTitle[qi][n] when creating the text labels to make the object names unique.
Fixed but still same error TextCreate: failed to create "Text" object! Error code = 4200

MQL4:
double max_price = SymbolInfoDouble(Symbol(), SYMBOL_BID) + 2 * Point;
 
//+------------------------------------------------------------------+
//| Creating Text object                                             |
//+------------------------------------------------------------------+
bool TextCreate(const long              chart_ID=0,               // chart's ID
                const string            name="Text",              // object name
                const int               sub_window=0,             // subwindow index
                datetime                time=0,                   // anchor point time
                double                  price=0,                  // anchor point price
                const string            text="Text",              // the text itself
                const color             clr=clrRed,               // color
                const string            font="Arial",             // font
                const int               font_size=10,             // font size
                const double            angle=0.0,                // text slope
                const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_LOWER, // anchor type
                const bool              back=false,               // in the background
                const bool              selection=false,          // highlight to move
                const bool              hidden=true,              // hidden in the object list
                const long              z_order=0)                // priority for mouse click
  {
 
//--- reset the error value
   ResetLastError();
//--- create Text object
   if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price))
     {
      Print(__FUNCTION__,
            ": failed to create \"Text\" object! Error code = ",GetLastError());
      return(false);
     }
//--- set the text
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the object by mouse
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
   return(true);
  }

Than

MQL4:
if(news_High && (eImpact[qi][n]=="High"))
        {
 
            VLineCreate(0,"Tr_VLine"+TimeToString(eTime[qi][n]),0,eTime[qi][n]+(TimeCurrent()-TimeLocal()),clrRed,STYLE_SOLID);
            TextCreate(0,"Text"+TimeToString(eTime[qi][n]),0,eTime[qi][n]+(TimeCurrent()-TimeLocal()),max_price,eTitle[qi][n],clrRed);
            }
 

Enivid

Administrator
Staff member
Nov 30, 2008
19,168
1,494
144
Odesa
www.earnforex.com
I think it creates the objects correctly. The error message you see is produced because the function (UpcomingNewsImpact) is called repeatedly. You would be receiving the same error for vertical lines if you added an error message output there. You can check whether the text object is actually created and at what price it is to be found by pressing Ctrl+B and finding the text label there in the list.
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
You would be receiving the same error for vertical lines
yes, your correct. I am getting same error for Vertical line also.

The error message you see is produced because the function (UpcomingNewsImpact) is called repeatedly
It has to be called repeatedly to check News real time, so it will Pause or Active the trades.

You can check whether the text object is actually created
Text label is created and it showing perfectly. No issue with that.

-------------x---------------

Should i ignore Error code = 4200 or What is the solution to fix this error?
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
It's best just to check for object existence (inside TextCreate and VLineCreate functions) before proceeding to create it.
Like this

MQL4:
// Check if Text and VLine objects with the specified names do not exist
if (!ObjectCreate(0, "Tr_VLine" + TimeToString(eTime[qi][n]), OBJ_VLINE, 0, eTime[qi][n] + (TimeCurrent() - TimeLocal()), 0))
    && !ObjectCreate(0, "NFtext_M" + TimeToString(eTime[qi][n] - 2), OBJ_TEXT, 0, eTime[qi][n] + (TimeCurrent() - TimeLocal() - 60), max_price, eTitle[qi][n], clrOrange))
{
    // Objects do not exist, create them
    VLineCreate(0, "Tr_VLine" + TimeToString(eTime[qi][n]), 0, eTime[qi][n] + (TimeCurrent() - TimeLocal()), clrOrange, STYLE_SOLID);
    TextCreate(0, "NFtext_M" + TimeToString(eTime[qi][n] - 2), 0, eTime[qi][n] + (TimeCurrent() - TimeLocal() - 60), max_price, eTitle[qi][n], clrOrange);
}
else
{
    // Print a message if the objects already exist
    Print("The objects already existed");
}
 

Enivid

Administrator
Staff member
Nov 30, 2008
19,168
1,494
144
Odesa
www.earnforex.com
Like this

MQL4:
// Check if Text and VLine objects with the specified names do not exist
if (!ObjectCreate(0, "Tr_VLine" + TimeToString(eTime[qi][n]), OBJ_VLINE, 0, eTime[qi][n] + (TimeCurrent() - TimeLocal()), 0))
    && !ObjectCreate(0, "NFtext_M" + TimeToString(eTime[qi][n] - 2), OBJ_TEXT, 0, eTime[qi][n] + (TimeCurrent() - TimeLocal() - 60), max_price, eTitle[qi][n], clrOrange))
{
    // Objects do not exist, create them
    VLineCreate(0, "Tr_VLine" + TimeToString(eTime[qi][n]), 0, eTime[qi][n] + (TimeCurrent() - TimeLocal()), clrOrange, STYLE_SOLID);
    TextCreate(0, "NFtext_M" + TimeToString(eTime[qi][n] - 2), 0, eTime[qi][n] + (TimeCurrent() - TimeLocal() - 60), max_price, eTitle[qi][n], clrOrange);
}
else
{
    // Print a message if the objects already exist
    Print("The objects already existed");
}
No, you have to use the ObjectFind function.
 

shanmugapradeep

Active Trader
Dec 18, 2020
119
5
34
39
No, you have to use the ObjectFind function.
I modified based on ObjectFind. Is this correct?

MQL4:
// Check if Text and VLine objects with the specified names do not exist
if (ObjectFind(0, "Tr_VLine" + TimeToString(eTime[qi][n])) == -1
    && ObjectFind(0, "NFtext_M" + TimeToString(eTime[qi][n] - 2)) == -1)
{
    // Objects do not exist, create them
    VLineCreate(0, "Tr_VLine" + TimeToString(eTime[qi][n]), 0, eTime[qi][n] + (TimeCurrent() - TimeLocal()), clrOrange, STYLE_SOLID);
    TextCreate(0, "NFtext_M" + TimeToString(eTime[qi][n] - 2), 0, eTime[qi][n] + (TimeCurrent() - TimeLocal() - 60), max_price, eTitle[qi][n], clrOrange);
}
else
{
    // Print a message if the objects already exist
    Print("The objects already existed");
}