Trade Scheduler - restriction of the advisor's work. How to limit the trading time of Forex advisors? Mql4 advisor work on certain days
Achieving success in the forex market today is almost impossible to take into account the stable pattern of price behavior, which can be expressed in any of its actions.
One of these striking patterns, which is familiar to almost every trader, is manifested in the activity of the price at a certain time of the day.
Actually, this is why most of the advisors and trading strategies, today are endowed with a trading filter by time, when a trader prohibits trading on a strategy in an unfavorable time period.
Trade big only with a leading broker
However, the time factor can often be a signal pattern, and the trader needs to somehow implement it.
It is natural to constantly be at the monitor at a certain time with an accuracy of seconds in order to open a planned position is not always possible.
That is why traders use special scripts and advisors that allow them to open a position at a specified time for them. Actually, we will get acquainted with one of such advisors in this article.
OpenTime 2 Time Advisor is completely independent trade expert for the MT5 trading terminal, which allows you to implement strategies based on the patterns of price movement at a certain time of the day.
A notable feature of OpenTime 2 is the fact that the robot's functionality allows it to be made entirely independent expert and find patterns of price movement for a specific asset using optimization.
Thus, a trader can create strategies based on temporal patterns, and also use it as an assistant to implement their ideas, for example, to open deals during news releases (trading on expectations).
Installing the script on the chart.
The first version of the time advisor for the MT5 trading terminal was developed back in 2017, but the robot's functionality was so limited that it could be safely attributed to simple scripts rather than full-fledged robots.
However, after the expansion of the functionality in 2018, according to the recommendations of many traders, the robot not only gained popularity, but two versions of it were published in the official library of MT5 developers.
Thus, the advisor can be installed in two ways, namely through the library in your MT5, or through the data directory according to the standard scheme.
To install an advisor through the library, launch your MT5 trading terminal and move to the "Tools" panel, where information on your positions and balance is located.
Then go to the "Library" tab and perform the simplest sorting so that only advisors appear in the list.
After you sort the list, find the OpenTime 2 time advisor in it and load it using the additional menu as shown in the image below:
If installation in this way caused difficulties, go to the end of the article and download the robot's file, which you install according to the standard scheme.
To do this, you just need to drop the downloaded robot file into the directory of the MT5 terminal, namely, into the Experts folder.
Regardless of the installation method that you have chosen after installing the expert, you must restart trading terminal or update it in the Navigator panel, otherwise OpenTime 2 will not appear in the list of advisors.
Using the OpenTime 2 Time Advisor
As we noted at the very beginning of the article, the OpenTime 2 time advisor is an assistant that allows you to implement strategies based on the pattern of price movement at a certain time of the day.
The second version of the robot has become more autonomous and flexible, which allows you to more carefully customize the system for opening and tracking transactions.
So in the lines Use closing time interval and Closing time interval # 2 you can give permission for early closing of deals on the first and second time intervals, while the time for each of the closing intervals can be set in the lines Closing time interval 1,2.
The Trailing stop variable allows you to activate trailing stop, while the step of moving the stop is indicated in the Trailing step line.
In the Trade on Monday - Friday variables, you can prohibit trading on a specific day of the week, and in the Opening start time interval and Opening end time interval lines, you can set the time interval during which the position should be opened.
The variable Duration in seconds is responsible for the holding time of an open position, and in the Type of trade in time interval line, you can specify the direction of the trade, namely buy or sell.
The Volume transaction variable is responsible for the trading lot of the order being opened, and in the StopLoss time interval and TakeProfit time interval variables, you can specify the profit and stop order for your position.
In conclusion, it should be noted that the OpenTime 2 time advisor is a more advanced and autonomous assistant that allows you to implement strategies based on opening positions at a specific time of the day.
You've probably noticed that trades bring losses on certain days or even hours. For example, it can be deals on Friday night, the result of which, when carried over through the weekend, is often unpredictable. How to be? Manually enable and disable the advisor? It's not very convenient, and we are all human - you can just forget to do it.
Problem solving - auxiliary advisor Trade Scheduler that allows you to limit the working hours of other Expert Advisors according to the schedule set by the trader. For example, you can limit the trading of robots from 7 am to 11 am on Monday. This development is from our friends from ArgoLab and today we will get to know her in detail.
Analysis of statistics
Before limiting the work of an advisor, you must first determine at what time the strategy gives up weakness. To do this, you can use one of the monitoring services, such as myfxbook, which provides detailed trade statistics over time. For the analysis to be reliable, it is desirable to have trading statistics for at least three months.
So, first, you need to start monitoring on myfxbook. How to do this, on our website is ... Let's take the monitoring of an advisor as an example. Forex Hunter.
You can also download a report from the strategy tester to the site. This is primarily necessary for those who do not yet have a sufficient amount of accumulated history on a real account, but have a robot that can be tested in the tester. How to do this, again, read inseparate article .
Further, after the monitoring has been loaded and processed, go to the extended statistics section, to the “Daily” tab. The number of profitable and unprofitable transactions by days of the week. As you can see, on Thursday and Friday the largest relative number of losing trades is 73% and 74%, respectively. This means that the state of the market these days is not suitable for this strategy, the forecasts are less accurate and the EA is losing money. To improve efficiency automatic strategy it is reasonable to remove these days from the trade.
Then we look at the statistics by the hour. The arrows in the screenshot mark the hours with the largest number of losing trades. In addition to the fact that during the night period (mainly the Asian session) there are not only much fewer transactions than in the middle of the day, but the quality of entries is also poor.
This means that if we block the work of the advisor on Thursday and Friday, leaving it to work on the remaining days from 11 to 19 hours, the result is guaranteed to improve.
The EA settings for changes in this example will look like this:
Installation and configuration
The advisor is installed in a standard way. Open the terminal data directory via File - Open Data Directory, and go to the MQL4 - Experts directory. Here we copy the previously downloaded EA file with the extension “.ex4”. To make the advisor appear in the navigator window, restart the terminal.
In the settings, you need to specify the operating time according to the days of the week. There are three input parameters for each day. The first is responsible for enabling / disabling trading on a specific day, the second for the time of the start of trading, the third for the time of the end of the trade. Time can be specified to the nearest minute. The start time can be longer than the end time, for example, 7:00 pm and 9:00 am. In this case, trading will be allowed from 00:00 to 9:00 and from 19:00 to 24:00.
The additional parameter CloseBeforeSwitchOFF is responsible for closing all positions immediately before turning off auto trading. In total, the parameter can take three values: No - positions are not closed; CloseAllProfitable - only profitable ones are closed; CloseAll - exit from all open positions. The slip parameter is responsible for maximum slippage.
Do not forget to enable autotrading and import of functions from DLL libraries.
The time should be specified based on the terminal time, which is displayed in the header of the market watch window. This is your broker's time.
Also, do not try to install several instances of the advisor on one account - only one instance is enough. Otherwise, none of them will work correctly.
Conclusion
Limiting work by time is the easiest and effective method improve your trading performance. For example, if the advisor consistently merges from 4 to 8, then there is a different pattern on the market, which the robot is unable to process. Just not trading during this period - you increase the overall profitability and relieve the deposit from unnecessary transactions.
Forum thread
Best regards, Alexey Vergunov
TradeLikeaPro.ru
Source http://tradelikeapro.ru/sovetnik-tradescheduler/
If your trading system is not based on news races, it can be very useful for financial and mental health to stop the work of the advisor before the release of important news. And after the volatility settles, after a few hours, turn it on again. It's good if you have access to the work terminal at your fingertips. And if not? This is where the automation of such an activity comes in handy.
One of the options for solving our problem is to compile a file with a schedule of important events. Reading this file by our expert, and determining when to work and when not. An example of working with a csv text file is given in the MQL4 textbook, which we will take as a basis, along the way, getting rid of a couple of mistakes that the authors made inadvertently or in order to check our attentiveness (which they themselves warn about - you should not blindly believe anyone, there are mistakes always).
So, let's schedule important events for the next week in the following format:
Date and time of event; tool; event description
2016.04.01 14: 00; USD; ISM Manufacturing Business Activity Index 2016.04.01 14: 00; USD; ISM Inflation Gradual Index 2016.04.04 09:00; EUR; Producer Price Index (MoM) 2016.04. 04 09: 00; EUR; Producer Price Index (YoY) 2016.04.05 04:30; AUD; RB Australia Interest Rate Decision 2016.04.05 04:30; AUD; Reserve Bank of Australia Covering Statement 2016.04.06 07: 00; EUR; ECB meeting 2016.04.06 18: 00; USD; Minutes of the meeting of the Committee on open markets US Federal Reserve 2016.04.07 11:30; EUR; Information on ECB meeting on monetary policy
Let's write it to the ht-news.csv file and place it in the necessary directory \ MQL4 \ Files \ ht-news.csv, from where our EA can read it.
First, let's set external variables for customization, comments explain their purpose:
Extern string startNewsEvent = "Limit work on news"; input bool StopOnNewsEvent = true; // Enable constraint input string NewsEventFileName = "ht-news.csv"; // File with the schedule input uint LoadNewsEventTimerInDay = 7; // How often in days to reload the file input uint StopPriorEventHours = 2; // Stop X hours before the event input uint StartAfterEventHours = 3; // Run X hours after the event extern string stopNewsEvent = "----------------";
The following structure will help us access the description of the event being handled:
Struct NEWS_EVENT (datetime EventTime; // time of event occurrence string Instrument; // event instrument string EventComment; // event comment);
Custom function for reading information from a file
Bool LoadNews () (int handle; // File descriptor string instrument, // Name of the event currency firstInstrument, secondInstrument, // 1st and 2nd parts of the name of the current pair eventComment, // Event description text stringDateTime; // String expression of the date and time of the event datetime eventDateTime; // Date and time of the event in datetime format handle = FileOpen (NewsEventFileName, FILE_CSV | FILE_READ, ";"); // Opening a file if (handle<0) // Неудача при открытии файла { int lastError=GetLastError(); if(lastError==4103) // Если файла не существует, сообщим Alert("Нет файла с именем ",NewsEventFileName); else // При любой другой ошибке Alert("Ошибка при открытии файла ",NewsEventFileName," :",lastError); PlaySound("Bzrrr.wav"); // Громко ругнемся и вернем фалсе return false; } int cnt=0; while(FileIsEnding(handle)==false) { stringDateTime =FileReadString(handle);// Дата и время события instrument=FileReadString(handle); //Инструмент eventComment =FileReadString(handle);// Текст описания события, может не быть eventDateTime =StrToTime(stringDateTime); // Преобразование типа данных firstInstrument=StringSubstr(Symbol(),0,3);// Извлекаем первые 3 символа secondInstrument=StringSubstr(Symbol(),3,3);// Извлекаем вторые 3 символа if(StringCompare(instrument,firstInstrument,false)!=0 && StringCompare(instrument,secondInstrument,false)!=0) { continue; //не наши инструменты } cnt++; ArrayResize(NewsEvent,cnt,1000); //изменяем размер массива с запасом для ускорения ArrayResize(NewsEventTime,cnt,1000); NewsEvent.EventTime= eventDateTime; NewsEvent.Instrument=instrument; NewsEvent.EventComment=eventComment; NewsEventTime=eventDateTime; //удобнее искать в одномерном массиве } FileClose(handle); // Закрываем файл ArraySort(NewsEventTime,WHOLE_ARRAY,0,MODE_ASCEND); //сортируем массив для последующего поиска return true; }
We search for the required time in the NewsEventTime array, and if the time is found, we will get its description of their array of the NewsEvent structure
String GetEventInfo (datetime date) (for (int i = 0; i Helper function to determine if the current time falls into an idle interval // check if it is necessary to disable the advisor on news True - work False - rest bool CheckEnableNewsWork () (if (ArraySize (NewsEventTime) == 0) return true; // for some reason the array with the schedule turned out to be empty, so we are working // now you need to find the closest date in NewsEventTime before which you need to stop work for StopPriorEventHours hours datetime timeCurrent = TimeCurrent (); datetime timeStopWork = timeCurrent + StopPriorEventHours * 3600; // If there is a time in NewsEventTime less than timeStopWork, then stop working int dateindex = ArrayBsearch (NewsEventTime, timeStopWork, WHOLE_ARRAY, 0, MODE_ASCEND); datetime foundEventTime = NewsEventTime; timeStopWork = foundEventTime-StopPriorEventHours * 3600; // count the stop time from the found time; / now check if we are now timeCurrent between timeStopWork and timeStartWork. If yes, then we do not work if (timeCurrent> = timeS topWork && timeCurrent<=timeStartWork)
{
DrawLabel("EnableNewsWork","Не работаем, новость: "+GetEventInfo(foundEventTime)+"",5,80,Red);
return false;
}
else
{
DrawLabel("EnableNewsWork","Нормальная работа, новостей нет",5,80,Green);
return true;
}
}
To periodically read from a file with a schedule, we need a timer that starts, for example, once a week, as configured // Check for the presence of a file with news by timer void OnTimer () (if (StopOnNewsEvent) (LoadNews (); // read the file)) When initializing the advisor, you need to start the timer and read the news for the first time OnInit () .... if (StopOnNewsEvent) // If set, load the file with news (bool tm = EventSetTimer (LoadNewsEventTimerInDay * 86400); // start the timer to load the file with the schedule if (! Tm) Alert ("EventSetTimer error : ", GetLastError ()); OnTimer (); // First start immediately) At each tick, we check if we can open positions. By the way, this should not affect the trailing. OnTick () .... bool enableNewsWork = true; // you can work on news events if (StopOnNewsEvent) (enableNewsWork = CheckEnableNewsWork (); // If there is a news limit, check the time) if (HaveMoney && enableNewsWork) Traiding (Pairs); // check the conditions and open trade for the pair That's all. Unfortunately, I have not tested this code on a real account yet, as I wrote it on weekends, emulated ticks with a timer and changed the current time, which stops on weekends, manually. But next week I will see it in real life, in the new version of "Forex Grail 1.11", where I have embedded the above code. In the future, you may need to make a convenient utility for generating the ht-news.csv file, for example, in the same Today we will talk about the Trade Scheduler robot, which has a very interesting function. When using automated systems in Forex trading, have you noticed that on certain days of the week or hours they bring losses more often? For example, on the first day of the week, the EA opens very few trades, and most of them are also unprofitable. In such cases, it makes sense to disable the advisor before Saturday and enable it on Tuesday. You can perform this simple operation manually, but you can also easily forget to disable or enable the advisor at the right time. The solution to this problem (and a couple of others) can be using a robot Trade Scheduler, which does not trade itself, but allows you to limit the working hours of other advisors according to the schedule, based on the analysis of the work of these advisors. Before making adjustments to the temporary mode of operation, you need to find out at what moments he often trades in the red. In this case, the MyFXbook service will help you, which provides detailed statistics of the system's trading by days of the week and hours. The optimal trading period for analyzing the work of the system is 3 months. To carry out it, you need to start monitoring on the service. You can read about installing the robot on MyFXbook. As an example, let us consider the results of the work of an expert, the monitoring of which can be found by clicking on the picture: As an option for those who do not yet have a sufficient trading history of the robot for analysis on a real account, but at the same time it can be tested - then feel free to upload the report received from. After downloading and processing the monitoring, you need to go to the extended statistics section, the Daily tab. Here you can find information on the relative amount by day of the week. In our example, the largest number of unprofitable trades falls on Thursday and Friday, which means that it would be reasonable to suspend the EA on these days. The reason for this behavior may lie in the market state, which these days is not suitable for the robot's strategy, and its calculations are less accurate: After analyzing by day, you can analyze the effective work by the hour. To do this, go to the By hours tab and see when the relative number of losing trades is greater: Conclusion: it would be reasonable to stop the trading process on Thursday, Friday, and for the rest of the days, block its work in the first two hours of a new day, and during the day in those hours when unprofitable trades prevail - in particular, at 12, 13, 14 noon ... That is, leave him to work at night from 2 to 8 in the morning inclusive, and from 13 to 21 in the afternoon. The result of the advisor's work should improve significantly. Installation of the Trade Scheduler auxiliary advisor is carried out by analogy with any other advisor, for more details see. Using the link below you can download the archive with the expert: Download
trade-scheduler.rar (Downloads: 147) Unzip the trade-scheduler.rar archive, copy the TradeScheduler v2.3.ex4 EA file to the data_directory \ MQL4 \ Experts \ folder. To open the data directory, select the Open data directory item from the File menu. Then the terminal restarts and after that the advisor can be found in the Navigator - Advisors window. When an Expert Advisor is installed on the chart, in the settings window, the required working time is specified by days of the week and hours. The time is set depending on the time of the terminal, it is also the time. There are 3 input parameters for each day. The first parameter is responsible for enabling / disabling the robot on a specific day of the week, the second parameter is for the time of the start of trading, the third is the stop time. The time is indicated in the format hours: minutes: There is also an additional CloseBeforeSwitchOFF parameter in the settings. If the CloseAll value is set, all trades will be closed automatically before the robot is disconnected. If CloseAllProfitable - only profitable orders will be closed, if No - deals will not be closed. The Slip parameter is responsible for the maximum allowable slippage. Make sure that autotrading and import of functions from DLLs is allowed in the terminal. One version of the advisor is installed for one terminal. Want to improve performance your advisor? Try the method of limiting it to work and analyze the results. If the statistics show that your Expert Advisor is "steadily losing" at a certain time of the day, then there is a pattern on the market that it cannot handle. Suspend trading during this unfavorable period and increase its profitability!
Fig. 2. The ratio of profitable and unprofitable trades of the Transient Zones 2.0 Expert Advisor per week.
Fig. 3. The relative number of unprofitable and profitable trades per hour. Installing and configuring an expert.
Fig. 4. Input parameters set after the analysis of the advisor's work. Conclusion.