TrailingStop from the EA not working

 

Hi,


I`ve been trying to create an EA but i am having trouble with the Trailing Stop, i have tried everything and it wont work, when i compile everything is fine, no errors, but when i simulate the Trailing Stop does nothing. I would like that everytime i am having 40points gain, my stop loss would go to my entry point.

//+------------------------------------------------------------------+
//| Include                                                          |
//+------------------------------------------------------------------+
#include <Expert\Expert.mqh>
//--- available signals
#include <Expert\Signal\SignalMACD.mqh>
#include <Expert\Signal\SignalMA.mqh>
//--- available trailing
#include <Expert\Trailing\TrailingFixedPips.mqh>
//--- available money management
#include <Expert\Money\MoneyFixedLot.mqh>
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
//--- inputs for expert
input string             Expert_Title                  ="random";     // Document name
ulong                    Expert_MagicNumber            =9999;        //
bool                     Expert_EveryTick              =false;       //
//--- inputs for main signal
input int                Signal_ThresholdOpen          =10;          // Signal threshold value to open [0...100]
input int                Signal_ThresholdClose         =10;          // Signal threshold value to close [0...100]
input double             Signal_PriceLevel             =0.0;         // Price level to execute a deal
input double             Signal_StopLevel              =150.0;       // Stop Loss level (in points)
input double             Signal_TakeLevel              =90.0;        // Take Profit level (in points)
input int                Signal_Expiration             =4;           // Expiration of pending orders (in bars)
input int                Signal_MACD_PeriodFast        =12;          // MACD(12,24,9,PRICE_CLOSE) Period of fast EMA
input int                Signal_MACD_PeriodSlow        =24;          // MACD(12,24,9,PRICE_CLOSE) Period of slow EMA
input int                Signal_MACD_PeriodSignal      =9;           // MACD(12,24,9,PRICE_CLOSE) Period of averaging of difference
input ENUM_APPLIED_PRICE Signal_MACD_Applied           =PRICE_CLOSE; // MACD(12,24,9,PRICE_CLOSE) Prices series
input double             Signal_MACD_Weight            =1.0;         // MACD(12,24,9,PRICE_CLOSE) Weight [0...1.0]
input int                Signal_MA_PeriodMA            =17;          // Moving Average(9,0,MODE_SMA,...) Period of averaging
input int                Signal_MA_Shift               =0;           // Moving Average(9,0,MODE_SMA,...) Time shift
input ENUM_MA_METHOD     Signal_MA_Method              =MODE_SMA;    // Moving Average(9,0,MODE_SMA,...) Method of averaging
input ENUM_APPLIED_PRICE Signal_MA_Applied             =PRICE_CLOSE; // Moving Average(9,0,MODE_SMA,...) Prices series
input double             Signal_MA_Weight              =1.0;         // Moving Average(9,0,MODE_SMA,...) Weight [0...1.0]
//--- inputs for trailing
input int                Trailing_FixedPips_StopLevel  =40;          // Stop Loss trailing level (in points)
input int                Trailing_FixedPips_ProfitLevel=90;          // Take Profit trailing level (in points)
//--- inputs for money
input double             Money_FixLot_Percent          =10.0;        // Percent
input double             Money_FixLot_Lots             =25.0;         // Fixed volume
//+------------------------------------------------------------------+
//| Global expert object                                             |
//+------------------------------------------------------------------+
CExpert ExtExpert;
//+------------------------------------------------------------------+
//| Initialization function of the expert                            |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Initializing expert
   if(!ExtExpert.Init(Symbol(),PERIOD_M5,Expert_EveryTick,Expert_MagicNumber))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing expert");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- Creating signal
   CExpertSignal *signal=new CExpertSignal;
   if(signal==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating signal");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//---
   ExtExpert.InitSignal(signal);
   signal.ThresholdOpen(Signal_ThresholdOpen);
   signal.ThresholdClose(Signal_ThresholdClose);
   signal.PriceLevel(Signal_PriceLevel);
   signal.StopLevel(Signal_StopLevel);
   signal.TakeLevel(Signal_TakeLevel);
   signal.Expiration(Signal_Expiration);
//--- Creating filter CSignalMACD
   CSignalMACD *filter0=new CSignalMACD;
   if(filter0==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating filter0");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
   signal.AddFilter(filter0);
//--- Set filter parameters
   filter0.PeriodFast(Signal_MACD_PeriodFast);
   filter0.PeriodSlow(Signal_MACD_PeriodSlow);
   filter0.PeriodSignal(Signal_MACD_PeriodSignal);
   filter0.Applied(Signal_MACD_Applied);
   filter0.Weight(Signal_MACD_Weight);
//--- Creating filter CSignalMA
   CSignalMA *filter1=new CSignalMA;
   if(filter1==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating filter1");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
   signal.AddFilter(filter1);
//--- Set filter parameters
   filter1.PeriodMA(Signal_MA_PeriodMA);
   filter1.Shift(Signal_MA_Shift);
   filter1.Method(Signal_MA_Method);
   filter1.Applied(Signal_MA_Applied);
   filter1.Weight(Signal_MA_Weight);
//--- Creation of trailing object
   CTrailingFixedPips *trailing=new CTrailingFixedPips;
   if(trailing==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating trailing");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- Add trailing to expert (will be deleted automatically))
   if(!ExtExpert.InitTrailing(trailing))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing trailing");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- Set trailing parameters
   trailing.StopLevel(Trailing_FixedPips_StopLevel);
   trailing.ProfitLevel(Trailing_FixedPips_ProfitLevel);
//--- Creation of money object
   CMoneyFixedLot *money=new CMoneyFixedLot;
   if(money==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating money");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- Add money to expert (will be deleted automatically))
   if(!ExtExpert.InitMoney(money))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing money");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- Set money parameters
   money.Percent(Money_FixLot_Percent);
   money.Lots(Money_FixLot_Lots);
//--- Check all trading objects parameters
   if(!ExtExpert.ValidationSettings())
     {
      //--- failed
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- Tuning of all necessary indicators
   if(!ExtExpert.InitIndicators())
     {
      //--- failed
      printf(__FUNCTION__+": error initializing indicators");
      ExtExpert.Deinit();
      return(INIT_FAILED);
     }
//--- ok
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Deinitialization function of the expert                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ExtExpert.Deinit();
  }
//+------------------------------------------------------------------+
//| "Tick" event handler function                                    |
//+------------------------------------------------------------------+
void OnTick()
  {
   if (PositionsTotal()==0)
      ExtExpert.OnTick();
  }
//+------------------------------------------------------------------+
//| "Trade" event handler function                                   |
//+------------------------------------------------------------------+
void OnTrade()
  {
   ExtExpert.OnTrade();
  }
//+------------------------------------------------------------------+
//| "Timer" event handler function                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
   ExtExpert.OnTimer();
  }
//+------------------------------------------------------------------+
 

To do this, you need to write your module for Trailing and connect it (instead of TrailingFixedPips).

Articles: MQL5 Wizard: How to Create a Module of Trailing of Open Positions

MQL5 Wizard: How to Create a Module of Trailing of Open Positions
MQL5 Wizard: How to Create a Module of Trailing of Open Positions
  • www.mql5.com
MetaTrader 5 has a powerful tool for quick checking of trade ideas. This is the generator of trade strategies MQL5 Wizard. The use of MQL5 Wizard for automatic creation of source code of Experts Advisors is described in the "MQL5 Wizard: Creating Expert Advisors without Programming" article. Openness of the system of generation of code allows...
 

Ok, i did exactly like the article told me, but now i am having errors when i use the module:

HG      0       02:42:05.581    Test (WIN$,M5) 2019.01.01 00:00:00   CExpertBase::SetPriceSeries: changing of timeseries is forbidden
KF      0       02:42:05.581    Test (WIN$,M5) 2019.01.01 00:00:00   CExpertBase::SetOtherSeries: changing of timeseries is forbidden
OG      0       02:42:05.581    Test (WIN$,M5) 2019.01.01 00:00:00   CExpertBase::InitIndicators: parameters of setting are not checked
OG      0       02:42:05.581    Test (WIN$,M5) 2019.01.01 00:00:00   CExpert::InitIndicators: error initialization indicators of trailing object
GD      0       02:42:05.581    Test (WIN$,M5) 2019.01.01 00:00:00   OnInit: error initializing indicators
RN      2       02:42:05.581    Tester  tester stopped because OnInit returns non-zero code

This is the code of the module, i copied from the article since download is available:

//+------------------------------------------------------------------+
//|                                               SampleTrailing.mqh |
//|                        Copyright 2010, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
//+------------------------------------------------------------------+
//| include files                                                    |
//+------------------------------------------------------------------+
#include <Expert\ExpertTrailing.mqh>
// wizard description start
//+------------------------------------------------------------------+
//| Description of the class                                         |
//| Title=Moving a position to a lossless level                      |
//| Type=Trailing                                                    |
//| Name=BreakEven                                                   |
//| Class=CSampleTrailing                                            |
//| Page=                                                            |
//| Parameter=Profit,int,20                                          |
//| Parameter=StopLevel,int,0                                        |
//+------------------------------------------------------------------+
// wizard description end
//+------------------------------------------------------------------+
//| Class CSampleTrailing.                                           |
//| Purpose: Class for trailing of open positions                    |
//|             by moving Stop order to a lossless level.            |
//|             Is derived from the CExpertTrailing class.           |
//+------------------------------------------------------------------+
class CSampleTrailing : public CExpertTrailing
  {
protected:
   int                m_profit;             // threshold level of profit
   int                m_stop_level;         // lossless level

public:
                      CSampleTrailing();
   //--- method of setting adjustable parameters
   void               Profit(int value)       { m_profit=value;     }
   void               StopLevel(int value)    { m_stop_level=value; }
   //--- method of validation of adjustable settings
   virtual bool       ValidationSettings();
   //--- methods of generation of position modification signals
   virtual bool       CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp);
   virtual bool       CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp);
  };
//+------------------------------------------------------------------+
//| Constructor CSampleTrailing.                                     |
//| INPUT:  no.                                                      |
//| OUTPUT: no.                                                      |
//| REMARK: no.                                                      |
//+------------------------------------------------------------------+
void CSampleTrailing::CSampleTrailing()
  {
//--- setting default values
   m_profit    =20;
   m_stop_level=0;
  }
//+------------------------------------------------------------------+
//| Check of adjustable parameters.                                  |
//| INPUT:  no.                                                      |
//| OUTPUT: true if the parameters are correct, false if not.        |
//| REMARK: no.                                                      |
//+------------------------------------------------------------------+
bool CSampleTrailing::ValidationSettings()
  {
//--- what if the Init has not been called?
   if(m_symbol==NULL) return(false);
//--- check of parameters
   if((m_profit-m_stop_level)*m_adjusted_point<=m_symbol.StopsLevel()*m_symbol.Point() && m_profit!=0.0)
     {
      printf(__FUNCTION__+": threshold level of profit must be greater than the level of setting stop orders");
      return(false);
     }
//--- ok
   return(true);
  }
//+------------------------------------------------------------------+
//| Check for modification of stop orders of a long position.        |
//| INPUT:  position - pointer to a position object,                 |
//|         sl       - link for a new price of stop loss order,      |
//|         tp       - link for a new price of take profit order.    |
//| OUTPUT: true if condition is satisfied, false if not.            |
//| REMARK: no.                                                      |
//+------------------------------------------------------------------+
bool CSampleTrailing::CheckTrailingStopLong(CPositionInfo* position,double& sl,double& tp)
  {
//--- check of pointer
   if(position==NULL) return(false);
//--- check of parameters
   if(m_profit==0.0)  return(false);
//--- already in a lossless zone?
   double open=position.PriceOpen();
   if(position.StopLoss()>=open) return(false);
//--- check of profit
   sl=EMPTY_VALUE;
   tp=EMPTY_VALUE;
   if(m_symbol.Bid()-open>m_profit*m_adjusted_point)
      sl=m_symbol.NormalizePrice(open+m_stop_level*m_adjusted_point);
//---
   return(sl!=EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
//| Check for modification of stop orders of a short position.       |
//| INPUT:  position - pointer to a position object,                 |
//|         sl       - link for a new price of stop loss order,      |
//|         tp       - link for a new take profit order.             |
//| OUTPUT: true if condition is satisfied, false if not.            |
//| REMARK: no.                                                      |
//+------------------------------------------------------------------+
bool CSampleTrailing::CheckTrailingStopShort(CPositionInfo* position,double& sl,double& tp)
  {
//--- check of pointer
   if(position==NULL) return(false);
//--- check of parameters
   if(m_profit==0.0)  return(false);
//--- already in a lossless zone?
   double open=position.PriceOpen();
   if(position.StopLoss()<=open) return(false);
//--- check of profit
   sl=EMPTY_VALUE;
   tp=EMPTY_VALUE;
   if(open-m_symbol.Ask()>m_profit*m_adjusted_point)
      sl=m_symbol.NormalizePrice(open-m_stop_level*m_adjusted_point);
//---
   return(sl!=EMPTY_VALUE);
  }
//+------------------------------------------------------------------+
 
Try this module here (trailing, as always, works only for profitable positions).
Files:
TrailingKVN.mqh  18 kb
 

I am sorry, i think i misunderstood things, i believe the word in english would be "breakeven", i need that everytime i reach 40 points of gain, my stop order gets moved to a lossless level and stay there.

I am really thankful for your patience

 
Leonardo Fernandez:

I am sorry, i think i misunderstood things, i believe the word in english would be "breakeven", i need that everytime i reach 40 points of gain, my stop order gets moved to a lossless level and stay there.

I am really thankful for your patience

Trailing Stop (min distance from price to Stop Loss, in pips)

Set this value 'Trailing Stop' to '40', and 'Trailing Step' to '1'.
 

it works now, but it will only work if i remove this line of code. I need this line, otherwise the EA will never wait for a trade to be fully complete, it will keep ending positions and starting others before it reaches loss or gain.


Anyway, thank you very much for your help.

void OnTick()
  {
   if (PositionsTotal()==0)
      ExtExpert.OnTick();
  }