SuhanovDM94 #: Good day to all. Could you please advise whether Sleep() is executed in the Expert Advisor testing mode (testing on real ticks, of course)?
In progress - the Tester time is changed by an appropriate amount.
Wizard #: Is it possible to find the size of the very tick in mql5, after which a position was opened?
It turns out that you can. The for loop is inserted in a separate function, in the OnTick() function or at your own discretion. I am interested in the opinion of others. For example, I need it to create an ultra-precise system. Therefore, I'm writing without libraries, including functions for opening and closing positions. Whoever says what, mqh libraries slow down the work, for example compilation takes 1.5 times longer. It's better to write everything in one file. The style, OOP or procedural, does not matter. MQL5 will never become a language on the level of C++, it is limited. The point is in libraries.
#define EXPERT_MAGIC 261// MagicNumber экспертаinputstring Symbol_T = "XAUUSD"; // глобальная переменная для задаваемого символа
..............
for(int i = PositionsTotal()-1; i >= 0; i--)
{
if(PositionGetTicket(i) > 0 && PositionGetString(POSITION_SYMBOL) == Symbol_T && PositionGetInteger(POSITION_MAGIC) == EXPERT_MAGIC)
{
int attempts = 0; // счетчик попытокbool success = false; // флаг успешного выполнения копирования тиковMqlTick tick_array[]; // массив для приема тиков//--- сделаем 3 попытки получить тикиwhile(attempts < 3)
{
//--- замерим время старта перед получением тиковuint start = GetTickCount();
//--- дата, по которую запрашиваются тики (время открытия позиции)datetime Time_Open = (datetime)PositionGetInteger(POSITION_TIME);
//--- дата, с которой запрашиваются тики (достаточно взять на 30 секунд раньше открытия позиции)datetime Time_Start = (datetime)(Time_Open-30);
//--- запросим тиковую историю с момента Time_Start до момента Time_Openint received = CopyTicksRange(Symbol_T, tick_array, COPY_TICKS_ALL, Time_Start*1000, Time_Open*1000);
if(received != -1)
{
//--- выведем информацию о количестве тиков и затраченном времениPrintFormat("%s: received %d ticks in %d ms", Symbol_T, received, GetTickCount()-start);
//--- если тиковая история синхронизирована, то код ошибки равен нулюif(GetLastError()==0)
{
success = true;
break;
}
elsePrintFormat("%s: Ticks are not synchronized yet, %d ticks received for %d ms. Error=%d", Symbol_T, received, GetTickCount()-start, _LastError);
}
//--- считаем попытки
attempts++;
//--- пауза в 1 секунду в ожидании завершения синхронизации тиковой базыSleep(1000);
}
//--- не удалось получить запрошенные тики от самого начала истории с трех попыток if(!success)
{
PrintFormat("Ошибка! Не удалось получить %d тиков по %s с трех попыток", Symbol_T);
//return; (вставить, если цикл находится внутри функции типа void)
}
//--- узнаем количесто элементов в массивеint ticks = ArraySize(tick_array);
//--- выведем bid последнего тика в массиве перед самым открытием позицииdouble last_bid_before_priceopen = tick_array[ticks-1].bid;
Print("BID последнего тика: ", tick_array[ticks-1].bid);
//--- выведем ask последнего тика в массиве перед самым открытием позицииdouble last_ask_before_priceopen = tick_array[ticks-1].ask;
Print("ASK последнего тика: ", tick_array[ticks-1].ask);
//--- узнаем цену, по которой была открыта позицияdouble Position_PriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);
if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
//--- вычислим размер последнего тика, на котором была открыта позиция (для BUY позиции открытие было по цене ASK)double size_last_tick_ASK = NormalizeDouble(fabs(Position_PriceOpen - last_ask_before_priceopen), _Digits);
}
elseif((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
//--- вычислим размер последнего тика, на котором была открыта позиция (для SELL позиции открытие было по цене BID)double size_last_tick_BID = NormalizeDouble(fabs(last_bid_before_priceopen - Position_PriceOpen), _Digits);
}
}
}
I'm sick of this bug - there is an indicator, there is an expert working on it. I change the indicator and recompile it. The indicator changes can be clearly seen on the chart - the Expert Advisor is run in the tester - but it is as if it didn't change anything. The same result.
If I restart the terminal and pass the tester after that it will generate a new code.
What is this hack, I do not understand.
I removed indicator ex5. Tester continues to run as if nothing has happened. Where does it get the file to run????
But now indicator buffer IndBuff[i] is doing the brains, array out of range. What does it need? Why it does not allocate to initial i=limit ?
//Проверка и расчёт количества просчитываемых баровint limit = rates_total-prev_calculated;
if(limit==1)
limit=2;
//-------------------------------------------------------------------------//Расчёт индикатораfor(int i=limit-1; i>=0; i--)
{
c = iClose(_Symbol,PERIOD_CURRENT,i);
IndBuff[i] = c; //на этой строке array out of range
}
That's because IndBuff is not allocated to rates_total + 1 And ArrayResize is not applicable to it. They broke the for construct. Now we have to use if-arses to do everything?
//+------------------------------------------------------------------+//| Custom indicator iteration function |//+------------------------------------------------------------------+intOnCalculate (constint rates_total,
constint prev_calculated,
constint begin,
constdouble& price[])
{
ArraySetAsSeries(IndBuff, true);
//-------------------------------------------------------------------------//Проверка и расчёт количества просчитываемых баровint limit = rates_total-prev_calculated;
if(limit > 1)
{
Print(rates_total,": rates_total");
Print(limit,": limit");
Print(ArraySize(IndBuff),": IndBuff");
}
//-------------------------------------------------------------------------//Расчёт индикатораfor(int i=limit; i>=0; i--)
{
c = iClose(_Symbol,PERIOD_CURRENT,i);
IndBuff[i] = c; //array out of range
}
return(rates_total);
}
100686: rates_total
100686: limit
100686: IndBuff
array out of range in 'Simple.mq5' (82,15)
Good day to all. Could you please advise whether Sleep() is executed in the Expert Advisor testing mode (testing on real ticks, of course)?
In progress - the Tester time is changed by an appropriate amount.
Executed - the Tester time is changed by an appropriate amount.
Thank you very much!
Is it possible to find the size of the very tick in mql5, after which a position was opened?
It turns out that you can. The for loop is inserted in a separate function, in the OnTick() function or at your own discretion. I am interested in the opinion of others. For example, I need it to create an ultra-precise system. Therefore, I'm writing without libraries, including functions for opening and closing positions. Whoever says what, mqh libraries slow down the work, for example compilation takes 1.5 times longer. It's better to write everything in one file. The style, OOP or procedural, does not matter. MQL5 will never become a language on the level of C++, it is limited. The point is in libraries.
I'm sick of this bug - there is an indicator, there is an expert working on it. I change the indicator and recompile it. The indicator changes can be clearly seen on the chart - the Expert Advisor is run in the tester - but it is as if it didn't change anything. The same result.
If I restart the terminal and pass the tester after that it will generate a new code.
What is this hack, I do not understand.
I removed indicator ex5. Tester continues to run as if nothing has happened. Where does it get the file to run????
3184
Strange behaviour in the indicator.
The for loop goes into the body, not on every tick, but only once on a new candle.
But i == 0 and the given condition allows i>=0
on the tick on the same bar limit = 0
so the first value of i = -1 and condition i>=0
that is why it does not go into the loop.
at the tick on the same bar limit = 0
so the first value i = -1 and the condition i>=0
that's why it doesn't go into the loop.
Thanks, I missed the one.
But now indicator buffer IndBuff[i] is doing its head in, array out of range.
What does it need? Why doesn't it allocate to initial i=limit ?
Thanks, missed the one.
But now indicator buffer IndBuff[i] is doing the brains, array out of range.
What does it need? Why it does not allocate to initial i=limit ?
So on every bar it goes into a loop, while it needs to go into a loop on every tick.
It used to work like this
for the ticks i>=0,
for bars i>0
Now I do not know how to work with the buffer.
That's because IndBuff is not allocated to rates_total + 1
And ArrayResize is not applicable to it.
They broke the for construct. Now we have to use if-arses to do everything?