[ARCHIVE] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 3. - page 524

 
sss2019:

My Expert Advisor opens three orders in my terminal, at some point it should close all three orders, but for some reason it closes only two, it gives no errors.

Here is this piece which should close trades

I do not understand what's wrong and why only two deals are closed. Please tell me who knows what.

if(OrderSelect(i, SELECT_BY_POS) == false) continue;
 
Vinin:


Do the cycle differently


This didn't help either though. Not rearranging the loop or substituting continue didn't help, as if the EA doesn't see its own three orders, and only deletes two.

 
Reverse the direction of cycle recalculation
 
Take it and use it.
Files:
 
Sometimes things are so incomprehensible, not logical at all, I think there are errors in the terminal environment itself.
 
sss2019:
Sometimes things are so incomprehensible, not logical at all, I think there are errors in the terminal environment itself.
To make it seem less you need to start by studying a textbook and a manual. Then try to find explanations of similar issues on the forum.
 
sss2019:

How would you better organise the maximum drawdown of the EA, at which it stops working, can you set a static variable that will accumulate the amount of losses?

The Expert Advisor should stop working, but it will start working again after restarting or changing parameters.


When initializing an EA, you can save the current balance in a static variable. And in the Start function, you can check how many percent of the current balance has decreased from the initial one and if the percentage is more than permissible - prohibit to trade. Briefly, without any code. After restarting, the Expert Advisor will remember the new initial balance...
 
MrSoros:

When initializing the Expert Advisor, the current balance can be saved in a static variable. And in the Start function, check how much the current balance has slipped from the initial balance, and if the percentage is higher than allowed - trade is prohibited. Briefly, without any code. After restarting, the Expert Advisor will remember the new initial balance.

Have you understood the question?
 
MrSoros:

1. When initializing the Expert Advisor, you can save the current balance to a static variable. Then the Start function checks by how many percent the current balance has declined from the initial one and if the percentage is higher, the trade will be prohibited. In brief, without any code.

2. After restarting, the assessor will remember the new original balance...

1. You can. I have this option (with code) - you initialize variables yourself:

extern int MaxLoss = 90;          // Максимально допустимая просадка в процентах от баланса
int  orderIndex;
bool IsExpertFailed = false;
bool IsExpertStopped = false;
double lots;                       // вспомогательная переменная для расчета нового размера лота 
double Lots_New;                   // Количество лотов для новых ордеров
int ticket;                        // Номер ордера
double orderLots;                  // Lots   
double orderProfit;                // Profit
double Price;                      // Цена открытия рыночного ордера
double SL;                         // Значение StopLoss ордера
double  TP;                        // Значение TakeProfit ордера
static datetime prevtime = 0;       // по ценам открытия
int start()
{  
   if (IsExpertStopped)
   {
      Comment("Не удалось инициализировать советник!");
      return (0);
   }
   
   if (IsExpertFailed)
   {
      Comment("Критическая ошибка! Советник остановлен.");
      return (0);
   }
      Level_new=MarketInfo(Symbol(),MODE_STOPLEVEL );    
 
   int orderCount = 0;  
      // ------------------------------------------------Учет ордеров только ЭТОГО ЭКСПА---------------------------

   int orderType;
   for (orderIndex = (OrdersTotal() - 1); orderIndex >= 0; orderIndex--)
     {  
      if (!OrderSelect(orderIndex, SELECT_BY_POS))    continue;
      if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != magic))    continue;

      orderType = OrderType();
      if ((orderType != OP_BUY) && (orderType != OP_SELL))     continue;
          ticket = OrderTicket( );                         // Номер ордера
          orderLots = OrderLots();                         // Lots   
          orderProfit = OrderProfit() + OrderSwap();       // Profit
          Price = OrderOpenPrice();                        // Цена открытия рыночного ордера
          SL =  OrderStopLoss();                           // Значение StopLoss ордера
          TP = OrderTakeProfit();                          // Значение TakeProfit ордера
          
             if (ticket>0)                                               // Если позиция открылась
                    {
                             while(OrderSelect(ticket,SELECT_BY_TICKET)==false)       // Если ордер выбран
                                 {
                                   Sleep(100);
                                 }
                                  double OpenPrice=OrderOpenPrice();
                    }
          // Проверка на предельную просадку      
      double loss = - ((orderProfit * 100.0) / AccountBalance());
      if (loss > MaxLoss)
      {
         Print ("MaxLoss");
         CloseAllOrders(magic);
         IsExpertFailed = true;
         return (0);
      }        
         
      orderCount++;                     // считаем ордера (не больше i)                   
     
    }   

2. No. It will not remember the balance level that was before the start of this EXPERT the first time. Will only remember the current level in the variable

AccountBalance()

. for this account.

 

Good afternoon! I had a question before about the correct representation of quotes in Excel. This question has been answered thanks tocosty .Now I have a question, is it possible to make (without MQL5 and dll) the data for more currencies to be uploaded? The schematic is shown below, instead of "..." the corresponding date values, closing price values and current period.

I assume the answer to the question will involve possible corrections to my code. I am attaching the code of Expert Advisor that writes values of closing prices for one, current financial instrument to the file.

#property copyright "S.I.Shlikov"
#property link      ""
int init()  
  {
   string Name=Symbol();
   int h=FileOpen(Symbol()+"-"+Period()+".csv",FILE_CSV|FILE_WRITE|FILE_READ,";");
    if(h<1)
      {
      Print("Файл не найден : ", GetLastError());
      return(false);
      }
   FileSeek(h, 0, SEEK_END);
   FileWrite(h,"Date",Name,"Period",Period());
   FileClose(h);        
  }
int start()
  {
   int h=FileOpen(Symbol()+"-"+Period()+".csv",FILE_CSV|FILE_WRITE|FILE_READ,";");
    if(h<1)
      {
      Print("Файл не найден : ", GetLastError());
      return(false);
      }
   string Wtime=TimeToStr(TimeCurrent(),TIME_DATE|TIME_MINUTES);
   FileSeek(h, 0, SEEK_END);
   FileWrite(h,Wtime,NormalizeDouble(Close[0], Digits));
   FileClose(h);   
   return(0);
  }