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

 
Vladimir Pastushak:

ZeroMemory (...) initializes array of string type with NULL value


Good afternoon. Here is the question. Written an EA, attached a trailing stop to it, compiled.......... doesn't work:))))). I rebooted my computer, tweaked source code, it works. Started to adjust it via input parameters, again it does not work, or rather it changed once, and that's all.......... May be the wind is glitchy or i messed up somewhere again. I am attaching the source code.

//+------------------------------------------------------------------+
//|                                                        test8.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.1;
extern int    TakeProfit      = 100;
extern int    StopLoss        = 50;
extern int    Magic           = 777; 
extern int    Slippage        = 3;

//-------------------------------------------------------------------
extern string TMA             = "Параметры индикатора TMA";
extern string TimeFrame       = "current time frame";
extern int    HalfLength      = 56; 
extern int    Price           = PRICE_CLOSE;
extern double ATRMultiplier   = 2.0;
extern int    ATRPeriod       = 100;
extern bool   Interpolate     = true;
extern int    TrailingStop    = 50; 
extern int    TrailingStep    = 20;
int    timeprev        = 0;
//-------------------------------------------------------------------
double PriceHigh, PriceLow, SL ,TP;
int ticket;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if (Digits == 3 || Digits == 5);
   {
       TakeProfit   *=10;
       Slippage     *=10;
       TrailingStop *=10;
       TrailingStep *=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];
  
    PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);  
    PriceLow  = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);  
    
    if (CountSell() == 0 && Bid >= PriceHigh)
    {
        ticket = OrderSend(Symbol(), OP_SELL, lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);  
        if (ticket > 0)
        {
            TP = NormalizeDouble(Bid - TakeProfit*Point, Digits);
            SL = NormalizeDouble(Bid + StopLoss*Point, Digits);
            if (OrderSelect(ticket, SELECT_BY_TICKET)) 
                if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0));
                    Print("Ошибк амодификации ордера на продажу!");
        } else Print("Ошибка открытия ордера на продаду!"); 
    }
  

    if (CountBuy() == 0 && Ask <= PriceLow)
    
      {
         ticket = OrderSend(Symbol(), OP_BUY, lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);  
         if (ticket > 0)
           { 
                SL = NormalizeDouble(Ask - StopLoss*Point, Digits);
                TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);
                if (OrderSelect(ticket, SELECT_BY_TICKET)) 
                if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0));
                  Print ("Ошибка модификации ордера на покупку!");
           }      else Print("Ошибка открытия ордера на покупкку!");
      }
     
     Trailing();    
    }
//+------------------------------------------------------------------+
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)
            {
               if (Bid - OrderOpenPrice() > TrailingStop*Point || OrderStopLoss() == 0)
               {
                   if (OrderStopLoss() < Bid-(TrailingStop+TrailingStep)*Point || OrderStopLoss() == 0)
                   {
                      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble (Bid-TrailingStop*Point, Digits), 0, 0))
                         Print ("Ошибка модификации ордера на покупку!");
                   } 
               }
            }
            
            if (OrderType() == OP_SELL)
            {
                if (OrderOpenPrice() - Ask > TrailingStop*Point || OrderStopLoss() == 0)
                {
                    if (OrderStopLoss() > Ask + (TrailingStop+TrailingStep)*Point || OrderStopLoss() == 0)
                    {
                        if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble( Ask + TrailingStop*Point, Digits), 0, 0))
                             Print ("Ошибка модификации ордера на родажу!"); 
                    }
                    
                }
            }
         
         }
      }
    }
}
  
//+------------------------------------------------------------------+


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 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);
  }
//-----------------------------------------------------------------------------------------------  
  
       
       
  
 

Good afternoon. My question is as follows.I wrote an EA, attached a trailing stop to it, compiled.......... does not work:))))). More precisely trailing stop works, but the profit previously prescribed does not work, what is the reason?

Как самому создать советника или индикатор - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
Как самому создать советника или индикатор - Алгоритмический трейдинг, торговые роботы - Справка по MetaTrader 5
  • www.metatrader5.com
Для разработки торговых систем в платформу встроен собственный язык программирования MetaQuotes Language 5 ( MQL5 ), среда разработки MetaEditor и...
 
danil77783:

Good afternoon. Question is as follows. Written an EA, attached a trailing stop to it, compiled.......... doesn't work:))))) I rebooted my computer, tweaked source code, it works. Started to adjust it via input parameters, again it does not work, or rather it changed once, and that's all.......... May be the wind is glitchy or i messed up somewhere again. I am attaching the source code.


 if (timeprev == Time [0])
{
         timeprev = Time [0];
return;

}

 
Vladimir Pastushak:


still doesn't put up a tickprofit.... Please take another look.

 
danil77783:

still doesn't put up a tickprofit.... Please check again.


In the trailing function you set take profit 0 for all orders, but when you open it, you set the right take profit.

Please read the logic line by line,

open an order, set a stop and a take

start trailing stop take 0

replace 0 in the trailing order with OrderTakeProfit()

 

Now he doesn't put a stoplight

 
danil77783:

Now it doesn't put a stoplight


Show me the new code.

 
Vladimir Pastushak:

Show the new code





//+------------------------------------------------------------------+
//|                                                        test8.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.1;
extern int    TakeProfit      = 50;
extern int    StopLoss        = 50;
extern int    Magic           = 777; 
extern int    Slippage        = 3;

//-------------------------------------------------------------------
extern string TMA             = "Параметры индикатора TMA";
extern string TimeFrame       = "current time frame";
extern int    HalfLength      = 56; 
extern int    Price           = PRICE_CLOSE;
extern double ATRMultiplier   = 2.0;
extern int    ATRPeriod       = 100;
extern bool   Interpolate     = true;
extern int    TrailingStop    = 50; 
extern int    TrailingStep    = 20;
int    timeprev        = 0;
//-------------------------------------------------------------------
double PriceHigh, PriceLow, SL ,TP;
int ticket;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if (Digits == 3 || Digits == 5);
   {
       TakeProfit   *=10;
       Slippage     *=10;
       TrailingStop *=10;
       TrailingStep *=10;
     
       
   }  
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
    if (timeprev == Time [0])
    {
         timeprev = Time [0];
         return;
  }
    PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);  
    PriceLow  = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);  
    
    if (CountSell() == 0 && Bid >= PriceHigh)
    {
        ticket = OrderSend(Symbol(), OP_SELL, lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);  
        if (ticket > 0)
        {
            TP = NormalizeDouble(Bid - TakeProfit*Point, Digits);
           
            if (OrderSelect(ticket, SELECT_BY_TICKET)) 
                if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0));
                    Print("Ошибк амодификации ордера на продажу!");
        } else Print("Ошибка открытия ордера на продаду!"); 
    }
  

    if (CountBuy() == 0 && Ask <= PriceLow)
    
      {
         ticket = OrderSend(Symbol(), OP_BUY, lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);  
         if (ticket > 0)
           { 
               
                TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);
                if (OrderSelect(ticket, SELECT_BY_TICKET)) 
                if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0));
                  Print ("Ошибка модификации ордера на покупку!");
           }      else Print("Ошибка открытия ордера на покупкку!");
      }
     
     Trailing();    
    }
//+------------------------------------------------------------------+
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)
            {
               if (Bid - OrderOpenPrice() > TrailingStop*Point || OrderStopLoss() == 0)
               {
                   if (OrderStopLoss() < Bid-(TrailingStop+TrailingStep)*Point || OrderStopLoss() == OrderTakeProfit())
                   {
                      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble (Bid-TrailingStop*Point, Digits), 0, 0))
                         Print ("Ошибка модификации ордера на покупку!");
                   } 
               }
            }
            
            if (OrderType() == OP_SELL)
            {
                if (OrderOpenPrice() - Ask > TrailingStop*Point || OrderStopLoss() == 0)
                {
                    if (OrderStopLoss() > Ask + (TrailingStop+TrailingStep)*Point || OrderStopLoss() == OrderTakeProfit())
                    {
                        if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble( Ask + TrailingStop*Point, Digits), 0, 0))
                             Print ("Ошибка модификации ордера на родажу!"); 
                    }
                    
                }
            }
         
         }
      }
    }
}
  
//+------------------------------------------------------------------+


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 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);
  }
//-----------------------------------------------------------------------------------------------  
  
       
       
  
 
danil77783:





I told you clearly in trailing you put 0 instead of take

Check this option.

//+------------------------------------------------------------------+
//|                                                        test8.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.1;
extern int    TakeProfit      = 100;
extern int    StopLoss        = 50;
extern int    Magic           = 777; 
extern int    Slippage        = 3;

//-------------------------------------------------------------------
extern string TMA             = "Параметры индикатора TMA";
extern string TimeFrame       = "current time frame";
extern int    HalfLength      = 56; 
extern int    Price           = PRICE_CLOSE;
extern double ATRMultiplier   = 2.0;
extern int    ATRPeriod       = 100;
extern bool   Interpolate     = true;
extern int    TrailingStop    = 50; 
extern int    TrailingStep    = 20;
int    timeprev        = 0;
//-------------------------------------------------------------------
double PriceHigh, PriceLow, SL ,TP;
int ticket;


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if (Digits == 3 || Digits == 5);
   {
       TakeProfit   *=10;
       Slippage     *=10;
       TrailingStop *=10;
       TrailingStep *=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];
  
    PriceHigh = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 1, 0);  
    PriceLow  = iCustom(NULL, 0, "TMA_Fair", TimeFrame, HalfLength, Price, ATRMultiplier, ATRPeriod, Interpolate, 2, 0);  
    
    if (CountSell() == 0 && Bid >= PriceHigh)
    {
        ticket = OrderSend(Symbol(), OP_SELL, lots, Bid, Slippage, 0, 0, "TMA robot", Magic, 0, Red);  
        if (ticket > 0)
        {
            TP = NormalizeDouble(Bid - TakeProfit*Point, Digits);
            SL = NormalizeDouble(Bid + StopLoss*Point, Digits);
            if (OrderSelect(ticket, SELECT_BY_TICKET)) 
                if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0));
                    Print("Ошибк амодификации ордера на продажу!");
        } else Print("Ошибка открытия ордера на продаду!"); 
    }
  

    if (CountBuy() == 0 && Ask <= PriceLow)
    
      {
         ticket = OrderSend(Symbol(), OP_BUY, lots, Ask, Slippage, 0, 0, "TMA robot", Magic, 0, Blue);  
         if (ticket > 0)
           { 
                SL = NormalizeDouble(Ask - StopLoss*Point, Digits);
                TP = NormalizeDouble(Ask + TakeProfit*Point, Digits);
                if (OrderSelect(ticket, SELECT_BY_TICKET)) 
                if(!OrderModify(ticket, OrderOpenPrice(), SL, TP, 0));
                  Print ("Ошибка модификации ордера на покупку!");
           }      else Print("Ошибка открытия ордера на покупкку!");
      }
     
     Trailing();    
    }
//+------------------------------------------------------------------+
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)
            {
               if (Bid - OrderOpenPrice() > TrailingStop*Point || OrderStopLoss() == 0)
               {
                   if (OrderStopLoss() < Bid-(TrailingStop+TrailingStep)*Point || OrderStopLoss() == 0)
                   {
                      if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble (Bid-TrailingStop*Point, Digits),OrderTakeProfit(), 0))  //          --------------------------
                         Print ("Ошибка модификации ордера на покупку!");
                   } 
               }
            }
            
            if (OrderType() == OP_SELL)
            {
                if (OrderOpenPrice() - Ask > TrailingStop*Point || OrderStopLoss() == 0)
                {
                    if (OrderStopLoss() > Ask + (TrailingStop+TrailingStep)*Point || OrderStopLoss() == 0)
                    {
                        if (!OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble( Ask + TrailingStop*Point, Digits),OrderTakeProfit(), 0))   //          --------------------------
                             Print ("Ошибка модификации ордера на родажу!"); 
                    }
                    
                }
            }
         
         }
      }
    }
}
  
//+------------------------------------------------------------------+


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 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);
  }
//-----------------------------------------------------------------------------------------------  
 
Hello.
Please help me to compare the price of the MA on the first bar with the prices of the MA on the previous four bars. If the price has increased and the difference is greater than N fill in the buffer. I am trying to
    
    MA_1  = iMA(NULL, 0, ma_period, 0, ma_method,applied_price, i+1);
    MA_2  = iMA(NULL, 0, ma_period, 0, ma_method,applied_price, i+2);
    MA_3  = iMA(NULL, 0, ma_period, 0, ma_method,applied_price, i+3);
    if(MA_1>MA_2)
    {
    double N_=0.005;
    BarCount=4;
    BUL=false;
   for(int il=i+1;il<=BarCount;il++)
     {
      if(iMA(NULL, 0, ma_period, 0, ma_method,applied_price, i)-iMA(NULL, 0, ma_period, 0, ma_method,applied_price, i+il)>=N_ )
      {BUL=true;break;}
     }
     RefreshRates();
      if(BUL)
       {
      BufferUP[i+1]=low[i+1]-distance*MyPoint;
      BUL=false;
    
       }
       }

Reason: