learn how to earn money villagers [Episode 2] ! - page 102

 
BeerGod:

Day three of manual trading, trading is over for today


Congratulations! I have a bunch of sells on the euro on a pullback down - closed, on the pound - not...

50,000 cent - went over - already good! :-)

[Deleted]  

Greetings.

maybe someone is familiar with this code:

//-----------------Закрытие по истории в безубыток--------------------
   //---------------------расчет по истории ордеров номера очередной итерации----------------------------------------------- 
  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) { // Имеем убыток по закрытым позам
double money = Lots;
   BuyLots = GetBuyLotsSum();
        SellLots = GetSellLotsSum();
        if(BuyLots  > SellLots)money = BuyLots * 10;
        if(BuyLots  < SellLots)money = SellLots * 10;
  if (((AccountEquity() + Sum_Loss + (Sum_Loss / money)) >= AccountBalance()) && (((totalSell > 0) && (totalBuy < 1)) || ((totalSell < 1) && (totalBuy > 0)))) { // Достигли безубытка
    // Здесь какой-то код, который необходимо выполнить при достижении безубытка
        CloseAllBuy();
           CloseAllSell();
           Sum_Loss = 0.0;
           

i can't seem to change this: when a deal was closed in minus, the loop is opened and if next order is closed above zero, i.e. positive balance, but less than negative, we add plus to negative and get a new negative value, which is already less.

if(OrderProfit() >= 0 && Sum_Loss < 0.0)
                  double lastLoss_two = OrderProfit();
                 Sum_Loss=Sum_Loss+lastLoss_two;  // считаем общий убыток по закрытым подряд убыточным ордерам
                 Time_at_History_Current = OrderCloseTime();
               }

If it is more negative, according to the signal, we close the order and start the cycle from the beginning.

 
belck:

Hello.

Perhaps someone is familiar with this code:

Yes. This is my code. I already wrote you that I use it in my rollover martin as follows:

If last trade (pose) was closed in profit, then we zero out the number of flips (Iteration) and start with starting lot, if in minus,

then count the number of losing trades in a row and open in the opposite direction with an increased volume.

This is a netting version of Avalanche (see the branch with the same name ), i.e. market order is closed (at position flip on increased volumes) and the opposite market order is opened on larger volumes depending on the share scheme. Here is my working part of the code. Edit it to suit your needs if you have a similar exp algorithm. I do not understand anything in your question. You can ask regardless of the situation in the "Any newbie question ...", just elaborate on your question, because nothing (at least for me) is clear - at all.

  //---------------------расчет по истории ордеров номера очередной итерации----------------------------------------------- 
  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;
               }
            }
         }
      }
   }
 //Print("Iteration at History = ",  Iteration, " Time_at_History_Current = ", TimeToStr(Time_at_History_Current, TIME_DATE|TIME_SECONDS),
 //      " Time_at_History_Previos = ", TimeToStr(Time_at_History_Previos, TIME_DATE|TIME_SECONDS));
       
    //-----------------------------------------------------расчет динамического канала----------------------------    
    if (Symbol() == "GBPJPY" || Symbol() == "EURJPY" || Symbol() == "USDJPY" || Symbol() == "CHFJPY" ||  Symbol() == "NZDJPY")  
      // || Symbol() == "XAUUSD" || Symbol() == "XAGUSD" || Symbol() == "EURGBP")   StopLossPips = StopLoss;    // т.к. волатильность (по АТР) другая (выше)
         {                 
           channel = (iATR(Symbol(),PERIOD_D1,Period_ATR,1)*1000)*Mul_Sl;                 
           StopLossPips = NormalizeDouble(channel,0);                                                                                                         
         }       
    else
         {                 
           channel = 10* (iATR(Symbol(),PERIOD_D1,Period_ATR,1)*10000/3)*Mul_Sl;                 
           StopLossPips = NormalizeDouble(channel,0);                                                                                                         
         }               
   TakeProfitPips=NormalizeDouble(StopLossPips*Mul_TP,0);  // расчет уровня тейка для всех инструментов по заданному значению динамического стопа        
                          
   // ------------------------------------------------Ищем наш ордер---------------------------------
   int orderType;
   for (int orderIndex = (OrdersTotal() - 1); orderIndex >= 0; orderIndex--)
   {
      if (!OrderSelect(orderIndex, SELECT_BY_POS))     continue; // если ордер не выбран, то идем на следующий открытый
      if(OrderCloseTime()!=0) continue;                    // если тикет принадлежит закрытому ордеру, то берем следующий открытый
      if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != MagicNumber)) 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();
       // Print("OrderTicket()=",OrderTicket(),  "OrderOpenTime()=",OrderOpenTime()); 
       // Print("TimeLocal()=",TimeLocal());                                                                    
                     //---------------------Запоминаем значения сл и тп ордера                     
                if (orderType == OP_BUY) 
                   {                
                     V_StopLossPips = NormalizeDouble(OpenPrice  - (StopLossPips * Point), Digits);
                     V_TakeProfitPips = NormalizeDouble(OpenPrice + (TakeProfitPips * Point), Digits);
                   }
            
                if (orderType == OP_SELL) 
                   {        
                     V_StopLossPips = NormalizeDouble(OpenPrice  + (StopLossPips * Point), Digits);
                     V_TakeProfitPips = NormalizeDouble(OpenPrice - (TakeProfitPips * Point), Digits);
                   }   
                            
              }
             
     // Проверка на предельную просадку      
      double loss = - ((orderProfit * 100.0) / AccountBalance());
      if (loss > MaxLoss)
      {
         Print ("MaxLoss");
         CloseAllOrders(MagicNumber);
         IsExpertFailed = true;
         return (0);
      }
    
       // Проверка закрытия открытой позиции (ордера) по стоп-лоссу           
      if ( V_StopLossPips != 0 )
        {
          if (orderType == OP_BUY && Bid <=  V_StopLossPips)  { CloseAllOrders(MagicNumber); Print ("V_StopLossPips закрываем по сл = ", V_StopLossPips); }             
          if (OrderType()== OP_SELL && Ask >=  V_StopLossPips){ CloseAllOrders(MagicNumber); Print ("V_StopLossPips закрываем по сл = ", V_StopLossPips); }  
        }         
        
        // Проверка закрытия открытой позиции (ордера) по тейку        
        if ( V_TakeProfitPips != 0 && MathAbs(orderProfit) > MathAbs (Sum_Loss))
        {
          if (orderType == OP_BUY && Bid >=  V_TakeProfitPips)  { CloseAllOrders(MagicNumber); Print ("V_TakeProfitPips закрываем по ТР = ", V_TakeProfitPips); }             
          if (OrderType()== OP_SELL && Ask <=  V_TakeProfitPips){ CloseAllOrders(MagicNumber); Print ("V_TakeProfitPips закрываем по ТР = ", V_TakeProfitPips); }  
        }        
      
      
      // Если тралить, то с соответствующего номера итерации при выполнении НЕОБХОДИМОГО УСЛОВИЯ соответствующим 
      // выбранному видом трала      
      
      if (UseTrailing==1) if ((Iteration >= k)&& (MathAbs(orderProfit) > (MathAbs (Sum_Loss))))
         switch(type)
          {
           case 0:  // простой трал по аналогии учебнику - в зависимости от параметра trlinloss (тралить ли в зоне лоссов)
                   if (orderType == OP_BUY)  SampleTrailing_texbook (0, V_StopLossPips, V_TakeProfitPips); // если бай
                   if (orderType == OP_SELL) SampleTrailing_texbook (1, V_StopLossPips, V_TakeProfitPips); // если селл
                   break;
           //трал по фракталам + отступ (Indent)
           case 1: TrailingByFractals_LAVINA(ticket,signal_period,Sum_Loss,Lots_New,V_StopLossPips,trlinloss); break; 
            //трал по теням N свечей + отступ (Indent)       
           case 2: TrailingByShadows  (ticket,signal_period,Sum_Loss,Lots_New,V_StopLossPips,trlinloss);  break;   
          }           
       

P.S. You're going to take all my battle robot out of my hands, which I'm eating right now. I've been working on it with interruptions and exits to proper algorithms since September 2010. See thread - Avalanche.

 

Continuation of the code in the trailer as it is larger than the permitted size:

 
     
Files:
itdakxijrxj.mq4  11 kb
[Deleted]  
Roman.:

Yes. This is my code. I already wrote you that I use it in my rollover martin as follows:

If the last trade (pose) was closed in profit, then we zero out the number of flips (Iteration) and start with the starting lot, if in deficit,

we calculate the number of losing trades in a row and open in the opposite direction by increasing the volume.

This is a netting version of Avalanche (see the branch with the same name ), i.e. market order is closed (at position flip on increased volumes) and the opposite market order is opened on larger volumes depending on the share scheme. Here is my working part of the code. Edit it to suit your needs if you have a similar exp algorithm. I do not understand anything in your question. You can ask regardless of the situation in the branch "Any newbie question ...", but describe your question in more detail, because nothing (at least for me) is clear - at all.

P.S. This is how you're going to lure out all my battle robot, which I'm eating out of my hand. I've been working on it with interruptions and exits to proper algorithms since September 2010. See thread - Avalanche.


I've already asked in the "any newbie question" thread and there is silence.

The situation is that when this code closes the deal in loss, it remembers the minus balance, and when it closes the deal in the plus, and the plus is less than the balance, it zeroed Sum_Loss, and I need that it would not zeroed, and mowed down.

So this is how it works now:

it checks a closed order, if the profit of closed order is less than zero, then this profit is added to Sum_Loss, and so on until the profit of open trade exceeds (will be more than) Sum_Loss, when reached, the trade is closed, and Sum_Loss is zeroed and the cycle begins again.

I need:

order closed in minus, its minus profit was added to Sum_Loss, then if the next deal closed with a positive profit, Sum_Loss is reduced by the amount received from the profit, which means that the next open order Sum_Loss is already a smaller amount, and so on until the order profit is higher than Sum_Loss, and then Sum_Loss is cleared and a new cycle starts.

Sum_Loss = 0;

1st closed order: Profit (-50) < 0

Sum_Loss + profit (Sum_Loss + (-50))

Sum_Loss = -50;

2nd closed order: Profit (+40) > 0 and Sum_Loss < 0

Sum_Loss + profit (Sum_Loss + 40)

Sum_Loss = -10

 
belck:

1. I have already addressed the "any beginner's question" thread and there is silence.

The situation is that when this code closes a deal in loss, it remembers the negative balance, but when it closes a deal in profit, and the plus is less than the balance, it resets Sum_Loss, but I need it not to reset, but to mow down.

2. So, right now this is how it works:

it checks a closed order, if the profit of closed order is less than zero, then this profit is added to Sum_Loss, and so on until the profit of open deal does not exceed (will be more than) Sum_Loss, when reached, the deal is closed, and Sum_Loss is reset and the cycle begins again.

3. I need:

The order closed with a minus, its minus profit was added to Sum_Loss; then if the next deal closed with a positive profit, Sum_Loss is decreased by the amount received from the profit; it means that the next open deal will receive a smaller Sum_Loss amount, and so on, until the order profit is larger than Sum_Loss, and then Sum_Loss is cleared and a new cycle starts.

Sum_Loss = 0;

1st closed order: Profit (-50) < 0

Sum_Loss + profit (Sum_Loss + (-50))

Sum_Loss = -50;

2nd closed order: Profit (+40) > 0 and Sum_Loss < 0

Sum_Loss + profit (Sum_Loss + 40)

Sum_Loss = -10

1. apply again - there are people there who will definitely help. Having previously put your code in that branch... (as it is)

2. That's right, because this is Avalanche's basic algorithm.

3. All this and describe it in the beginner's thread with your code for this algorithm. People will correct it. Start writing code on mcl4 yourself consistently and quietly.

If you can't do it yourself, go to the "Jobs" section of the fifth forum - they write there for food...

Will write code from scratch for free ONLY if you have personal interest!

Everything.

 

You can exhale... :-)

Bunch of orders this time... :-) closed in profit!

DoublePlus and vse_dlya_sela_J_OsMA_kh owls + my variant (also with description of TS) with settings - in branch.

[Deleted]  
Roman.:

You can exhale... :-)

Bunch of orders this time... :-) closed in profit!

DoublePlus and vse_dlya_sela_J_OsMA_kh owls + my variant (also with description of TS) with settings - in the branch.


And you personally know how to program?

I'm not much of a programmer.

Maybe you can still help me complete the code?

[Deleted]  
Roman.:

You can exhale... :-)

Bunch of orders this time... :-) closed in profit!

And regrets that no lots were added before the profit? :))
 
belck:

I'm not much of a programmer.

Maybe you can help me finish the code after all?

If you don't do it yourself, contact the "Jobs" service at mql5.com - they will quickly complete any whims you may have.