Questions from Beginners MQL5 MT5 MetaTrader 5 - page 710

 
Kirill Andreev:
not working, sadly.
ShortModified and LongModified methods.
 
Vladimir Karputov:
ShortModified and LongModified methods.
class CSampleExpert
  {
protected:
   double            m_adjusted_point;             // point value adjusted for 3 or 5 points
   CTrade            m_trade;                      // trading object
   CSymbolInfo       m_symbol;                     // symbol info object
   CPositionInfo     m_position;                   // trade position object
   CAccountInfo      m_account;                    // account info wrapper
   //--- indicators
   int               m_handle_macd;                // MACD indicator handle
   int               m_handle_ema;                 // moving average indicator handle
   //--- indicator buffers
   double            m_buff_MACD_main[];           // MACD indicator main buffer
   double            m_buff_MACD_signal[];         // MACD indicator signal buffer
   double            m_buff_EMA[];                 // EMA indicator buffer
   //--- indicator data for processing
   double            m_macd_current;
   double            m_macd_previous;
   double            m_signal_current;
   double            m_signal_previous;
   double            m_ema_current;
   double            m_ema_previous;
   //---
   double            m_macd_open_level;
   double            m_macd_close_level;
   double            m_traling_stop;
   double            m_take_profit;

public:
                     CSampleExpert(void);
                    ~CSampleExpert(void);
   bool              Init(void);
   void              Deinit(void);
   bool              Processing(void);

protected:
   bool              InitCheckParameters(const int digits_adjust);
   bool              InitIndicators(void);
   bool              LongClosed(void);
   bool              ShortClosed(void);
   bool              LongModified(void);
   bool              ShortModified(void);
   bool              LongOpened(void);
   bool              ShortOpened(void);
  };

They are entered in the class. I need to add them as a separate function .... ?

I can't figure out how to make them. Tried to find examples of adding existing trailing classes, couldn't find any.

 
Kirill Andreev:
class CSampleExpert
  {
protected:
   double            m_adjusted_point;             // point value adjusted for 3 or 5 points
   CTrade            m_trade;                      // trading object
   CSymbolInfo       m_symbol;                     // symbol info object
   CPositionInfo     m_position;                   // trade position object
   CAccountInfo      m_account;                    // account info wrapper
   //--- indicators
   int               m_handle_macd;                // MACD indicator handle
   int               m_handle_ema;                 // moving average indicator handle
   //--- indicator buffers
   double            m_buff_MACD_main[];           // MACD indicator main buffer
   double            m_buff_MACD_signal[];         // MACD indicator signal buffer
   double            m_buff_EMA[];                 // EMA indicator buffer
   //--- indicator data for processing
   double            m_macd_current;
   double            m_macd_previous;
   double            m_signal_current;
   double            m_signal_previous;
   double            m_ema_current;
   double            m_ema_previous;
   //---
   double            m_macd_open_level;
   double            m_macd_close_level;
   double            m_traling_stop;
   double            m_take_profit;

public:
                     CSampleExpert(void);
                    ~CSampleExpert(void);
   bool              Init(void);
   void              Deinit(void);
   bool              Processing(void);

protected:
   bool              InitCheckParameters(const int digits_adjust);
   bool              InitIndicators(void);
   bool              LongClosed(void);
   bool              ShortClosed(void);
   bool              LongModified(void);
   bool              ShortModified(void);
   bool              LongOpened(void);
   bool              ShortOpened(void);
  };

They are entered in the class. I need to add them as a separate function .... ?

I can't figure out how to make them. Tried to find examples of adding existing trailing classes, couldn't find any.

You just need to copy them into your code.
 
Vladimir Karputov:
You just need to copy it into your code.

void LongModified()
  {

double m_traling_stop=InpTrailingStop*m_adjusted_point;
   bool res=false;
//--- check for trailing stop
   if(InpTrailingStop>0)  
     {
      if(m_symbol.Bid()-m_position.PriceOpen()>m_adjusted_point*InpTrailingStop)
        {
         double sl=NormalizeDouble(m_symbol.Bid()-m_traling_stop,m_symbol.Digits());
         double tp=m_position.TakeProfit();
         if(m_position.StopLoss()<sl || m_position.StopLoss()==0.0)
           {
            //--- modify position
            if(m_trade.PositionModify(Symbol(),sl,tp))
               printf("Long position by %s to be modified",Symbol());
            else
              {
               printf("Error modifying position by %s : '%s'",Symbol(),m_trade.ResultComment());
               printf("Modify parameters : SL=%f,TP=%f",sl,tp);
              }
            //--- modified and must exit from expert
            res=true;
           }
        }
     }
//--- result
   return(res);
  }  

 

 

gives an error

'return' - 'void' function returns a value traal.mq5 482 4

 
Kirill Andreev:

