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

 

I need help - I have trailing stops - 3 orders, but the example of trailing from video tutorials :) only for unlinked orders, in my case they are linked by algorithm, i.e. takeprofit is calculated by sum of three orders, or one if I got into a trend. Well, I have thought of something but my Expert Advisor has not started to earn more - it has started to earn the same amount of orders but I get 2-3 times less trades compared to my previous EA without trailing. So my trailing is not trailing but some nonsense. How should I place it on linked orders? Can someone give me an idea? I'm afraid I can't think of anything else. Here is the result of my "trailing" - it is shown in blue:

The result for 1 test is attached. Is there a trailing stop there or not? I don't understand. Why was not the profit for the same period increased? Only the number of deals decreased by 2-3 times?

//+------------------------------------------------------------------+
//|                                     BLACKJACK&HOOKERS TrailX.mq4 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern double  Lots           = 0.01;
extern int     TakeProfit     = 5;
extern int     Step           = 2;

extern int     TrailingStep   = 3;
extern int     TrailingStop   = 1;

extern int     MaPeriod       = 200;
extern int     MaShift        = 1;

extern int     Magic          = 123;
extern int     Slippage       = 5;

int timeprev=0;

extern double price,op,cn,tp;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(Digits == 3 || Digits == 5)
      TakeProfit     *= 10;
      Step           *= 10;
      TrailingStep   *= 10;
      TrailingStop   *= 10;
      Slippage       *= 10;

      
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{  if (timeprev == Time[0]) return;
   timeprev = Time[0];
   double maprice=iMA(Symbol(),0,MaPeriod,MaShift,MODE_SMA,PRICE_CLOSE,1);
   op=CalculateProfit();
   cn=CountTrades();
   tp=TakeProfit;
   if(tp>TakeProfit)
   {
      TakeProfit+=tp;
   }

   
 

 
   if (cn==0 && CountBuy() + CountSell() == 0 && Ask > maprice)
   {
      if (OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "", Magic, 0, Blue)<0)
            Print("Не удалось открыть ордер на покупку");
            
   }
   
   if (cn==0 && CountBuy() + CountSell() == 0 && Bid < maprice)
   {
      if (OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "", Magic, 0, Red)<0)
            Print("Не удалось открыть ордер на продажу");
            
   }
   

   
   if(cn==1 && CountBuy()==1)//CountBuy()==1 && 
   {
      price=FindLastBuyPrice();
      if((price-Ask)>=Step*Point)
      {
         if(OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"",Magic,0,Red)<1)
            Print("Не удалось открыть ордер на продажу");
      }
   }
   else if(cn==1 && CountSell()==1)//CountSell()==1 && 
   {
      price=FindLastSellPrice();
      if((Bid-price)>=Step*Point)
      {
         if(OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"",Magic,0,Blue)<1)
            Print("Не удалось открыть ордер на покупку");
      }
   }
   
   
   
   if(cn==2 && CountBuy()==1 && CountSell()==1)//CountBuy() + CountSell()==2 && 
   {
      price=FindLastSellPrice();
      if((price-Bid)>=Step*Point)
      {
         if(OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"",Magic,0,Red)<1)
               Print("Не удалось открыть ордер на продажу");
               
      }
      else 
      price=FindLastSellPrice();
      if((Bid-price)>=Step*Point)
      {
         if(OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"",Magic,0,Blue)<1)
            Print("Не удалось открыть ордер на покупку");
           
      }
   }
   else if(cn==2 && CountSell()==1 && CountBuy()==1)//CountSell() + CountBuy()==2 && 
   {
      price=FindLastBuyPrice();
      if((Ask-price)>=Step*Point)
      {
         if(OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,0,0,"",Magic,0,Blue)<1)
               Print("Не удалось открыть ордер на продажу");
               
      }
      else 
      price=FindLastBuyPrice();
      if((price-Ask)>=Step*Point)
      {
         if(OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,0,0,"",Magic,0,Red)<1)
            Print("Не удалось открыть ордер на покупку");
           
      }
   }
   
   Trailing();

   

   if (op>=tp)
   {
         CloseAll();    
   }
   
   

 
   
   
   
   
   
   
   






}    
//---------------------------------------------------------------------------------------
//   double Equity() //или OrderProfit() - эти идеи в работе и задуманы как автоподбор лота (без мартингейла) для снижения рисков от контрдвижения (интервенций) рынка 
//   {
//      double eqv=0;
//      eqv+=AccountEquity();
//      return(eqv);     
//   }
//---------------------------------------------------------------------------------------
void Trailing()

{
   for (int i=OrdersTotal() -1; i>=0; i--)
   {
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
         {
            if (OrderType() == OP_BUY)
            
            {
               price=FindLastBuyPrice();   
               if (Bid - price > (TakeProfit+TrailingStep)*Point)
               {
                  {
                     tp=NormalizeDouble((TakeProfit+TrailingStep)*Point, Digits);
                  }
               }
               if (price - (TakeProfit-TrailingStop)*Point < Bid - (TakeProfit+TrailingStep)*Point)
               {
                  {
                     tp=NormalizeDouble((TakeProfit-TrailingStop)*Point, Digits);
                  }
               }
            }
            
            if (OrderType() == OP_SELL)
            {
               price=FindLastSellPrice();
               if (price - Ask > (TakeProfit+TrailingStep)*Point)
               {  
                  {
                     tp=NormalizeDouble((TakeProfit+TrailingStep)*Point, Digits);
                  }
               }
               if (price - (TakeProfit-TrailingStop)*Point > Ask + (TakeProfit+TrailingStep)*Point)
               {  
                  {
                     tp=NormalizeDouble((TakeProfit-TrailingStop)*Point, Digits);
                  }
               }
            }
         }
      }
   }
}
//---------------------------------------------------------------------------------------
double CalculateProfit()
  {
   double oprofit=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY || OrderType()==OP_SELL)
              {
               oprofit+=OrderProfit();
              }
           }
        }
     }
   return(oprofit);
  }
//--------------------------------------------------------------------------------------
void CloseAll()
  {
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY)
              {
               if(!OrderClose(OrderTicket(),OrderLots(),Bid,Slippage))
                  Print("Не удалось закрыть ордер на покупку");
              }
            if(OrderType()==OP_SELL)
              {
               if(!OrderClose(OrderTicket(),OrderLots(),Ask,Slippage))
                  Print("Не удалось закрыть ордер на продажу");
              }
           }
        }
     }
  }
//---------------------------------------------------------------------------------------------------
double FindLastBuyPrice()
  {
   int oldticket,ticket= 0;
   double oldopenprice = 0;
   for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)
     {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_BUY)
           {
            oldticket=OrderTicket();
            if(oldticket>ticket)
              {
               ticket=oldticket;
               oldopenprice=OrderOpenPrice();
              }
           }
        }
     }
   return(oldopenprice);
  }
//---------------------------------------------------------------------------------------------------
double FindLastSellPrice()
  {
   int oldticket,ticket= 0;
   double oldopenprice = 0;
   for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)
     {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_SELL)
           {
            oldticket=OrderTicket();
            if(oldticket>ticket)
              {
               ticket=oldticket;
               oldopenprice=OrderOpenPrice();
              }
           }
        }
     }
   return(oldopenprice);
  }
//----------------------------------------------------------------------------------------------
int CountBuy()
  {
   int count=0;
   for(int trade=OrdersTotal()-1; trade>=0; trade--)
     {
      if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_BUY)
            count++;
        }
     }
   return(count);
  }
//----------------------------------------------------------------------------------------------
int CountSell()
  {
   int count=0;
   for(int trade=OrdersTotal()-1; trade>=0; trade--)
     {
      if(OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==OP_SELL)
            count++;
        }
     }
   return(count);
  }
//+---------------------------------------------------------------------------------+
int CountTrades()
{
    int count=0;
    for (int i=OrdersTotal()-1; i>=0; i--)
      {  
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
               if(OrderType() == OP_BUY || OrderType() == OP_SELL)
                  count++; 
         }
      }
      return(count);
}
//----------------------------------------------------------------------------------+
int FindLastOrderType()
{
      for(int i = OrdersTotal()-1; i>=0; i--)
      {
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
            if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
            return(OrderType());
         } 
      }
      return(-1);
}
//----------------------------------------------------------------------------------+



Автоматический трейдинг и тестирование торговых стратегий
Автоматический трейдинг и тестирование торговых стратегий
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
 
geratdc:

I need help - I have stop flips - 3 orders, but the example of trailing only for unrelated orders, in my case they are linked by an algorithm, i.e. takeprofit is based on the sum of three orders, or one if you are in a trend. Well, I have thought of something but my Expert Advisor has not started to earn more - it has started to earn the same amount of orders but I get 2-3 times less trades compared to my previous EA without trailing. So my trailing is not trailing but some nonsense. How should I place it on linked orders? Can someone give me an idea? I'm afraid I can't think of anything else, here's the result of my "trailing" - highlighted in red:


Do you think someone will understand your code as a scribble?
 
Vitaly Muzichenko:
Do you think someone is going to understand your scribbled code?

How should it be displayed? Well, I can't throw in a piece of code, otherwise it would be unclear what's what.
 
geratdc:

How do you show it? Well, I can't throw in a piece of code, otherwise it would be unclear what's what.

At least like this:


 
Vitaly Muzichenko:

At least that's the way it is:



Someone's redone it. That's certainly better, thank you.
 


Friends, I'm studying MQL4 and decided to write an EA for Lazy Trader system.
The EA is written, but it doesn't work correctly. The error I see is that orders are not closed by time. It may be that there are some other errors.


Please help me find these errors and give me feedback on the code you see.

Here are the rules of the system I wrote the Expert Advisor for:

1/ At the beginning of the week wait for the first four-hour candle to close.
2/ We put pending Buy Stop and Sell Stop orders 20 pips above the High and 20 pips below Low of this candlestick.
3/ Stop Loss should be set at the level of the opposite order. Take Profit is not placed.
4/ When the order reaches a profit, equal to the stop loss, we transfer the stop to Breakeven (we transfer the stop loss of the position to its opening price).
5/ The second order after the activation of the first, DO NOT REMOVE!
6/ At the end of the week we remove / close all orders, regardless of their profit / loss.

Thanks for your help:)

I am attaching a file with EA code

Files:
 
ivan-baaton:


Friends, I'm studying MQL4 and decided to write an EA for Lazy Trader system.
The EA is written, but it doesn't work correctly. The error I see is that orders are not closed by time. It may be that there are some other errors.


Please help me find these errors and give me feedback on the code you see.

Here are the rules of the system I wrote the Expert Advisor for:

1/ At the beginning of the week wait for the first four-hour candle to close.
2/ We put pending Buy Stop and Sell Stop orders 20 pips above the High and 20 pips below Low of this candlestick.
3/ Stop Loss should be set at the level of the opposite order. Take Profit is not placed.
4/ When the order reaches a profit, equal to the stop loss, we transfer the stop to Breakeven (we transfer the stop loss of the position to its opening price).
5/ The second order after the activation of the first, DO NOT REMOVE!
6/ At the end of the week we remove / close all orders, regardless of their profit / loss.

Thanks for your help:)

I am attaching the file with the code of advisor.

TimeHour(TimeCurrent()) == DayTimeClose

Such an absolute equality may be very rare and if you close the week at 23, it would be better to close orders a bit earlier, at least for 15 minutes. I did not look for other errors. At first glance, it seems to be written quite accurately.

 
Alexey Viktorov:

This absolute equality may be very rare and if you close the week at 23, you'd better close orders a bit earlier, at least by 15 minutes. I have not looked for other errors. At first glance it seems to be written quite neatly.

Closing of the week is at 00:00, i.e. I close orders 1 hour earlier.


What is wrong in this code:TimeHour(TimeCurrent()) == DayTimeClose ?


I think there is an error somewhere in this code:


for (int i = OrdersTotal(); i>=0; i--)
{
if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES) == true && TimeHour(TimeCurrent()) == DayTimeClose && DayOfWeek() == 5 && (OrderType() == OP_SELL || OrderType() == OP_SELLSTOP) && OrderMagicNumber() == Magic)
{
ticket_sell = OrderClose(ticket_sell, Lots, Bid, 3, Red);
if (ticket_sell == false)
Print("Sell order not closed");
}

}


Thank you

 
ivan-baaton:

Closing of the week is at 00:00, i.e. I close orders 1 hour earlier.


What is wrong in this code:TimeHour(TimeCurrent()) == DayTimeClose ?


I think there is an error somewhere in this code:


for(int i = OrdersTotal(); i>=0; i--)
{
if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES) == true && TimeHour(TimeCurrent()) == DayTimeClose && DayOfWeek() == 5 && (OrderType() == OP_SELL || OrderType() == OP_SELLSTOP) && OrderMagicNumber() == Magic)
{
ticket_sell = OrderClose(ticket_sell, Lots, Bid, 3, Red);
if (ticket_sell == false)
Print("Sell order not closed");
}

}


Thanks

That's exactly what I pointed out. Although I see now that I was inattentive. I only saw TimeHour(TimeCurrent()) highlighted. == DayTimeClose.

But the fact that the loop counter is i and order k is selected, I didn't see that right away.

 
Alexey Viktorov:

That's exactly what I pointed out. Although I see now that I was inattentive. I saw only highlighted TimeHour(TimeCurrent()) == DayTimeClose.

But the fact that the loop counter is i and order k is selected, I didn't see that right away.


Yes, this K is also written in externalvariables in the upper header... Maybe it's the return value of some function...


Alexey, what can you say about my problem? I try to attach trailing stop to reverse orders. Have you encountered such a problem?

Reason: