Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 486

 
alex12:
I'm trying to synthesise price movement analytics and nlp-attention management, and my brain is on autopilot :)
In the quest for enlightenment, the main thing is to choose the right substances so as not to fly too far
 

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.
 
Vladon:
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...
 
Thank you for the explanations.
 
evillive:

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?


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()
//+-----------------------------------------------------------------

 
OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Aqua);
OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Aqua);

how is that?

and this:

if(stop==AccountBalance()/100*Percent)
stop=AccountBalance()/100*Percent;

will never be fulfilled.

therefore:

if(stop<=AccountBalance())

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:

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(OrderProfit()>=AccountBalance()/100*Percent)

{
if(OrderType() == OP_SELL)OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Aqua);
if(OrderType() == OP_BUY)OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Aqua);
}//if(ostop<=AccountBalance())
}//if(ostop==AccountBalance()/100*Percent)
}//if (OrderSymbol() == Symbol() )
}//if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
}//for(int i = OrdersTotal()-1; i>=0; i--)
return;
}//void OnStart()
//+-----------------------------------------------------------------
 
Vladon:


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

// 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)                        // По типу ордера
        {
         case 0: double Price_Cls=Bid;          // Ордер Buy
            string Text="Buy ";                 // Текст для Buy
            break;                              // Из switch
         case 1: 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)                             // Преодолимые ошибки
        {
         case 135:Alert("Цена изменилась. Пробуем ещё раз..");
            RefreshRates();                     // Обновим данные
            continue;                           // На след. итерацию
         case 136:Alert("Нет цен. Ждём новый тик..");
            while(RefreshRates()==false)        // До нового тика
               Sleep(1);                        // Задержка в цикле
            continue;                           // На след. итерацию
         case 146:Alert("Подсистема торговли занята. Пробуем ещё..");
            Sleep(500);                         // Простое решение
            RefreshRates();                     // Обновим данные
            continue;                           // На след. итерацию
        }
      switch(Error)                             // Критические ошибки
        {
         case 2 : Alert("Общая ошибка.");
            break;                              // Выход из switch
         case 5 : Alert("Старая версия клиентского терминала.");
            break;                              // Выход из switch
         case 64: Alert("Счет заблокирован.");
            break;                              // Выход из switch
         case 133:Alert("Торговля запрещена");
            break;                              // Выход из switch
         default: Alert("Возникла ошибка ",Error);//Другие варианты   
        }
      break;                                    // Выход из цикла закр
     }
//-------------------------------------------------------------- 10 --
   Alert ("Скрипт закончил работу -----------------------------");
   return;                                      // Выход из start()
  }

 

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.

Reason: