The work of the advisor in a given time interval. How to limit the trading time of Forex advisors? Pending orders expert
You've probably noticed that trades on certain days or even hours bring losses. For example, these could be transactions on Friday evening, the result of which, when transferred over the weekend, is often unpredictable. What should I do? Manually enable and disable the advisor? This is not very convenient, and we are all human - you can simply forget to do it.
Solving the problem - auxiliary advisor Trade Scheduler, which allows you to limit the work time of other experts according to the schedule set by the trader. For example, you can limit robot trading from 7 to 11 a.m. on Monday. This development comes from our friends from ArgoLab and today we will get to know it in detail.
Statistics analysis
Before limiting the work of the advisor, you must first determine at what time the strategy becomes weak. To do this, you can use one of the monitoring services, such as myfxbook, which provides detailed trading statistics over time. For the analysis to be reliable, it is advisable to have trading statistics for at least three months.
So, first, you need to start monitoring on myfxbook. There is information on how to do this on our website. . Let's take advisor monitoring 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 a tester. How to do this, again, read inseparate article .
Next, after the monitoring has been downloaded and processed, go to the advanced statistics section, to the “Daily” tab. The number of profitable and losing trades by day 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 market conditions these days are not suitable for this strategy, the forecasts are less accurate and the advisor is losing money. To improve the effectiveness of the automatic strategy, it is wise to remove these days from trading.
Then we look at the statistics by hour. The arrows in the screenshot mark the hours with the largest number losing trades. In addition, 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 also leaves much to be desired.
This means that if we block the adviser’s work on Thursday and Friday, leaving it to work on other days from 11 to 19 hours, the result is guaranteed to improve.
The advisor settings for changes in the above example will look like this:
Installation and configuration
The advisor is installed in the 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”. For the advisor to 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 certain day, the second - for the start time of trading, the third - the end time of trading. The time can be specified to the nearest minute. The start time may be greater than the end time, for example, 19:00 and 9:00. 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 slip.
Don't forget to enable auto trading and import of functions from DLLs.
The time must be specified based on the terminal time, which is displayed in the header of the market review window. This is also 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 simplest and effective way improve your trading performance. For example, if the advisor consistently loses from 4 to 8, then there is another pattern in the market that the robot is not able to process. By simply not trading during this period, you increase your overall profitability and relieve your deposit from unnecessary transactions.
Forum thread
Best regards, Alexey Vergunov
TradeLikeaPro.ru
Source http://tradelikeapro.ru/sovetnik-tradescheduler/
Achieving success in the Forex market today is almost impossible to take into account a 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 price activity at a certain time of day.
In fact, this is why most advisors and trading strategies, today are equipped with a time trading filter, when the trader prohibits trading on the 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.
Naturally, it is not always possible to constantly be at the monitor at a certain time with an accuracy of seconds in order to open a planned position.
That is why traders use special scripts and advisors that allow them to open a position at a specified time. In fact, we will get acquainted with one of such advisors in this article.
Time Advisor OpenTime 2 is a completely independent trading expert for the MT5 trading terminal, which allows you to implement strategies based on the pattern of price movement at a certain time of day.
A notable feature of OpenTime 2 is the fact that the robot’s functionality allows it to become a completely independent expert and find patterns of price movement on a certain asset using optimization.
Thus, a trader can create strategies based on time patterns, and also use it as an assistant to implement his ideas, for example, to open transactions during news releases (trading on expectations).
Installing a script on a chart.
The first version of the time advisor for the MT5 trading terminal was developed back in 2017, but the functionality of the robot was so limited that it could easily be classified as simple scripts rather than full-fledged robots.
However, after expanding the functionality in 2018, following the recommendations of many traders, the robot not only gained popularity, but two of its versions 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 for standard scheme.
To install the 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 do a simple sorting so that only advisors appear in the list.
After you sort the list, find the OpenTime 2 time advisor in it and download it using the additional menu as shown in the image below:
If installing this way caused difficulties, go to the end of the article and download the robot file, which you will install according to the standard scheme.
To do this, you just need to drop the downloaded robot file into the MT5 terminal directory, namely into the Experts folder.
Regardless of the installation method you chose, 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 already 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 day.
The second version of the robot has become more autonomous and flexible, which allows you to more carefully configure the system for opening and maintaining transactions.
So in the lines Use closing time interval and Closing time interval #2 you can give permission to early closure transactions in 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, and 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 period during which the position should be opened.
The Duration in seconds variable is responsible for the time the open position is held, and in the Type of trade in time interval line you can specify the direction of the transaction, 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 is worth noting 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 certain time of day.
From the article you will learn:
Good afternoon, dear readers and guests of the blog. Today we will talk about how there are auxiliary advisors that place time-based and pending orders, as well as how transactions are closed.
Best broker
An advisor that opens orders every hour or by time is a tool that helps in various trading situations. In general, as far as I can tell, interest in such advisors who perform similar actions has existed for a long time. And in 2006 there were such robots, and in 2008, based on requests, you can track interest in them, and now requests to produce such experts continue to appear. At the same time, often experienced traders, and not just traders, but those who are engaged in trading, help newcomers. Overall, this is a good tradition. It is usually based on mutual exchange. The newbie provides ideas, and the experienced gets the right to use the idea and creates expert code that he shares with his partner.
When conditions arise for using these experts
However, let's get to the point! My story today is a story about an expert for placing orders at the right time. It is used for a variety of purposes. For example, there are trading systems that are strictly tied to the start of a candle or session. For example, there is and, according to my modest research, a certain semblance of such waves exists in reality, but they appear on different timeframes, and there are periods of different durations. You can, for example, find them on USDCAD on Mn.
There are candles that are very similar to each other every month. In January, for example, for example, for six years there has been an upward trend or a downward trend, that’s not the point. In order to receive income from using this approach, you need to place an order in a direction determined by the research method at the beginning of the month and delete it at the end, and do this only in certain months of the year. This is precisely why the expert places orders by date, hour and minute.
An expert who gives orders at the right time also implements other tasks, for example, it is known that tomorrow there will be a trend in the market and the trading idea stipulates that you need to take positions on each hourly candle in the direction of the trend. And you need to cancel orders at the end of the trading day.
Thus, orders will appear in the form of such a grid. You can see how this is done differently on the page where. By the end of the working day, buy-, sellstop or market orders are deleted, also at the right moment.
Why is this so? Because I have seen this approach in the following modification: placing orders on each candle with a market order or also on each candle, but with buy and sell stops in opposite directions. In the second case, you may not even know in which direction the market will move, but simply catch the movement, as if using a butterfly net. Also, when placing buy and sell stop orders in both directions, perhaps until the end of the day one of them will not open and will remain hanging.
Download
So, it becomes clear that today there are three types of auxiliary experts in this context.
- The first type is an expert placing orders on the market, taking into account certain hours and minutes,
- The second type is an expert of pending orders by hours and minutes.
- The third type can be implemented within the first two or be separate program. This is exactly the case in our example.
Market order expert
When you know that the uptrend will start at 23:50, so the price will definitely pass 60 pips, with a stop loss of 30 pips, and you have an expert who will trail the stop loss, so you will need an order. At the same time, you will not be far away, so the sound notifying the opening will come in handy. Under such conditions, you will need the first type of expert. In this case, this is the e-OpenByTime expert. This expert, which can be downloaded using social buttons, has the following parameters:
- TimeTrade – here you set the exact moment when the order should be opened. Data format hh:mm.
- Duration – the period in seconds during which the expert will attempt to place an order.
- Sell – here you need to specify the order type true – this means that an order will be opened on the market to sell the asset. The value false corresponds to a buy order.
- Lots – this option will limit your trading lot to a specified value.
- SopLoss – stop loss is designed for four-digit brokers, so in order to determine its size at 30 points you need to set the value to 300
- TakeProfit – it’s the same story with take profit.
- MagicNumber – I think everything is clear here.
- UseSound – next are the sound settings.
- NameFileSound – here we select a sound file.
- Of the remaining settings, only MaketWatch may raise questions. It turns out that this setting is needed to ensure that trade requests are sent according to the Market Watch rules that some brokers require.
Pending orders expert
The second type of experts who work on opening pending orders are experts for various box trading systems. Similar
This time, I will describe an expert, so to speak, an auxiliary one, which will, without regard to trends and other signs of the chart, open two buy-, sellstop trades in both directions.
We are talking about the 37_Exp-TimeOpenBuy expert. Setup is quite simple.
- BuyStopOpen and SellStopOpen - both in this case are defined as true.
- Distance – determines at what distance from the current price these orders will be placed. Please note that the value here and in the next line is calculated for a four-digit broker, so to set the distance you need to use a number, for example, 30 points and add another 0 at the end.
- TPBuyStop, SLBuyStop, TPSellStop, SLSellStop – allow you to determine the distance to take profit and stop loss for each order. (Here we also add a zero to the number at the end.)
- CloseAfterOpen – allows you to delete a deal that remains after one of the buy and sellstop orders has been triggered.
- Slippage is a setting that in my experience must be set to any value other than zero in order for orders to be placed. This is the maximum slip value.
- CloseIfNotOpen – was conceived as a function that deletes all failed buy and sell stops at a new time. However, no matter how hard I tried to use this operation, nothing came of it.
- The remaining options are needed in order to determine the moment of entry into the market and exit from it.
Expert remover of deposits
Finally, the third advisor, which, using the mql4 code I compiled, performs the removal of buy-, in time, more precisely than all of them. In general, now you will have a full set of advisors for placing buy-, sellstop orders and on the market and an expert who will close orders on time. To do this, before the cycle, which simply closes buy-, sellstop orders in fact, or it would be more correct to say: deletes them, you need to perform a check if (TimeCurrent()>=BlackTime). In this case, the variable is assigned the time after which orders are deleted.
Conclusions
Today we got acquainted with a very useful set of auxiliary advisors that can be used in different market conditions. To use them, you will need a quick setup and some kind of market forecast. As a result of their use, you will be able to organize completely independent and almost completely automatic entries and exits. I would even say that everything will happen automatically, but only within the framework of a couple of actions, then the settings of the experts will have to be changed. However, this is already a good help for those who do not have time to sit in front of a monitor without restrictions. That's all, dear friends. I hope you found this page interesting.
(2 ratings, average: 5,00 out of 5)If your trading system is not based on news races, it can be very useful for financial and mental health to stop the adviser’s work before the release of important news. And after the volatility settles down, after a few hours, turn it on again. It's good if you have access to a working terminal at hand. What if not? This is where automation of such activities 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 you can work and when not. The MQL4 textbook provides an example of working with a CSV text file, and we will take it as a basis, simultaneously getting rid of a couple of mistakes that the authors made unintentionally or in order to test our attentiveness (which they themselves warn about - we should not blindly trust anyone, mistakes happen Always).
So, let's make a schedule of important events for next week in the following format:
Event date and time; instrument; event description
2016.04.01 14:00;USD;ISM business activity index in the manufacturing sector 2016.04.01 14:00;USD;Index of gradual acceleration of inflation from ISM 2016.04.04 09:00;EUR;Producer price index (m/m) 2016.04. 04 09:00;EUR;Producer Price Index (YoY) 2016.04.05 04:30;AUD;Decision of the Reserve Bank of Australia on the interest rate 2016.04.05 04:30;AUD;Accompanying statement of the Reserve Bank of Australia 2016.04.06 07: 00;EUR;ECB meeting 2016.04.06 18:00;USD;Minutes of the meeting of the US Federal Open Market Committee 2016.04.07 11:30;EUR;Information on the ECB meeting on monetary policy
Let's write it to the file ht-news.csv and place it in the required directory \MQL4\Files\ht-news.csv, from where our advisor can read it.
First, let's set external variables for configuration; comments explain their purpose:
Extern string startNewsEvent="Restriction of work on news"; input bool StopOnNewsEvent=true; //Enable the restriction input string NewsEventFileName="ht-news.csv"; //File with 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; //Start X hours after the event extern string stopNewsEvent="----------------";
The following structure will help us access the description of the event being processed:
Struct NEWS_EVENT (datetime EventTime; //event time string Instrument; //event instrument string EventComment; //event comment);
Custom function to read 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, // Text of the event description 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 get its description of their NewsEvent structure array
String GetEventInfo(datetime date) ( for(int i=0;i Helper function to determine if the current time falls within idle time //check if we need to disable the news advisor True - work False - rest bool CheckEnableNewsWork() ( if (ArraySize(NewsEventTime)==0) return true; //for some reason the array with the schedule was empty, which means we are working //now we need to find the nearest date in NewsEventTime before which we need to stop work for StopPriorEventHours hours datetime timeCurrent =TimeCurrent(); datetime timeStopWork=timeCurrent+StopPriorEventHours*3600; //If there is a time in NewsEventTime that is less than timeStopWork, then we stop working int dateindex= ArrayBsearch(NewsEventTime,timeStopWork,WHOLE_ARRAY,0,MODE_ASCEND); datetime foundEventTime=NewsEventTime; timeStopWork=foundEventTime-StopPriorEventHours*3600; //calculate the stop time from the found time datetime timeStartWork=foundEventTime+StartAfterEventHours*3600; /now let's check if we are now timeCurrent between timeStopWork and timeStartWork. If yes, then we are not working if (timeCurrent>=timeStopWork && 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 runs, for example, once a week, as configured //Check for the presence of a news file using the 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 the news ( bool tm=EventSetTimer(LoadNewsEventTimerInDay*86400); //start the timer to load the file with the schedule if (!tm) Alert("EventSetTimer error :",GetLastError()); OnTimer();//First launch immediately ) At each tick we check whether we can open positions. By the way, this should not affect 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 conditions and open trade on a pair That's all. Unfortunately, I haven’t tested this code on a real account yet, since I wrote it on the weekend, emulated the ticks with a timer, and changed the current time, which stops on the weekend, manually. But next week I’ll look in real life, in the new version “Forex Grail 1.11”, where I 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 This advisor is ideal for those who trade by levels and any strategies that use pending limit orders. The advisor will place orders at the right time at the right distance from the current price! In the robot settings, you can set stop losses, take profits of orders, as well as the lot of each order. Everything is set for each order separately. You can place only a buy limit, or a sell limit, or both orders together! The advisor is ready to work on any trading instrument, in any Metatrader 4 trading terminal. The robot is also ready to work on several currency pairs at once. That is, you can open any number of pairs and install an advisor on them, giving each one its own magic number and time settings. After which, each couple will work strictly individually. If you still work with limit orders manually, this robot is for you!