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

 

...and decide - here is also for you a code section of one of the ILANINS of the "Villagers" branch - calculation of the average price of the market orders and the target price of the PriceTarget - this is the b/w level + TP. TP is already at your discretion - adjust it to your needs as well:

 total=CountTrades();
      AveragePrice = 0;
      double Count = 0;
      for(cnt=OrdersTotal()-1; cnt>=0; cnt--) 
        {
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber) continue;
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber) 
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL) 
              {
               AveragePrice+=OrderOpenPrice()*OrderLots();
               Count+=OrderLots();
              }
           }
        }
      if(total>0) AveragePrice=NormalizeDouble(AveragePrice/Count,Digits);
      if(NewOrdersPlaced) 
        {
         for(cnt=OrdersTotal()-1; cnt>=0; cnt--) 
           {
            OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
            if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber) continue;
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber) 
              {
               if(OrderType()==OP_BUY) 
                 {
                  PriceTarget= AveragePrice + TakeProfit * Point;
                  BuyTarget=PriceTarget;
                  Stopper=AveragePrice-Stoploss*Point;
                  flag=TRUE;
                 }
              }
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber) 
              {
               if(OrderType()==OP_SELL) 
                 {
                  PriceTarget= AveragePrice - TakeProfit * Point;
                  SellTarget = PriceTarget;
                  Stopper=AveragePrice+Stoploss*Point;
                  flag=TRUE;
                 }
              }
           }
        }
      if(NewOrdersPlaced) 
        {
         if(flag == TRUE) 
           {
            for(cnt=OrdersTotal()-1; cnt>=0; cnt--) 
              {
               OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
               if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber) continue;
               if(OrderSymbol()== Symbol() && OrderMagicNumber() == MagicNumber) OrderModify(OrderTicket(),AveragePrice,OrderStopLoss(),PriceTarget,0,Yellow);
               NewOrdersPlaced = FALSE;
              }
           }
        }
     }
   return(0);
  }
//???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

int CountTrades() 
  {
   int count=0;
   for(int trade=OrdersTotal()-1; trade>=0; trade--) 
     {
      OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=MagicNumber) continue;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
         if(OrderType()==OP_SELL || OrderType()==OP_BUY) count++;
     }
   return(count);
  }

Instead of this NewOrdersPlaced () and OrderModify()

you will have the level of drawing (setting) your b/u line - the whole mosaic is in your hands - edit.

 
Roman.:

Here is my code section - responsible for accounting of total loss of consecutive losing trades of this particular EA (according to magician). I made it for my version of netting Avalanche - adjust it to your needs - the code is commented out...

Global Variables

This code fragment is followed by a loop through the open orders of this very EA and calculate their total profit. After that, you compare this value with the variable

and make a decision.

Iteration' - variable not defined D:Programs/MetaTrader 4 - RoboForex/experts/NewCobWebPivot.mq4 (204, 3)
Iteration' - variable not defined D:\Programs\MetaTrader 4 - RoboForex\experts\NewCobWebPivot.mq4 (234, 17)
 
belck:
Iteration' - variable not defined D:Programs/MetaTrader 4 - RoboForex/experts/NewCobWebPivot.mq4 (204, 3)
Iteration' - variable not defined D:\Programs\MetaTrader 4 - RoboForex\experts\NewCobWebPivot.mq4 (234, 17)

double  Level_new,  PointValue,
        lots;                       // вспомогательная переменная для расчета нового размера лота при очередной итерации
int Iteration, Counter_Loss, Ticket_at_history; // счетчик для подсчета последовательного убытка позиций колен лавины
//bool Flag_Counter_Loss = false;
double Current_Loss, Sum_Loss;     // текущий и суммарный убыток
 

Look at the simple way offered to you by Yuri Reshetov on the previous page.

If it does not suit you, then assemble a mosaic of your suggested code sections.

Also on the subject, it might be useful to disassemble the owl code completely - from my last post - the b/w level is ILANIN from the CELAN Double_Minus_1 branch. If you take it apart bones by bones, it will clarify the solution to your problem better, IMHO. If you are going to draw a line, you need to know how to work with objects. THESE things, IMHO, can't be solved by a "middle-level programmer" at a glance and without a push... :-)

Code owl on averaging and b/w + TP in the trailer.

Files:
 
Roman.:

You can contact me on Skype: avto-personal-plus
 
Reshetov:
This is not an error. Errors in the logbook are marked with red, not yellow icons.

Why isn't it working then?
 

I don't have Skype here.


Try the simplified version, see how Yuri Reshetov recommended you on the front page - enter his code right after mine.

See the full received code with comments:


double  Level_new,  PointValue,
        lots;                       // вспомогательная переменная для расчета нового размера лота при очередной итерации
int Iteration, Counter_Loss, Ticket_at_history; // счетчик для подсчета последовательного убытка позиций колен лавины
//bool Flag_Counter_Loss = false;
double Current_Loss, Sum_Loss;     // текущий и суммарный убыток


int start()    // -----------------------СТАРТ ЭКСПЕРТА--------------- 
{
//---------------------расчет по истории ордеров номера очередной итерации----------------------------------------------- 
  Iteration = 0; // зануляем инерации перед их учетом в цикле по истории
  Sum_Loss = 0;  // суммарный убыток по этим итерациям

datetime 
Time_at_History_Current = 0,
Time_at_History_Previos = 0;     
 
 if(OrdersHistoryTotal() != 0)
   {
    for(int counter = OrdersHistoryTotal()-1; counter >= 0; counter--)
      {
       OrderSelect(counter, SELECT_BY_POS, MODE_HISTORY);
       if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
         {
          if(OrderType() == OP_BUY || OrderType() == OP_SELL)
            {
             if(OrderProfit() < 0) // если убыток по выбранному ордеру, то считаем суммарный и записываем время закрытия ордера
                                   // для последующего его анализа при подсчете количества итераций
                {
                 double lastLoss = OrderProfit();
                 Sum_Loss=Sum_Loss+lastLoss;  // считаем общий убыток по закрытым подряд убыточным ордерам
                 Time_at_History_Current = OrderCloseTime();
                } 
             
             //Print(" Time_at_History_Current_в цикле = ", TimeToStr(Time_at_History_Current, TIME_DATE|TIME_SECONDS));
             //Print(" Time_at_History_Previos_в цикле = ", TimeToStr(Time_at_History_Previos, TIME_DATE|TIME_SECONDS));
             
             if(Time_at_History_Current != Time_at_History_Previos) // если они не равны, то считаем итерации и делаем их равными
               {
                Time_at_History_Previos = Time_at_History_Current ;
                Iteration++;
                //Print("Iteration at History в условии сравнения  = ",  Iteration);
               }   
             else // они равны, то проверяем, дополнительно, наличие профита по выбранному следующему ордеру и выходим из цикла
               {
                if(OrderProfit() >= 0)
                  break;
               }
            }
         }
      }
   }

if (Sum_Loss < 0.0) { // Имеем убыток по закрытым позам
  if ((AccountEquity + Sum_Loss) >= AccountBalance) { // Достигли безубытка
    // Здесь какой-то код, который необходимо выполнить при достижении безубытка
  }
}


}// Конец старт
 
Roman.:

I don't have Skype.


Try the simplified version, see as Yuri Reshetov recommended on the previous page - enter his code right after mine.

See the full received code with comments:



'TotalCloseProfit' - variable not defined D:\Programs\MetaTrader 4 - RoboForex\experts\NewCobWebPivot.mq4 (251, 24)
 
belck:
'TotalCloseProfit' - variable not defined D:\Programs\MetaTrader 4 - RoboForex\experts\NewCobWebPivot.mq4 (251, 24)

I have already fixed it - try again.
 

Most importantly, don't forget to enter YOUR action code when you exceed the b/w level here:

if (Sum_Loss < 0.0) { // Имеем убыток по закрытым позам
  if ((AccountEquity + Sum_Loss) >= AccountBalance) 
  { 

    // Достигли безубытка
    // Здесь какой-то код, который необходимо выполнить при достижении безубытка


  }
}
Reason: