[Archive!] Any rookie question, so as not to clutter up the forum. Professionals, don't pass it by. Couldn't go anywhere without you - 2. - page 521

 
Roger:

How would I check it?

Thank you.

Is it possible to make the MaxEquity setting work for example 500 times without restarting the EA?

For example, if I write 500 in the counter, let it be as follows: Suppose the initial equity is 10 000,

After adding to the initial equity of 10,000 (by specifying in the settings), large deficits will close.

It will be done 500 times (for example) (it is anyway impossible to multiply the initial equity 500 times).

That is the difference will turn out with your version - that after increments of 10 000 to the initial equity = 10 000 -

The EA does not need to be restarted, and the cycle will continue - to 20 000 more 10 000 will be added, to 30 000 + 10 000 and so on 500 times ( for example). Well

and after each increment = 10 000, the losing order with the biggest minus ( or several orders - to be specified in the settings) will be closed ?

 
alex12:

Thank you.

Is it possible to make MaxEquity setting work for example 500 times without restarting the EA?

For example, if I write 500 in the counter, let it work like this: Suppose the initial equity is 10 000,

After adding to the initial equity of 10,000 (by specifying in the settings), the big drawbacks will close.

In the same way, let's say 500 times (for example) (after all, it is impossible to multiply the initial equity 500 times).

In other words, the difference will appear in your version: after adding 10 000 to the initial equity = 10 000.

The Expert Advisor does not need to be restarted, and the cycle will continue - to 20 000 will be added 10 000, to 30 000 + 10 000 and so on 500 times ( for example). For example:

And, after each increment equal to 10 000, the losing order with the biggest loss will be closed (or several losing orders, if you specify so in the settings) ?


There is no need to do any restarts. You need to update the initial equity data after closing the positions and wait for the equity to increase from the new initial equity.
 
artmedia70:
There is no need to do any restarts. You need to update the initial equity data after closing the positions and wait for the equity to increase from the new initial equity.
But as I understand it is all done in the programming code. I don't have programming skills)
 
alex12:
But as I understand it, it's all done in programming code. I don't have the power of programming.)
Of course you do. All we need is a function that will continuously monitor equity and send a command to close unprofitable positions if the specified value is exceeded. Then, after all of the positions are closed successfully, we need to record the new equity value and trace it further.
 
artmedia70:
Naturally. There is only one function that will continuously monitor equity and send a command to close unprofitable positions if the specified value is exceeded. Then, after all of the positions are closed successfully, the new equity status must be recorded and continued to monitor it.
Thank you.
 
tol64:

Can you tell me what the problem might be?


I'm assuming that my question doesn't contain enough information to help me.) I will complete my question. Below I provide a structure with the main functions of my Expert Advisor. Maybe this will reveal the problem that I have outlined.

// ПОДКЛЮЧАЕМЫЕ БИБЛИОТЕКИ С ФУНКЦИЯМИ
// ВНЕШНИЕ ПАРАМЕТРЫ
// ГЛОБАЛЬНЫЕ ПЕРЕМЕННЫЕ

Init()
{
  // ПРОВЕРКА: ПРАВИЛЬНО ЛИ ВВЕДЕНЫ ЗНАЧЕНИЯ ТАЙМФРЕЙМОВ ВО ВНЕШНИХ ПАРАМЕТРАХ.
}

Deinit()
{
  return(0);
}

Start()
{
  // ЛОКАЛЬНЫЕ ПЕРЕМЕННЫЕ
  // ИНДИКАТОРЫ
  // УСЛОВИЯ
  // ФУНКЦИИ ВИЗУАЛИЗАЦИИ
  // ФУНКЦИЯ УДАЛЕНИЯ ОРДЕРОВ ПРИ ИСПОЛНЕНИИ ОПРЕДЕЛЁННОГО УСЛОВИЯ
  
//--- ВЫЗОВ ФУНКЦИИ УПРАВЛЕНИЯ КАПИТАЛОМ ------------------------------------------------------------------//  
   if (Money_Management_OnOff == TRUE)
      {  
         MM_FxProp(Delta,Start_Lot,Start_Deposit,Step_Lot,Stop_Trade,Symbol());
         Lots = NormalizeDouble(GlobalVariableGet("fxprop_lot"),2);

      //--- ПРОВЕРКА: ИЗМЕНИЛОСЬ ЛИ ЗНАЧЕНИЕ ЛОТА С ЦЕЛЬЮ ПЕРЕУСТАНОВКИ ОТЛОЖЕННЫХ ОРДЕРОВ ----------------//
         Re_Set_All_Orders_by_Lots(dgt, Lots);
      }
   else  Lots = 0.1;

  // ФУНКЦИЯ ИНФОРМАЦИОННОЙ ПАНЕЛИ
  // ПРОВЕРКА НА НОВЫЙ БАР
  // ПРОВЕРКА НА КОЛ-ВО БАРОВ НА ГРАФИКЕ
  // ПРОВЕРКА НА КОЛ-ВО ЗНАКОВ В СИМВОЛЕ
  // УСТАНОВКА ФЛАГОВ, ЕСЛИ ИСПОЛНЯЮТСЯ УСЛОВИЯ ДЛЯ ЗАКРЫТИЯ ОПРЕДЕЛЁННЫХ ПОЗИЦИЙ
  // ФУНКЦИИ ЗАКРЫТИЯ ПОЗИЦИЙ ПО ОПРЕДЕЛЁННЫМ УСЛОВИЯМ
  // ФУНКЦИЯ ТРЕЙЛИНГ СТОПА
  // ФУНКЦИЯ МОДИФИКАЦИИ ОТЛОЖЕННЫХ ОРДЕРОВ
  // ФУНКЦИЯ УСТАНОВКИ ОТЛОЖЕННЫХ ОРДЕРОВ
  // ФУНКЦИЯ ОТКРЫТИЯ ПОЗИЦИИ ПО ОПРЕДЕЛЁННЫМ УСЛОВИЯМ
  // УДАЛЕНИЕ ОТЛОЖЕННЫХ ОРДЕРОВ ПО ОПРЕДЕЛЁННЫМ УСЛОВИЯМ
  
//--- ЗАНОСИТЬ ДАННЫЕ В ОТЧЁТ ТОЛЬКО, ЕСЛИ КОЛ-ВО ЗАКРЫТЫХ ПОЗИЦИЙ ИЗМЕНИЛОСЬ
   Amount_Positions = 0;
   
   for(count = 0; count < OrdersHistoryTotal(); count++)
      {
         OrderSelect(count, SELECT_BY_POS, MODE_HISTORY);

         if(OrderType() == OP_BUY || OrderType() == OP_SELL)
            {
               Amount_Positions++;
            }
      }

   if(Amount_Close_Deals != Amount_Positions)
      {  
         if(Short_Trade_Report == TRUE)
            {  
               // ФУНКЦИЯ ФОРМИРУЮЩАЯ ОТЧЁТ
            }
         Amount_Close_Deals = Amount_Positions;
      }
}

At the moment I have to recompile the EA every time after enabling/disabling the money management function in EA parameters, for the report to be generated correctly.

P.S. Maybe it has something to do with global variable terminal fxprop_lot?

 
tol64:


I assume, that there is not enough information in my question to help me). I'll supplement my question. Below I am providing structure with basic functions of my EA. Maybe in this way it will be possible to identify the problem, which I have highlighted.

At the moment I have to recompile the EA every time after enabling/disabling the money management function in EA parameters for the report to be generated correctly.

P.S. Maybe it has something to do with global variable terminalfxprop_lot?


If you think that's enough, I guess it is. I just have to wait for an answer. I don't have one.
 
Vinin:

If you think that is enough, I guess so. I am waiting for an answer. I do not have one.


My experience so far unfortunately does not allow me to judge whether or not the information provided is sufficient to address a particular issue. I don't do it on purpose and apologise if you do.) The thing is, in my opinion, the key point in the problem I highlighted is that everything works correctly when recompiling the Expert Advisor. But this again due to my immature experience. Please advise what information needs to be provided to resolve this issue. The money management function or report generation function obviously appears in the problem. That is why I will give you the money management function:

double MM_FxProp(double Delta, double Start_Lot, double Start_Deposit, double Step_Lot, double Stop_Trade, string fSymbol) 
{
   if (Delta < Step_Lot || Start_Lot < Step_Lot                          ||    // если Delta <, чем 0.01 или Start_Lot <, чем 0.01 или
       Start_Deposit <= MarketInfo(fSymbol, MODE_MARGINREQUIRED) / 10.0  ||    // Start_Depo <=, чем размер свободных средств, ...
                                                                               // ...необходимых для открытия 1 лота на покупку (разделить на 10) или
       AccountFreeMarginCheck(fSymbol, OP_BUY, Start_Lot) <= Stop_Trade  ||    // размер свободных средств после BUY <= Stop_Trade или
       AccountFreeMarginCheck(fSymbol, OP_SELL, Start_Lot) <= Stop_Trade ||    // размер свободных средств после SELL <= Stop_Trade или
       Start_Lot < MarketInfo(fSymbol, MODE_MINLOT)                      ||    // Start_Lot <, чем минимальный возможный или
                
       (fSymbol != "GBPUSD" && fSymbol != "EURUSD" && fSymbol != "USDCHF" && fSymbol != "USDJPY" &&     // нет ни одного инструмента из ниже перечисленных, то
        fSymbol != "AUDUSD" && fSymbol != "USDCAD" && fSymbol != "EURCHF" && fSymbol != "EURGBP" && 
        fSymbol != "EURJPY" && fSymbol != "EURCAD" && fSymbol != "EURAUD" && fSymbol != "GBPCHF" &&
        fSymbol != "GBPJPY" && fSymbol != "CHFJPY" && fSymbol != "NZDUSD" && fSymbol != "USDSEK" && 
        fSymbol != "USDDKK" && fSymbol != "USDNOK" && fSymbol != "USDSGD" && fSymbol != "USDZAR" && 
        fSymbol != "EURNZD" && fSymbol != "AUDJPY" && fSymbol != "AUDNZD" && fSymbol != "AUDCAD" && 
        fSymbol != "AUDCHF" && fSymbol != "CADCHF" && fSymbol != "CADJPY" && fSymbol != "NZDJPY" && fSymbol != "XAUUSD")) 
       {
         Print("Расчет лота функцией MM_FxProp() невозможен из-за некорректности значений переданных ей аргументов.");
         return (0);
       }
   
   double S_D     = Start_Deposit;
   double S_L     = Start_Lot;
   double Stp_L   = Step_Lot;
   double stepUP  = 0;
   double stepDW  = 0;
   
   if (AccountBalance() >= Start_Deposit) //если текущий баланс >= значению Start_Depo, то
   {
      while (AccountBalance() > S_D + Delta * (10.0 * S_L)) //пока текущий баланс >, чем результат формулы
      {
         S_D += Delta * (10.0 * S_L);
         S_L += Stp_L;
      }
      stepUP = S_D + Delta * (10.0 * S_L);
      stepDW = S_D;
   }
   
   if (AccountBalance() < Start_Deposit) 
   {
      while (AccountBalance() < S_D) 
      {
         if (S_L > Stp_L) S_L -= Stp_L;
         else S_L = Stp_L;
         S_D -= Delta * (10.0 * S_L);
      }
      stepDW = S_D;
      stepUP = S_D + Delta * (10.0 * S_L);
   }
   
   if (AccountFreeMarginCheck(fSymbol, OP_BUY, S_L) <= Stop_Trade  ||   // если размер свободных средств после BUY <= Stop_Trade или
       AccountFreeMarginCheck(fSymbol, OP_SELL, S_L) <= Stop_Trade ||   // размер свободных средств после SELL <= Stop_Trade или
       GetLastError() == 134/* NOT_ENOUGH_MONEY */                 ||   // не хватает средств для операции или
       S_L < MarketInfo(fSymbol, MODE_MINLOT))                          // расчитанный объём лота <, чем минимальный возможный, то
       {
         while (AccountFreeMarginCheck(fSymbol, OP_BUY, S_L) <= Stop_Trade || // пока размер свободных средств после BUY <= Stop_Trade или
                AccountFreeMarginCheck(fSymbol, OP_SELL, S_L) <= Stop_Trade)  // размер свободных средств после SELL <= Stop_Trade, то
                {
                  S_L -= Stp_L;    // считаем так.
                  if (S_L < MarketInfo(fSymbol, MODE_MINLOT))  // если же расчитанный объём лота <, чем минимальный возможный, то
                     {
                        Print("Объём средств на счете не позволяет открыть позицию минимального объёма.");
                        return (GlobalVariableSet("fxprop_lot", 0));
                     }
                }
       } 
   else {
            GlobalVariableSet("fxprop_lot", S_L);
            Comment("Средств на счете: ", DoubleToStr(AccountBalance(),2), ", лот: ", S_L, ", лот + ", Stp_L, "при >=", stepUP, ", лот - ", Stp_L, "при <", stepDW); return;
        }
   return (0.0);
}
And in the next post the report generation function...
 
void Short_Trade_Report(int Mgc_Src_LP_TS№1,int Mgc_LP01_TS№1,int Mgc_LP02_TS№1,int Mgc_LP03_TS№1,int Mgc_LP04_TS№1,int Mgc_LP05_TS№1,int Mgc_LP06_TS№1,
                        int Mgc_Src_SP_TS№1,int Mgc_SP01_TS№1,int Mgc_SP02_TS№1,int Mgc_SP03_TS№1,int Mgc_SP04_TS№1,int Mgc_SP05_TS№1,int Mgc_SP06_TS№1,
                        
                        int Mgc_Src_LP_TS№2,int Mgc_LP01_TS№2,int Mgc_LP02_TS№2,int Mgc_LP03_TS№2,int Mgc_LP04_TS№2,int Mgc_LP05_TS№2,int Mgc_LP06_TS№2,
                        int Mgc_Src_SP_TS№2,int Mgc_SP01_TS№2,int Mgc_SP02_TS№2,int Mgc_SP03_TS№2,int Mgc_SP04_TS№2,int Mgc_SP05_TS№2,int Mgc_SP06_TS№2,
                        
                        int Mgc_Src_LP_TS№3,int Mgc_LP01_TS№3,int Mgc_LP02_TS№3,int Mgc_LP03_TS№3,int Mgc_LP04_TS№3,int Mgc_LP05_TS№3,int Mgc_LP06_TS№3,
                        int Mgc_Src_SP_TS№3,int Mgc_SP01_TS№3,int Mgc_SP02_TS№3,int Mgc_SP03_TS№3,int Mgc_SP04_TS№3,int Mgc_SP05_TS№3,int Mgc_SP06_TS№3)
{
#define  RA 10000      // Range Array - Размер массива для отчёта
      
double   Acc_Bal_Close[RA];   // Массив для баланса на закрытии сделки(-ок)
double   Acc_Bal_Open[RA];    // Массив для баланса на открытии сделки(-ок)

double   Price_Open_Pos[RA];
double   Price_Stop_Loss[RA];

double   TS№1_DS[RA], TS№2_TA[RA], TS№3_SBH[RA];

int      pos, handle, dgt, Magic, sign, index;

double   Swap_P;
double   Profit_P;
double   Commission;
double   Open_Price;
double   Stop_Loss;
      
string   Type_Pos;
string   comment;
string   Str_Stop_Loss;
      
//--- ПРОВЕРКА НА КОЛ-ВО ЗНАКОВ В СИМВОЛЕ ДЛЯ РАСЧЁТА ОТСТУПА В СТРОКАХ КОММЕНТАРИЕВ --------------------------------//
int digit_string;
int digit = MarketInfo(Symbol(),MODE_DIGITS);
   
switch(digit)
      {  case 2 : digit_string = 4; dgt = 100;    break;
         case 3 : digit_string = 5; dgt = 100;    break;
         case 4 : digit_string = 6; dgt = 10000;  break;
         case 5 : digit_string = 7; dgt = 10000;  break;
         default: Print("Неизвестный символ! Количество знаков = ",digit); return(0);  }

handle = FileOpen("ShortReport.csv",FILE_CSV|FILE_WRITE);
      
if(handle > 0) //1
   {
      FileWrite(handle,"Time Close"+","+"Symbol"+","+"Type"+","+"Lots"+","+"Balance($)"+","+"Stop Loss(p)"+","+"Profit(p)"+","+"TS#1_DS(p)"+","+"TS#2_TA(p)"+","+"TS#3_SBH(p)");

      for(pos = 0; pos < OrdersHistoryTotal(); pos++) // 2
         {  
            OrderSelect(pos,SELECT_BY_POS,MODE_HISTORY);
                  
            Commission =  OrderCommission();
            Swap_P     = (OrderSwap()/10)/OrderLots();
            Profit_P   = (OrderProfit()/10)/OrderLots()+(OrderSwap()/10)/OrderLots();
            Open_Price =  NormalizeDouble(OrderOpenPrice(),Digits);
            
            index = StringFind(OrderComment(),"[sl]",0);
            
            if(index != -1)   {  comment = StringSubstr(OrderComment(),0,StringLen(OrderComment())-4);   }
            else  {  comment = StringSubstr(OrderComment(),0,StringLen(OrderComment()));  }
            
            if(OrderType() < 2 && OrderCloseTime() == TimeCurrent() && 
                                 (OrderMagicNumber() == Mgc_Src_LP_TS№1 || OrderMagicNumber() == Mgc_Src_SP_TS№1 || 
                                  OrderMagicNumber() == Mgc_LP01_TS№1   || OrderMagicNumber() == Mgc_LP02_TS№1   || OrderMagicNumber() == Mgc_LP03_TS№1 || 
                                  OrderMagicNumber() == Mgc_LP04_TS№1   || OrderMagicNumber() == Mgc_LP05_TS№1   || OrderMagicNumber() == Mgc_LP06_TS№1 ||
                                  OrderMagicNumber() == Mgc_SP01_TS№1   || OrderMagicNumber() == Mgc_SP02_TS№1   || OrderMagicNumber() == Mgc_SP03_TS№1 ||
                                  OrderMagicNumber() == Mgc_SP04_TS№1   || OrderMagicNumber() == Mgc_SP05_TS№1   || OrderMagicNumber() == Mgc_SP06_TS№1))
               {     
                  TS№1_DS[pos]         = Profit_P + Swap_P + Commission;
                  Acc_Bal_Close[pos]   = AccountBalance();
                  Str_Stop_Loss        = StringSubstr(comment,StringLen(comment)-digit_string,digit_string);
                  Price_Stop_Loss[pos] = MathAbs((StrToDouble(Str_Stop_Loss)-Open_Price)*dgt);
               }

            if(OrderType() < 2 && OrderCloseTime() == TimeCurrent() && 
                                 (OrderMagicNumber() == Mgc_Src_LP_TS№2 || OrderMagicNumber() == Mgc_Src_SP_TS№2 || 
                                  OrderMagicNumber() == Mgc_LP01_TS№2   || OrderMagicNumber() == Mgc_LP02_TS№2   || OrderMagicNumber() == Mgc_LP03_TS№2 || 
                                  OrderMagicNumber() == Mgc_LP04_TS№2   || OrderMagicNumber() == Mgc_LP05_TS№2   || OrderMagicNumber() == Mgc_LP06_TS№2 ||
                                  OrderMagicNumber() == Mgc_SP01_TS№2   || OrderMagicNumber() == Mgc_SP02_TS№2   || OrderMagicNumber() == Mgc_SP03_TS№2 ||
                                  OrderMagicNumber() == Mgc_SP04_TS№2   || OrderMagicNumber() == Mgc_SP05_TS№2   || OrderMagicNumber() == Mgc_SP06_TS№2))
               {  
                  TS№2_TA[pos]         = Profit_P + Swap_P + Commission;
                  Acc_Bal_Close[pos]   = AccountBalance();
                  Str_Stop_Loss        = StringSubstr(comment,StringLen(comment)-digit_string,digit_string);
                  Price_Stop_Loss[pos] = MathAbs((StrToDouble(Str_Stop_Loss)-Open_Price)*dgt);
               }

            if(OrderType() < 2 && OrderCloseTime() == TimeCurrent() && 
                                 (OrderMagicNumber() == Mgc_Src_LP_TS№3 || OrderMagicNumber() == Mgc_Src_SP_TS№3 || 
                                  OrderMagicNumber() == Mgc_LP01_TS№3   || OrderMagicNumber() == Mgc_LP02_TS№3   || OrderMagicNumber() == Mgc_LP03_TS№3 || 
                                  OrderMagicNumber() == Mgc_LP04_TS№3   || OrderMagicNumber() == Mgc_LP05_TS№3   || OrderMagicNumber() == Mgc_LP06_TS№3 ||
                                  OrderMagicNumber() == Mgc_SP01_TS№3   || OrderMagicNumber() == Mgc_SP02_TS№3   || OrderMagicNumber() == Mgc_SP03_TS№3 ||
                                  OrderMagicNumber() == Mgc_SP04_TS№3   || OrderMagicNumber() == Mgc_SP05_TS№3   || OrderMagicNumber() == Mgc_SP06_TS№3))
               {  
                  TS№3_SBH[pos]        = Profit_P + Swap_P + Commission;
                  Acc_Bal_Close[pos]   = AccountBalance();
                  Str_Stop_Loss        = StringSubstr(comment,StringLen(comment)-digit_string,digit_string);
                  Price_Stop_Loss[pos] = MathAbs((StrToDouble(Str_Stop_Loss)-Open_Price)*dgt);
               }
                  
            if(OrderType() == OP_BUY)   {  Type_Pos = "buy";   }
            if(OrderType() == OP_SELL)  {  Type_Pos = "sell";  }
                  
            if(OrderType() < 2)
               {  
                  FileWrite(handle,TimeToStr(OrderCloseTime(),TIME_DATE|TIME_MINUTES)+","+Symbol()+","+Type_Pos+","
                                                                                           
                                  +DoubleToStr(OrderLots(),2)+","+DoubleToStr(Acc_Bal_Close[pos],2)+","+DoubleToStr(Price_Stop_Loss[pos],2)+","
                                       
                                  +DoubleToStr(Profit_P+Swap_P+Commission,2)+","+DoubleToStr(TS№1_DS[pos],2)+","+DoubleToStr(TS№2_TA[pos],2)+","+DoubleToStr(TS№3_SBH[pos],2));  }
      }  FileClose(handle); // 2\
   } //1
}
Please help in resolving the issue.
 

Tried calling the capital management function during initialisation:

int init()
  {

   ...
   
   if(!GlobalVariableCheck("fxprop_lot"))
      {
      //--- ВЫЗОВ ФУНКЦИИ УПРАВЛЕНИЯ КАПИТАЛОМ ----------------------------------------//
         if (Money_Management_OnOff == TRUE)
            {  
               MM_FxProp(Delta,Start_Lot,Start_Deposit,Step_Lot,Stop_Trade,Symbol());
               Lots = NormalizeDouble(GlobalVariableGet("fxprop_lot"),2);
            }
         else  Lots = 0.1;
      }

   return(0);
  }
But that doesn't solve the problem...
Reason: