I will write an advisor free of charge - page 18

 

Need help.

http://forum.mql4.com/ru/67309#1011467

Помогите добавить к текущему советник пирамидинг. - MQL4 форум
  • www.mql5.com
Помогите добавить к текущему советник пирамидинг. - MQL4 форум
 

Please advise: orders are not opened every day trawling does not work and open orders are closed not according to TP. What am I doing wrong ?


input int    StartHour    = 23;    // Время ачало торговли
input int    TakeProfit   = 40;    // TakeProfit
input int    StopLoss     = 40;    // StopLoss
input int    Lots         = 0.1;   // Лот для торговли
input int    Magic        = 22;    // Магическое число
input int    Trals        = 20;    // Дистанция тралинга в пунктах
input int    _Step        = 1;     // Шаг
input bool   _StepUse     = true;  // Использовать шаг или нет

void OnTick()
{
   static bool IsFirstTick = false;
   static int ticket = 0;
  
   double lot=Lot_Normalize(Symbol(),Lots,1);
   double sl= Dist_Normalize(Symbol(),Trals);
   double step= Dist_Normalize(Symbol(),_Step);
  
   int h= TimeHour(TimeCurrent());
   if(h == StartHour)
   {
    Alert("TimeHor: ", h);
    if (IsFirstTick == true)
      IsFirstTick = false;
     
      bool res;
      res= OrderSelect(ticket, SELECT_BY_TICKET);
      if(res == true)
      {
         if(OrderCloseTime() == 0)
         {
            bool res2;
            res2 = OrderClose(ticket, Lots, OrderClosePrice(), 10);
           
            if(res2 == false)
            {
               Alert("Error Closing Order #", ticket);
               } Alert("Closing Order #", ticket);
         }  
      }
       if(Open[0] < Open[StartHour])
      {
         ticket = OrderSend(Symbol(), OP_BUYLIMIT, Lots, High[1],10, Low[1]-StopLoss*Point, High[1]+TakeProfit*Point,"Set bu ForexRobot");
         Tralling_Stop(OrderSymbol(),Magic,sl,step,_StepUse);
         if(ticket < 0)
         {
           Alert("Error Sending Order!");
         } Alert("Sending Order! BUY_LIMIT");
       }
       else
       {
         ticket = OrderSend(Symbol(), OP_SELLLIMIT, Lots, Low[1],10, High[1]+StopLoss*Point, Low[1]+TakeProfit*Point,"Set bu ForexRobot");
         Tralling_Stop(OrderSymbol(),Magic,sl,step,_StepUse);
         if(ticket < 0)
         {
           Alert("Error Sending Order!");
         } Alert("Sending Order! SEL_LLIMIT");
    }  
}
 
}  

double Dist_Normalize(string Smv, int _Distancia)
{
 int Dig= int(MarketInfo(Smv,MODE_DIGITS));
 double Pip=MarketInfo(Smv,MODE_POINT);
 if(Dig==3 || Dig==5)
   return NormalizeDouble(_Distancia*10*Pip,Dig);
 else return NormalizeDouble(_Distancia*Pip,Dig);
 } 


double Lot_Normalize(string Smv, double _lot, double _mult)
{
 double minlot=MarketInfo(Smv,MODE_MINLOT);
 double maxlot=MarketInfo(Smv,MODE_MAXLOT);
 double steplot=MarketInfo(Smv,MODE_LOTSTEP);
 double lot= _lot*_mult;
 if(lot<=minlot) lot+minlot;
 else if(lot>=maxlot) lot=minlot;
 else if(lot>minlot && lot<maxlot)
  {
    int k=int((lot-minlot)/steplot);
    lot=NormalizeDouble(minlot+k*steplot,2);
  }
  return(lot);




void Tralling_Stop(string Smv, int _Magic, double _Tral, double _Step, bool _Step_Use)
{
  int Dig=int(MarketInfo(_Symbol,MODE_DIGITS));
  for(int pos=OrdersTotal()-1; pos>=0;pos--)
    {
      if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Smv &&
      OrderMagicNumber()==_Magic && OrderType()<2)
        {
          double SLPrice;
          if(OrderType()==OP_BUY)
            {
              if(_Step_Use)
              {
                RefreshRates();
                if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral+_Step,Dig))
                {
                  SLPrice=NormalizeDouble(Ask-_Tral,Dig);
                  if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
                   Alert("Error modifi Order!: ",GetLastError());
                  }
                 }
               else
                 {
                  RefreshRates();
                  if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral,Dig))
                    {
                     SLPrice=NormalizeDouble(Bid+_Tral,Dig);
                     if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
                     Alert("Error modifi Order!: ",GetLastError());
                 }
             }
          }
       }
    }
 }            

 
MIR_KAZAN:

Please advise: orders are not opened every day trawling does not work and open orders are closed not according to TP. What am I doing wrong ?


input int    StartHour    = 23;    // Время ачало торговли
input int    TakeProfit   = 40;    // TakeProfit
input int    StopLoss     = 40;    // StopLoss
input int    Lots         = 0.1;   // Лот для торговли
input int    Magic        = 22;    // Магическое число
input int    Trals        = 20;    // Дистанция тралинга в пунктах
input int    _Step        = 1;     // Шаг
input bool   _StepUse     = true;  // Использовать шаг или нет

void OnTick()
{
 ......
 

if (IsFirstTick == true)

IsFirstTick = false;

I would replace this piece with

if (TM!=Time[0])
{
   TM = Time[0];
......
}

Where the TM variable is declared as DateTime outside the OnTick() function, i.e. it is global for this module.

I do not understand this code: if(Open[0] < Open[StartHour])

The StartHour equals 23 and it suggests that the open price of the zero bar will be compared to the open price of the 23rd bar before it. Well, ok, maybe it's a trick of the Expert Advisor.

But this design is not appropriate at all.

      res= OrderSelect(ticket, SELECT_BY_TICKET);
      if(res == true)
      { 
         if(OrderCloseTime() == 0)
         {
            bool res2;
            res2 = OrderClose(ticket, Lots, OrderClosePrice(), 10);
            
            if(res2 == false)
            {
               Alert("Error Closing Order #", ticket);
               } Alert("Closing Order #", ticket);
         }   
      }

What if the ticket variable is equal to zero, or has the EA been reinitialized and this variable has been reset by default?

 
StartHour is the time at which the EA should run. It should be one o'clock in the morning. Why doesn't the trawling work?
 
MIR_KAZAN:
The StartHour is the time when the EA should work. It should be 1:00 a.m. Why does the trawling not work?

You need to analyse the code to understand why it does not work.

Try to insertthe Print("Tralling_Stop")function into theTralling_Stop() function, and see if this message (Tralling_Stop) appears in the log, if not, then this function is not called. If so, analyze the function Tralling_Stop() itself, maybe it contains some logical errors.

In general, wherever there are logical if conditions, insert Print(" condition 1" ), Print(" condition 2" ), etc. Run the Expert Advisor in the strategy tester and in the journal you can trace the logic of your EA.

 
vitales:

You need to analyse the code to understand why it does not work.

Try to insertthe Print("Tralling_Stop")function into theTralling_Stop() function, and see if this message (Tralling_Stop) appears in the log, if not, then this function is not called. If yes, analyze the function Tralling_Stop() itself - maybe there are some logical errors in it.

In general, wherever there are logical if conditions, insert Print(" condition 1" ), Print(" condition 2" ), etc. Run the Expert Advisor in the Strategy Tester and in the log you can trace the logic of your EA.


I have tried to rewrite it but it still does not work as I need. The orders are not opened when I want them to be, then they are not trilling. According to the idea, the Expert Advisor should work this way: at the close of the last candle in one day (at 00:00) it should open two pending orders: High (for buy) and Low (for sell) and then just trill them.

input int     StartHour    = 1;     // Начало торговли
input int     TakeProfit   = 40;    // TakeProfit
input int     StopLoss     = 10;    // StopLoss
extern double Lots         = 0.1;   // Лот для торговли
input int     Magic        = 22;    // Магическое число
input int     Trals        = 5;     // Дистанция тралинга в пунктах
input int     _Step        = 1;     // Шаг
input bool    _StepUse     = false; // Использовать шаг или неT

void OnTick()
{
   static bool IsFirstTick = false;
  
   Trailing();
  
   if (StartHour != Hour()) { return;}
   if (OrdersTotal()>0)
   {
    OrderSend(Symbol(), OP_BUYLIMIT, Lots, High[1],10, Low[1]-StopLoss*Point, High[1]+TakeProfit*Point,"Set bu ForexRobot",Magic);
    OrderSend(Symbol(), OP_SELLLIMIT, Lots, Low[1],10, High[1]+StopLoss*Point, Low[1]+TakeProfit*Point,"Set bu ForexRobot",Magic);                    
   }
}           

//+------------------------------------------------------------------+ 
void Trailing()
{
  if (_StepUse)
{
  for (int trall=0; trall<OrdersTotal(); trall++) {
    if (!(OrderSelect(trall, SELECT_BY_POS, MODE_TRADES))) continue;
    if (OrderSymbol() != Symbol()) continue;      
 
    if (OrderType() == OP_BUY ) {
      if (Bid-OrderOpenPrice() > StopLoss*Point || OrderMagicNumber()==Magic) {
        if (OrderStopLoss() < Bid-(StopLoss+_Step-1)*Point || OrderStopLoss() == 0) {
          OrderModify(OrderTicket(), OrderOpenPrice(), Bid-StopLoss*Point, OrderTakeProfit(), 0, Blue);
       }
      }
    }
 
    if (OrderType() == OP_SELL) {
     if (OrderOpenPrice()-Ask > StopLoss*Point || OrderMagicNumber()==Magic) {
        if (OrderStopLoss() > Ask+(StopLoss+_Step-1)*Point || OrderStopLoss() == 0) {
          OrderModify(OrderTicket(), OrderOpenPrice(), Ask+StopLoss*Point, OrderTakeProfit(), 0, Blue);
        }
     }
    }
  }
 }
}
//+------------------------------------------------------------------+

 
MIR_KAZAN:

Try

if (StartHour != Hour()) { return;} 

Replace with:

if (StartHour != TimeHour(Time[0])) { return;}//Если час текущей свечи не равен StartHour то выход из функции и тогда ниже написанный код выполнятся не будет, в том числе и трейлинг стоп. 
 if (OrdersTotal()>0)
{
....
}

Replace with:

if (OrdersTotal()==0) 
{
    bool rezult = false;
    rezult=OrderSend(Symbol(), OP_BUYLIMIT, Lots, High[1],10, Low[1]-StopLoss*Point, High[1]+TakeProfit*Point,"Set bu ForexRobot",Magic);
    if (!rezult) Print("Ошибка открытия ордера BUY LIMIT");
    rezult = OrderSend(Symbol(), OP_SELLLIMIT, Lots, Low[1],10, High[1]+StopLoss*Point, Low[1]+TakeProfit*Point,"Set bu ForexRobot",Magic);
    if (!rezult) Print("Ошибка открытия ордера SELL LIMIT"); 
//для работы в реале надо сделать более детальную проверку ошибок 

} else Trailing();

In addition, the prices must be normalized using NormalizeDouble(). That is, instead ofLow[1]-StopLoss*Point you must write NormalizeDouble(Low[1]-StopLoss*Point,Digits()).

Also, according to your code, if the _StepUse variable is equal to false, your trailing stop will not work. Look closely at the code of the Trailing() function

void Trailing()
{
  if (_StepUse)//если false то код внутри скобок выполнятся не будет.
  {
   ......

  }
}// Скорее всего вы этот код просто бездумно скопировали от куда нибудь, даже не понимая как он работает.
 
vitales:

Try

Replace with:

Replace with:

In addition, the prices must be normalized using NormalizeDouble(). That is, instead ofLow[1]-StopLoss*Point you must write NormalizeDouble(Low[1]-StopLoss*Point,Digits()).

Also, according to your code, if the _StepUse variable is equal to false, your trailing stop will not work. Look closely at the code of the Trailing() function.

Are you in contact? Send me a message to http://vk.com/computerwizard116. I don't know how to solve the EA problem anymore. On my demo account I've been working on this strategy for a week

And it works. And in testing, this rascal does not even close the order to the takeout point(((((( In the photo, you can see that the price went beyond the takeout point and went back, but it closed in a loss, dammit !(((

Why is he doing that?

Files:
 
MIR_KAZAN:

Are you in contact? Email me at http://vk.com/computerwizard116. I don't know how to solve the EA problem anymore. I've been using this strategy for a week on a demo account

and it works. But when testing, this rascal does not even close the order to takeaway. (((((( In the photo, you can see the price went beyond the takeaway and went back, but it closed in a loss.

Why is it doing that?

I am not in contact.

Take profit and Stop lossorders do not depend on the adviser, they are executed on the broker's server. The EA only sets the take profit and stop loss, not executes them. Check if the take profit was already set after the price reached this value. In other words, the order was opened first, and then the price was moving back and forth, and then the take profit was set.

 
vitales:

I am not in contact.

The execution of take profit and stop lossorders does not depend on the EA, they are executed on the broker's server. The EA only sets the take and stop orders, not executes them. Check if the take profit was already set after the price reached this value. In other words, the order was opened first, then the price went back and forth, and then the take profit was set.

How do I paste TP, Sl in OrderSend, so that SL was High of previous candle and TP was Low of previous one + TakeProfit?