It will always find an order with zero number (which is i-1). This is some wild method of determining the "next" order, which is truly misleading...
If there are no orders then by this design:
for(int i=1; i<=OrdersTotal(); i++) // Цикл перебора ордер
{
if (OrderSelect(i-1,SELECT_BY_POS)==true) // Если есть следующий
{
if (OrderSymbol()!= Symb) continue;
it will not go to the next condition.
because there is no order and-1 (in our case =0)
Of course, it is not convenient to write it this way and it is not clear why it should be this way,
and not, for example, in this way:
for(int i=0; i<OrdersTotal(); i++) // Цикл перебора ордер
{
if (OrderSelect(i,SELECT_BY_POS)==true) // Если есть следующий
{
if (OrderSymbol()!= Symb) continue;
Hello Mr. programmers, I have a question, I can not learn a part of the code to close the percentage of the account balance. it closes not the percentage but all at once and all orders that are in the market. I need that would close a specific order and the calculated percentage of the balance of the deposit.advise what I do wrong?
Of course, it is not convenient to write it this way and it is not clear why it should be this way,
and not, for example, like this:
When I was reading it, I also thought why not just put i=0, it seems to be simpler and clearer.
Here is the entire script code, maybe there is a good reason why the author put i=1 instead of i=0. I just don't know enough about it and may simply not see it, while I need to understand the mechanism of functioning in order not to raise questions later
// closeorder.mq4// Предназначен для использования в качестве примера в учебнике MQL4.//--------------------------------------------------------------- 1 --int start() // Спец.функция start
{
string Symb=Symbol(); // Финанс. инструментdouble Dist=1000000.0; // Предустановкаint Real_Order=-1; // Пока рыночных нетdouble Win_Price=WindowPriceOnDropped(); // Здесь брошен скрипт//--------------------------------------------------------------- 2 --for(int i=1; i<=OrdersTotal(); i++) // Цикл перебора ордер
{
if (OrderSelect(i-1,SELECT_BY_POS)==true) // Если есть следующий
{ // Анализ ордеров://------------------------------------------------------ 3 --if (OrderSymbol()!= Symb) continue; // Не наш фин.инструм.int Tip=OrderType(); // Тип ордераif (Tip>1) continue; // Отложенный ордер //------------------------------------------------------ 4 --double Price=OrderOpenPrice(); // Цена ордераif (NormalizeDouble(MathAbs(Price-Win_Price),Digits)< //ВыборNormalizeDouble(Dist,Digits)) // самого близкого орд
{
Dist=MathAbs(Price-Win_Price); // Новое значение
Real_Order=Tip; // Есть рыночный ордерint Ticket=OrderTicket(); // Номер ордераdouble Lot=OrderLots(); // Количество лотов
}
//------------------------------------------------------ 5 --
} //Конец анализа ордера
} //Конец перебора орд.//--------------------------------------------------------------- 6 --while(true) // Цикл закрытия орд.
{
if (Real_Order==-1) // Если рыночных нет
{
Alert("По ",Symb," рыночных ордеров нет");
break; // Выход из цикла закр
}
//--------------------------------------------------------- 7 --switch(Real_Order) // По типу ордера
{
case0: double Price_Cls=Bid; // Ордер Buystring Text="Buy "; // Текст для Buybreak; // Из switchcase1: Price_Cls=Ask; // Ордер Sell
Text="Sell "; // Текст для Sell
}
Alert("Попытка закрыть ",Text," ",Ticket,". Ожидание ответа..");
bool Ans=OrderClose(Ticket,Lot,Price_Cls,2);// Закрытие ордера//--------------------------------------------------------- 8 --if (Ans==true) // Получилось :)
{
Alert ("Закрыт ордер ",Text," ",Ticket);
break; // Выход из цикла закр
}
//--------------------------------------------------------- 9 --int Error=GetLastError(); // Не получилось :(switch(Error) // Преодолимые ошибки
{
case135:Alert("Цена изменилась. Пробуем ещё раз..");
RefreshRates(); // Обновим данныеcontinue; // На след. итерациюcase136:Alert("Нет цен. Ждём новый тик..");
while(RefreshRates()==false) // До нового тикаSleep(1); // Задержка в циклеcontinue; // На след. итерациюcase146:Alert("Подсистема торговли занята. Пробуем ещё..");
Sleep(500); // Простое решениеRefreshRates(); // Обновим данныеcontinue; // На след. итерацию
}
switch(Error) // Критические ошибки
{
case2 : Alert("Общая ошибка.");
break; // Выход из switchcase5 : Alert("Старая версия клиентского терминала.");
break; // Выход из switchcase64: Alert("Счет заблокирован.");
break; // Выход из switchcase133:Alert("Торговля запрещена");
break; // Выход из switchdefault: Alert("Возникла ошибка ",Error);//Другие варианты
}
break; // Выход из цикла закр
}
//-------------------------------------------------------------- 10 --Alert ("Скрипт закончил работу -----------------------------");
return; // Выход из start()
}
I'm trying to synthesise price movement analytics and nlp-attention management, and my brain is on autopilot :)
I have started to learn MQL4 and I cannot understand how an order is selected
from the tutorial:
for(int i=1; i<=OrdersTotal(); i++) // Order loop
{
if (OrderSelect(i-1,SELECT_BY_POS)==true) // If
{
if (OrderSymbol()!= Symb) continue;
My understanding is: For i=1 as long as i<= Number of Orders
If the selected order in position i-1(i.e. order #0) exists
Compare it against the symbol
Then add 1(i++) to i and start a new iteration
I do not understand the comment // If there is a next order (what do you mean: the next position or this order that is being currently selected?)
Please explain in Russian.
If there is an order, i.e. it exists under the number and-1, then go to the next condition.
It will always find an order with number zero (which is i-1). What a crazy method to determine the "next" order, truly misleading...
It will always find an order with zero number (which is i-1). This is some wild method of determining the "next" order, which is truly misleading...
If there are no orders then by this design:
it will not go to the next condition.
because there is no order and-1 (in our case =0)
Of course, it is not convenient to write it this way and it is not clear why it should be this way,
and not, for example, in this way:
Hello Mr. programmers, I have a question, I can not learn a part of the code to close the percentage of the account balance. it closes not the percentage but all at once and all orders that are in the market. I need that would close a specific order and the calculated percentage of the balance of the deposit.advise what I do wrong?
extern double Percent = 2.0;
extern int Slippage = 2;
double stop;
void OnStart()
{
if (Digits == 3 || Digits == 5)
{
Slippage *= 10;
}
for(int i = OrdersTotal()-1; i>=0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol() == Symbol())
{
if (OrderType() == OP_BUY || OrderType() == OP_SELL)
{
if(stop==AccountBalance()/100*Percent)
stop=AccountBalance()/100*Percent;
if(stop<=AccountBalance())
{
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Aqua);
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Aqua);
}//if(ostop<=AccountBalance())
}////(ostop==AccountBalance()/100*Percent)
}//// (OrderSymbol() == Symbol() )
}// (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
}//// for(int i = OrdersTotal()-1; i>=0; i--)
return;
}////void OnStart()
//+-----------------------------------------------------------------
how is that?
and this:
will never be fulfilled.
therefore:
will always work with every order.
CONCLUSION: everything is wrong.
Your function needs to be thought through, I don't have a quick answer.
But at least it's like this to start with:
If there are no orders in such a construction:
it will not go to the next condition.
because there is no order and-1 (in our case =0)
Of course, it is not convenient to write it this way and it is not clear why it should be this way,
and not, for example, like this:
When I was reading it, I also thought why not just put i=0, it seems to be simpler and clearer.
Here is the entire script code, maybe there is a good reason why the author put i=1 instead of i=0. I just don't know enough about it and may simply not see it, while I need to understand the mechanism of functioning in order not to raise questions later
There's not much difference, or am I missing something? :-)
Maybe it's more convenient for the author. Like how the score starts? 1.2.3.4.5.6.7.8.9.
And in programming language counting starts with 0.1.2.3.4.5.6
That's why the author decided to make the initial count from 1, but the whole algorithm counts from 0, to avoid confusing the newcomer.
There are no errors, it is just probably more convenient.