void LongModified()
  {

double m_traling_stop=InpTrailingStop*m_adjusted_point;
   bool res=false;
//--- check for trailing stop
   if(InpTrailingStop>0)  
     {
      if(m_symbol.Bid()-m_position.PriceOpen()>m_adjusted_point*InpTrailingStop)
        {
         double sl=NormalizeDouble(m_symbol.Bid()-m_traling_stop,m_symbol.Digits());
         double tp=m_position.TakeProfit();
         if(m_position.StopLoss()<sl || m_position.StopLoss()==0.0)
           {
            //--- modify position
            if(m_trade.PositionModify(Symbol(),sl,tp))
               printf("Long position by %s to be modified",Symbol());
            else
              {
               printf("Error modifying position by %s : '%s'",Symbol(),m_trade.ResultComment());
               printf("Modify parameters : SL=%f,TP=%f",sl,tp);
              }
            //--- modified and must exit from expert
            res=true;
           }
        }
     }
//--- result
   return(res);
  }  

 

 

gives an error

'return' - 'void' function returns a value traal.mq5 482 4

You can't copy it WITHOUT thinking. Look again at the original source.
 

Example of an EA: on a hadge account we open two opposite positions at once - without any stops.

There are two parameters in the EA settings:

  • TrailingStop (in pips)
  • TrailingStep (in pips)
TrailingStep protects against too frequent modifications:

//+------------------------------------------------------------------+
//|                                                 TrailingStop.mq5 |
//|                              Copyright © 2016, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2016, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
#property description "Пример TrailingStop"
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
//--- input parameters
input ushort   InpTrailingStop    =10;       // TrailingStop (in pips)
input ushort   InpTrailingStep    =5;        // TrailingStep (in pips)
//---
double         ExtTrailingStop=0.0;
double         ExtTrailingStep=0.0;
ulong          m_magic=15489;                // magic number
ENUM_ACCOUNT_MARGIN_MODE m_margin_mode;
bool           FirstStart=true;              // true - first start
double         m_adjusted_point;             // point value adjusted for 3 or 5 points
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   SetMarginMode();
   if(!IsHedging())
     {
      Print("Hedging only!");
      return(INIT_FAILED);
     }
   m_symbol.Name(Symbol());                  // sets symbol name
   m_symbol.Refresh();                       // refreshes the symbol data
   if(!RefreshRates())
     {
      Print("Error RefreshRates. Bid=",DoubleToString(m_symbol.Bid(),Digits()),
            ", Ask=",DoubleToString(m_symbol.Ask(),Digits()));
      return(INIT_FAILED);
     }
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=digits_adjust*m_symbol.Point();
   ExtTrailingStop=InpTrailingStop*m_adjusted_point;
   ExtTrailingStep=InpTrailingStep*m_adjusted_point;

   m_trade.SetExpertMagicNumber(m_magic);    // sets magic number

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

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(FirstStart)
     {
      m_trade.Buy(0.01);
      m_trade.Sell(0.01);
      FirstStart=false;
     }
//--- TrailingStop
   if(!RefreshRates())
      return;

//--- при таком методе мы будет сюда попадать на каждом тике.
   for(int i=PositionsTotal()-1;i>=0;i--)
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)
           {
            //--- TrailingStop -> подтягивание StopLoss у ПРИБЫЛЬНОЙ позиции
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               //--- когда у позиции ещё нет StopLoss
               if(m_position.StopLoss()==0)
                 {
                  //--- пока StopLoss равен 0.0, TrailingStep не учитываем
                  if(m_symbol.Bid()-ExtTrailingStop>m_position.PriceOpen())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),m_position.PriceOpen(),0.0);
                    }
                 }
               //--- у позиции уже есть StopLoss
               else
                 {
                  //--- теперь TrailingStep нужно учитывать, иначе мы будет модифицировать
                  //--- поизцию НА КАЖДОМ ТИКЕ, а это ПЛОХО
                  if(m_symbol.Bid()-ExtTrailingStop-ExtTrailingStep>m_position.StopLoss())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),
                                            NormalizeDouble(m_symbol.Bid()-ExtTrailingStop,m_symbol.Digits()),0.0);
                    }
                 }
              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)
              {
               //--- когда у позиции ещё нет StopLoss
               if(m_position.StopLoss()==0)
                 {
                  //--- пока StopLoss равен 0.0, TrailingStep не учитываем
                  if(m_symbol.Ask()+ExtTrailingStop<m_position.PriceOpen())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),m_position.PriceOpen(),0.0);
                    }
                 }
               //--- у позиции уже есть StopLoss
               else
                 {
                  //--- теперь TrailingStep нужно учитывать, иначе мы будет модифицировать
                  //--- поизцию НА КАЖДОМ ТИКЕ, а это ПЛОХО
                  if(m_symbol.Bid()+ExtTrailingStop+ExtTrailingStep<m_position.StopLoss())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),
                                            NormalizeDouble(m_symbol.Ask()+ExtTrailingStop,m_symbol.Digits()),0.0);
                    }
                 }
              }
           }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void SetMarginMode(void)
  {
   m_margin_mode=(ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHedging(void)
  {
   return(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
      return(false);
//---
   return(true);
  }
//+------------------------------------------------------------------+
Files:
 
Vladimir Karputov:

Example of an EA: on a hadge account we open two opposite positions at once - without any stops.

There are two parameters in the EA settings:

  • TrailingStop (in pips)
  • TrailingStep (in pips)
TrailingStep protects against too frequent modifications:

//+------------------------------------------------------------------+
//|                                                 TrailingStop.mq5 |
//|                              Copyright © 2016, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2016, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
#property description "Пример TrailingStop"
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>  
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
//--- input parameters
input ushort   InpTrailingStop    =10;       // TrailingStop (in pips)
input ushort   InpTrailingStep    =5;        // TrailingStep (in pips)
//---
double         ExtTrailingStop=0.0;
double         ExtTrailingStep=0.0;
ulong          m_magic=15489;                // magic number
ENUM_ACCOUNT_MARGIN_MODE m_margin_mode;
bool           FirstStart=true;              // true - first start
double         m_adjusted_point;             // point value adjusted for 3 or 5 points
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   SetMarginMode();
   if(!IsHedging())
     {
      Print("Hedging only!");
      return(INIT_FAILED);
     }
   m_symbol.Name(Symbol());                  // sets symbol name
   m_symbol.Refresh();                       // refreshes the symbol data
   if(!RefreshRates())
     {
      Print("Error RefreshRates. Bid=",DoubleToString(m_symbol.Bid(),Digits()),
            ", Ask=",DoubleToString(m_symbol.Ask(),Digits()));
      return(INIT_FAILED);
     }
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)
      digits_adjust=10;
   m_adjusted_point=digits_adjust*m_symbol.Point();
   ExtTrailingStop=InpTrailingStop*m_adjusted_point;
   ExtTrailingStep=InpTrailingStep*m_adjusted_point;

   m_trade.SetExpertMagicNumber(m_magic);    // sets magic number

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

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(FirstStart)
     {
      m_trade.Buy(0.01);
      m_trade.Sell(0.01);
      FirstStart=false;
     }
//--- TrailingStop
   if(!RefreshRates())
      return;

//--- при таком методе мы будет сюда попадать на каждом тике.
   for(int i=PositionsTotal()-1;i>=0;i--)
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==Symbol() && m_position.Magic()==m_magic)
           {
            //--- TrailingStop -> подтягивание StopLoss у ПРИБЫЛЬНОЙ позиции
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               //--- когда у позиции ещё нет StopLoss
               if(m_position.StopLoss()==0)
                 {
                  //--- пока StopLoss равен 0.0, TrailingStep не учитываем
                  if(m_symbol.Bid()-ExtTrailingStop>m_position.PriceOpen())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),m_position.PriceOpen(),0.0);
                    }
                 }
               //--- у позиции уже есть StopLoss
               else
                 {
                  //--- теперь TrailingStep нужно учитывать, иначе мы будет модифицировать
                  //--- поизцию НА КАЖДОМ ТИКЕ, а это ПЛОХО
                  if(m_symbol.Bid()-ExtTrailingStop-ExtTrailingStep>m_position.StopLoss())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),
                                            NormalizeDouble(m_symbol.Bid()-ExtTrailingStop,m_symbol.Digits()),0.0);
                    }
                 }
              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)
              {
               //--- когда у позиции ещё нет StopLoss
               if(m_position.StopLoss()==0)
                 {
                  //--- пока StopLoss равен 0.0, TrailingStep не учитываем
                  if(m_symbol.Ask()+ExtTrailingStop<m_position.PriceOpen())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),m_position.PriceOpen(),0.0);
                    }
                 }
               //--- у позиции уже есть StopLoss
               else
                 {
                  //--- теперь TrailingStep нужно учитывать, иначе мы будет модифицировать
                  //--- поизцию НА КАЖДОМ ТИКЕ, а это ПЛОХО
                  if(m_symbol.Bid()+ExtTrailingStop+ExtTrailingStep<m_position.StopLoss())
                    {
                     //--- модификация позиции
                     m_trade.PositionModify(m_position.Ticket(),
                                            NormalizeDouble(m_symbol.Ask()+ExtTrailingStop,m_symbol.Digits()),0.0);
                    }
                 }
              }
           }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void SetMarginMode(void)
  {
   m_margin_mode=(ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool IsHedging(void)
  {
   return(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
      return(false);
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
      return(false);
//---
   return(true);
  }
//+------------------------------------------------------------------+


Thank you, it worked even though it didn't work the first time!!!
 
I wonder if there are three maxima (minima), then the index of which one will give ArrayMaximum(ArrayMinimum)?
 
Vladimir:
I wonder, if there are three maxima (minima), which one will index ArrayMaximum (ArrayMinimum)?
The maximum (minimum) one. This function does not have more than one output value.
 
Vitalie Postolache:
The maximum (minimum) value. This function does not have more than one output value.
That's what I'm asking. There are five numbers in the array: 1.1012 1.1013 1.1013 1.1012, which of the elements will the function consider the maximum? None of them, there are three equally big ones. Answer options: the first encountered, the last encountered, any of the maximal. You can come up with more options if you want. The choice should be reflected in the function description in the help (documentation), but I haven't found it.
Reason: