[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 426

 
ikatsko >>:

Здравствуйте! Как бы организовать в тестере стратегий оптимизацию (или тестирование) на промежутке времени, определенном не датами, а количеством последних баров? Попытка установки в советнике ограничителя времени работы, который определяется заданным количеством баров и основывается на TimeCurrent(), ничего не дала.


Хотя:

datetime TimeCurrent( )

Возвращает последнее известное время сервера (время прихода последней котировки) в виде количества секунд, прошедших после 00:00 1 января 1970 года.

Замечание: при тестировании последнее известное время сервера моделируется


Получается, что время, на котором работает оптимизатор, задается только в окне тестера фразой "Использовать дату:". Может кто знает какую-нибудь хитрость?

Do you mean to set the time of day trading?

If so

//begin
extern string     Торгуемый_диапазон  =  "В часах";
extern int        начало=8;
extern int        окончание=20;


//B start

if(Hour()>= начало&&Hour()< окончание)//если час больше или = 8, а так же если час меньше 20, торгуем
{
//условия
}
 
costy_ >>:

Вы имеете ввиду задавать время торгов внутри дня?

Если так то


I would like to optimise the parameters of an EA on short timeframes on a small period of time close to the current time. The Strategy Tester, on the other hand, allows you to set the date on which the optimization process starts and ends. When the TF is 15 minutes (for example), then in a day (and this is the minimum that allows the tester to set) there will be 96 bars. And I think it is a lot. I would like for this TF to be optimized on the last 2 hours, i.e. on 8 bars for example.


I have inserted such a fragment into the EA:

extern int History=100; //History in bars, on which the Expert Advisor works
StartDateTime=TimeCurrent()-History*Period()*60;
if(TimeCurrent()<StartDateTime) // Start time has not come
{
Alert("The start time has not come. EA didn't work.",": ",Symb,", ",Period());
return; // Exit start()

}

I expected that the EA in the strategy tester will not work before StartDateTime. But no!

 
ikatsko >>:

Я хотел бы оптимизировать параметры советника на коротких таймфреймах на малом промежутке времени поближе к текущему времени. Тестер же стратегий позволяет установить дату на которой начинается и на которой заканчивается процесс оптимизации. Когда же ТФ равен 15 минутам (например), то в сутках (а это минимум который позволяет установить тестер) будет 96 баров. А это по моему много. Хотелось бы для этого ТФ пооптимизировать на последних 2-х часах т.е. на 8-ми например барах.

//begin
extern string     Торгуемый_диапазон  =  "В часах";
extern int        начало=22;
extern int        окончание=0;


//B start

if(Hour()>= начало&&Hour()< окончание)//на интервале  меж 22:00 - 00:00
{
//условия
}

int Hour( )
Returns current hour (0,1,2,...23) of the last known server time at program start (this value does not change during program execution).

Note: when testing, the last known server time is simulated.


The tester supports M1 TF, don't tie it to bars, tie it to time, maybe you need that too.

 
costy_ >>:

int Hour( )
Возвращает текущий час (0,1,2,..23) последнего известного серверного времени на момент старта программы (в процессе выполнения программы это значение не меняется).

Замечание: при тестировании последнее известное время сервера моделируется.


Тестер поддерживает ТФ М1, не привязывайтесь к барам, привязывайтесь ко времени, возможно это тоже нужно.

The phrase: when testing, the last known server time is simulated is present and in TimeCurrent( ) however it doesn't work. Your variant is good, but we have to check if it works? Secondly, when changing TF it is necessary to change a piece of code or must recognize in which TF it works, to adequately perceive numbers "start" and "end". Thirdly, I think it is much more convenient to set the baro number backward - there is no need to calculate the "beginning" manually. In MQL we deal with bars! And the last thing: what is the disadvantage of this code? (Except that it does not work in the strategy tester. And that is my question)

 
costy_ >>:

int Hour( )
Возвращает текущий час (0,1,2,..23) последнего известного серверного времени на момент старта программы (в процессе выполнения программы это значение не меняется).

Замечание: при тестировании последнее известное время сервера моделируется.


Тестер поддерживает ТФ М1, не привязывайтесь к барам, привязывайтесь ко времени, возможно это тоже нужно.

extern int History=100; //История в барах, на которой работает советник
StartDateTime=TimeCurrent()- History*Period()*60;//...=datetime - int*int*int (допустим 1265996665 - 100 * 15 * 60 это не есть интересующее время)

Alert("TimeCurrent()    "+TimeCurrent()+" < StartDateTime    "+ StartDateTime);//...проверим соотношение datetime 

if(TimeCurrent()< StartDateTime) // Время старта не наступило...
{
Alert("Время старта не наступило. Эксперт не работает.",": ", Symb,", ",Period());
return; // Выход из start()

} 
 
costy_ >>:

Sort of like:

datetime is date and time, an unsigned integer containing the number of seconds elapsed since 0 hours on 1 January 1970.

и

Data of types color and datetime are represented as integers. Integer types, together with floating-point types, are called arithmetic (numeric) types.

If not, how to get out of it.

Thanks for the tip about the number format, though. There is a direction of search. If still there is a ready solution will be grateful

 

Actually, it's better to use Time[0] instead of TimeCurrent() in the tester, it seemed to me that TimeCurrent() worked in the tester before...

and now TimeCurrent() in the tester (or not in the tester) will most likely give the time when the last quote came...


in this case it will work out

extern int History=100; // History in bars, on which the Expert Advisor works
StartDateTime=Time[History];
if(Time[0] < StartDateTime) // Start time has not come
{
Alert("Start time has not come. EA not working.",": ",Symb,", ",Period());
return; // Exit start()
}

 
ikatsko >>:

Вроде как:

datetime - дата и время, беззнаковое целое число, содержащее количество секунд, прошедших с 0 часов 1 января 1970 года.

и

Данные типов color и datetime представляются в виде целых чисел. Целые типы вместе с типами с плавающей точкой называются арифметическими (числовыми) типами.

А если нет, то как выйти из этого положения.

Хотя, спасибо за подсказку на счет формата чисел. Есть направление поиска. Если всеже есть готовое решение буду благодарен

Well, in the previous comment, the error was displayed via the alert.

The help says "Note: when testing, the last known server time is simulated." but if it's not simulated all questions to the help editor.

You checked, you found the error...

Only you know the solution, as we do not know the further direction of logic.

I do not understand just why there is so much text

StartDateTime=TimeCurrent()-History*Period()*60;

when everything can be done much easier?

 
costy_ >>:

Готовое решение знаете только Вы, так как дальнейшее направление логики нам не известно.

I agree completely with your solution in the previous answer: it is a data format incompatibility! The request for an off-the-shelf solution comes down to solving the issue of format conversion. But obviously MQL4 has no such options. For example, today is the 43rd day of the year, i.e. the 43rd bar in the daily timeframe from the beginning of the year. Suppose I want to optimize my Expert Advisor on 60 bars. It means that the tester should start working with 365-(60-43)=348th day (bar) of the previous year. I.e. we should take TimeDayOfYear(TimeCurrent()) (it's an int!) and compare it to 348. Obviously we have to take into account the value of the year (last year) as well. All in all, I think I've got it. We just have to implement it. It will be much more difficult on small TFs, when one has to test a large number of bars, which (for example, 5-minutes) will go beyond the previous hour, or maybe the previous day.

 

Your whole problem is in the problem statement, make it clear to others... I honestly did not understand what time you need to test from...

If you need to start with a 60 bar, start with 60 bars.

int startTime = iTime(NULL,PERIOD_D1, N); // N - number of the bar from the current moment on the daily timeframe

Reason: