Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1944

 
makssub #:

That's right) That's exactly what I want. Calculate and close the losing part.
Any examples?
Tried through while, got confused, didn't work.

If I'm not mistaken, these functions overlap one direction, i.e. either buy or sell. In short, we need to modify it.




//=========================================================================================================================================//
//  Функция расчета текущего состояния по открытым ордерам                                                                                 //
//=========================================================================================================================================//

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double CurrentCondition(string OrdType, string inf)
{
   int    Pos   = 0;
   double result = 0, Count = 0, AveragePrice = 0, profit = 0;
   double LastPriceBuy, LastPriceSell, ProfitBuy, ProfitSell, SumProfit;
   for(int cnt = 0; cnt < OrdersTotal(); cnt++)
   {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && (OrderMagicNumber() == MagicNumber || MagicCheck()))
         {
            if(OrderType() == OP_SELL || OrderType() == OP_BUY)
            {
               if(inf == "Lpos")
               {
                  profit = OrderProfit()              ;
                  Pos    = OrderTicket()              ;

                  if(profit > 0 && profit > Lprofit)
                  {
                     Lprofit1 = Lprofit                  ;
                     Lpos1    = Lpos                     ;
                     Lprofit  = profit                   ; //макс значение
                     Lpos     = Pos                      ;
                  }

                  if(profit < 0 && profit < Cprofit)
                  {
                     Cprofit = profit                    ; //мин  значение
                     Cpos    = Pos                       ;
                  }
               }

               SumProfit += OrderProfit() + OrderSwap() + OrderCommission() ;
               if(inf == "CurrentDrawdown")
                  result = MathMax((AccountBalance() + AccountCredit() - AccountEquity()) / (AccountBalance() + AccountCredit()) * 100, 0);
               if(inf == "CurrentUrov" && AccountMargin() > 0)
                  result = AccountEquity() / AccountMargin() * 100        ;
               if(inf == "TotalOrd")
                  result++                ;

               if(OrdType == "Buy")
               {
                  if(OrderType() == OP_BUY)
                  {
                     if(inf == "TotalBuy")
                        result++                         ;
                     if(inf == "LastLotBuy")
                        result  = OrderLots()            ;
                     if(inf == "SumLotBuy")
                        result += OrderLots()            ;
                     AveragePrice += OrderOpenPrice() * OrderLots()            ;
                     Count        += OrderLots()                              ;
                     LastPriceBuy  = OrderOpenPrice()                         ;
                     ProfitBuy += OrderProfit() + OrderSwap() + OrderCommission() ;
                     if(AveragePrice > 0 && Count > 0)
                     {
                        if(inf == "CalculateAveragePriceBuy")
                           return(NormalizeDouble(AveragePrice / Count, Digits));
                     }
                     else
                        return(0);
                  }
               }

               if(OrdType == "Sell")
               {
                  if(OrderType() == OP_SELL)
                  {
                     if(inf == "TotalSell")
                        result++                        ;
                     if(inf == "LastLotSell")
                        result  = OrderLots()           ;
                     if(inf == "SumLotSell")
                        result += OrderLots()           ;
                     AveragePrice  += OrderOpenPrice() * OrderLots()           ;
                     Count         += OrderLots()                             ;
                     LastPriceSell  = OrderOpenPrice()                        ;
                     ProfitSell += OrderProfit() + OrderSwap() + OrderCommission();
                     if(AveragePrice > 0 && Count > 0)
                     {
                        if(inf == "CalculateAveragePriceSell")
                           return(NormalizeDouble(AveragePrice / Count, Digits));
                     }
                     else
                        return(0);
                  }
               }
            }
         }
      }
   }

   if(inf == "Lpos")
      return(Lpos)                                    ;  //Ордер с наибольшим профитом
   if(inf == "Cpos")
      return(Cpos)                                    ;  //Ордер с наименьшим профитом
   if(inf == "LastPriceBuy")
      return(NormalizeDouble(LastPriceBuy, Digits))  ;
   if(inf == "LastPriceSell")
      return(NormalizeDouble(LastPriceSell, Digits))  ;
   if(inf == "ProfitBuy")
      return(NormalizeDouble(ProfitBuy,      2))  ;
   if(inf == "ProfitSell")
      return(NormalizeDouble(ProfitSell,      2))  ;
   if(inf == "SumProfit")
      return(NormalizeDouble(SumProfit,      2))  ;
   return(result)                                                             ;
}

//=========================================================================================================================================//
//   Перекрытие ордеров                                                                                                                    //
//=========================================================================================================================================//

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CheckOverlapping()
{
   Lpos = 0;
   Cpos = 0;
   Lprofit = 0;
   Cprofit = 0;

   Lpos = CurrentCondition("", "Lpos");
   Cpos = CurrentCondition("", "Cpos");

   if(totalord >= LeadingOrder)
   {
      if(Lprofit > 0 && Lprofit1 <= 0 && Cprofit < 0)
      {
         if(Lprofit + Cprofit > 0 && (Lprofit + Cprofit) * 100 / Lprofit > ProfitPersent)
         {
            Lpos1 = 0;
            CloseSelectOrder();
         }
      }
      else

         if(Lprofit > 0 && Lprofit1 > 0 && totalord > LeadingOrder && Cprofit < 0)
         {
            if(Lprofit + Lprofit1 + Cprofit > 0 && (Lprofit + Lprofit1 + Cprofit) * 100 / (Lprofit + Lprofit1) > SecondProfitPersent)
               CloseSelectOrder();
         }
   }
}

//=========================================================================================================================================//
//  Перекрытие ордеров                                                                                                                     //
//=========================================================================================================================================//

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int CloseSelectOrder()
{
   if(Info)
      Print("Функция перекрытия ордеров.");
   int error =  0;
   int error1 = 0;
   int error2 = 0;
   int Result = 0;
   int Slippage = 2 * MarketInfo(Symbol(), MODE_SPREAD);

//                       ---------------------- последний  -----------------------

   while(error1 == 0)
   {
      RefreshRates();
      int i = OrderSelect(Lpos, SELECT_BY_TICKET, MODE_TRADES);
      if(i != 1)
      {
         Print("Ошибка! Невозможно выбрать ордер с наибольшим профитом. Выполнение перекрытия отменено.");
         return (0);
      }
      if(OrderSymbol() == Symbol() && (OrderMagicNumber() == MagicNumber || MagicCheck()))
      {
         if(OrderType() == OP_BUY)
         {
            error1 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), Slippage, Blue));
            if(error1 == 1)
            {
               if(Info)
                  Print("Лидирующий ордер закрыт успешно.");
               Sleep(500);
            }
            else
            {
               Print("Ошибка закрытия лидирующего ордера, повторяем операцию. ");
            }
         }

         //                        -----------------------------------------------------

         if(OrderType() == OP_SELL)
         {
            error1 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), Slippage, Red));
            if(error1 == 1)
            {
               if(Info)
                  Print("Лидирующий ордер закрыт успешно");
               Sleep(500);
            }
            else
            {
               Print("Ошибка закрытия лидирующего ордера, повторяем операцию. ");
            }
         }
      }
   }

//                       ---------------------- пред последний  -----------------------

   if(Lpos1 != 0)
   {
      while(error2 == 0)
      {
         RefreshRates();
         i = OrderSelect(Lpos1, SELECT_BY_TICKET, MODE_TRADES);
         if(i != 1)
         {
            Print("Ошибка! Невозможно выбрать пред ордер с наибольшим профитом. Выполнение перекрытия отменено.");
            return (0);
         }
         if(OrderSymbol() == Symbol() && (OrderMagicNumber() == MagicNumber || MagicCheck()))
         {
            if(OrderType() == OP_BUY)
            {
               error2 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), Slippage, Blue));
               if(error2 == 1)
               {
                  if(Info)
                     Print("Пред Лидирующий ордер закрыт успешно.");
                  Sleep(500);
               }
               else
               {
                  Print("Ошибка закрытия пред лидирующего ордера, повторяем операцию. ");
               }
            }
            //                        -----------------------------------------------------
            if(OrderType() == OP_SELL)
            {
               error2 = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), Slippage, Red));
               if(error2 == 1)
               {
                  if(Info)
                     Print("Пред Лидирующий ордер закрыт успешно");
                  Sleep(500);
               }
               else
               {
                  Print("Ошибка закрытия Пред лидирующего ордера, повторяем операцию. ");
               }
            }
         }
      }
   }

//                      ----------- выбранный (обычно с наименьшим профитом ) -----------

   while(error == 0)
   {
      RefreshRates();
      i = OrderSelect(Cpos, SELECT_BY_TICKET, MODE_TRADES);
      if(i != 1)
      {
         Print("Ошибка! Невозможно выбрать ордер с наименьшим профитом. Выполнение перекрытия отменено.");
         return (0);
      }
      if(OrderSymbol() == Symbol() && (OrderMagicNumber() == MagicNumber || MagicCheck()))
      {
         if(OrderType() == OP_BUY)
         {
            error = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Bid, Digits), Slippage, Blue));
            if(error == 1)
            {
               if(Info)
                  Print("Перекрываемый ордер закрыт успешно.");
               Sleep(500);
            }
            else
            {
               Print("Ошибка закрытия перекрываемого ордера, повторяем операцию. ");
            }
         }

         //                             --------------------------------------------------

         if(OrderType() == OP_SELL)
         {
            error = (OrderClose(OrderTicket(), OrderLots(), NormalizeDouble(Ask, Digits), Slippage, Red));
            if(error == 1)
            {
               if(Info)
                  Print("Перекрываемый ордер закрыт успешно.");
               Sleep(500);
            }
            else
            {
               Print("Ошибка закрытия перекрываемого ордера, повторяем операцию. ");
            }
         }
      }
   }

   Result = 1;
   return (Result);
}

 
makssub #:

That's right) That's exactly what I want. Calculate and close the losing part.
Any examples?
Tried while, got confused, didn't work.

What's with the vail? What's wrong with it? You need the code. I just don't have such problems. and frankly i don't think such an approach to money management is wise.

 
Can you tell me how to load 2 same indicators with the same intents in one window in MT5? I tried INDICATOR_SHORTNAME to change it each time I start it, it doesn't help. Maybe there is another way?
 
Aleksandr Kononov #:
Please advise how to load 2 same indicators with the same intents in one window in MT5. I tried INDICATOR_SHORTNAME, I should change it each time I start it. Maybe there is another way?

Get another worthless input and change it.

 
Valeriy Yastremskiy #:

Why do you need a vail? What's wrong with it? You need a code. I just don't have this kind of problem. and frankly i don't think this approach is wise for a money manager

Good afternoon. I read about vail. I can't add or subtract.
I can't say anything about money management. I haven't tried it.
I have attached the latest version. But I have already messed up everything for myself)
Order1(2) the selected order's profit
Order1(3) the selected order's lot

double FirstProfit(int a = 1)
{
   double  profit = 0, proflot = 0,
           OneProfLot = 0, result = 1, profit_1 = 0;
           
      OneProfLot = NormalizeDouble(Lots*Order1(2)/Order1(3),2);
      profit = NormalizeDouble(Lots*Order1(2)/Order1(3),2);
      proflot = Order1(3);
      while (profit >= Order1(2) && profit <= OneProfLot)
         {
            profit -= OneProfLot;
            if (profit !=0 && NormalizeDouble(profit + CalculateProfitHistory(),2) > NormalizeDouble(ProfitLot, Digits)*Lots*100) 
            profit_1 = profit;
            proflot = NormalizeDouble(proflot*profit/Order1(2),2);
 
         }
      }
   }
   if(a==1) {result = (double)profit_1;} else
   if(a==2) {result = (double)proflot;}  
   return(result);
}
 
Alexey Viktorov #:

Get another worthless input and change it.

What about without manual intervention? In mt4 I have indicators that are set one on top of the other, and I don't know why. I would like it to be the same in mt5, and in general I would like to understand what it depends on.

 
Aleksandr Kononov #:

What about without manual intervention? In mt4 I have indicators that overlap each other, and I don't know why. I would like to do the same in mt5, and in general I would like to understand what it depends on.

It was even more interesting in MT3. I have the distribution, do you want it?

 
Alexey Viktorov #:

And MT3 was even more interesting. I have the distribution, do you want it?

I guess there is no such possibility in mt5. All right, we'll know, thank you.
 
Aleksandr Kononov #:
I understand there is no such option in mt5. Okay, well, that's good to know, thank you.

Not quite no, I told you how to get around this logical limitation.

 
The four script is taking a long time (40 minutes already) check if it's OK
Reason: