Trailing Panel

Author: Copyright © 2020, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Trailing Panel
ÿþ//+------------------------------------------------------------------+

//|                                               Trailing Panel.mq5 |

//|                              Copyright © 2020, Vladimir Karputov |

//|                     https://www.mql5.com/ru/market/product/43516 |

//+------------------------------------------------------------------+

#property copyright "Copyright © 2020, Vladimir Karputov"

#property link      "https://www.mql5.com/ru/market/product/43516"

#property version   "1.000"

//---

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>

//---

CPositionInfo  m_position;                   // object of CPositionInfo class

CTrade         m_trade;                      // object of CTrade class

CSymbolInfo    m_symbol;                     // object of CSymbolInfo class

//---

#include <Controls\Dialog.mqh>

#include <Controls\Button.mqh>

//+------------------------------------------------------------------+

//| defines                                                          |

//+------------------------------------------------------------------+

//--- indents and gaps

#define INDENT_LEFT                         (11)      // indent from left (with allowance for border width)

#define INDENT_TOP                          (11)      // indent from top (with allowance for border width)

//--- for buttons

#define BUTTON_WIDTH                        (70)      // size by X coordinate

#define BUTTON_HEIGHT                       (20)      // size by Y coordinate

//+------------------------------------------------------------------+

//| Class CControlsDialog                                            |

//| Usage: main dialog of the Controls application                   |

//+------------------------------------------------------------------+

class CControlsDialog : public CAppDialog

  {

private:

   CButton           m_button_pause_start;            // the button object

   //--- input parameters

   ushort            m_TrailingFrequency;             // Trailing, in seconds (< "10" -> only on a new bar)

   ushort            m_TrailingStop;                  // Trailing Stop (min distance from price to Stop Loss, in pips

   ushort            m_TrailingStep;                  // Trailing Step, in pips (1.00045-1.00055=1 pips)

   ulong             m_Deviation;                     // Deviation, in points (1.00045-1.00055=10 points)

   bool              m_AllMagic;                      // Trailing All Magic

   ulong             m_OnlyMagic;                     // Trailing Only Magic number (if 'Trailing All Magic' -> false)

   bool              m_PositionMagic;                 // Use Magic number from position

   //---

   bool              m_PrintLog;                      // Print log

   ulong             m_Magic;                         // Trailing Panel: Magic number



public:

                     CControlsDialog(void);

                    ~CControlsDialog(void);

   //--- create

   virtual bool      Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2);

   //--- init

   int               Init(const ushort Inp_TrailingFrequency,

                          const ushort Inp_TrailingStop,

                          const ushort Inp_TrailingStep,

                          const ulong  Inp_Deviation,

                          const bool   Inp_AllMagic,

                          const ulong  Inp_OnlyMagic,

                          const bool   Inp_PositionMagic,

                          const bool   Inp_PrintLog,

                          const ulong  Inp_Magic);

   //--- chart event handler

   virtual bool      OnEvent(const int id,const long &lparam,const double &dparam,const string &sparam);

   //--- panel tick function

   void              OnTickPanel(void);



protected:

   //--- create dependent controls

   bool              CreateButtonPauseStart(void);

   //--- handlers of the dependent controls events

   void              OnClickButtonPauseStart(void);

   //--- refreshes the symbol quotes data

   bool              RefreshRates();

   //--- check Freeze and Stops levels

   bool              FreezeStopsLevels(double &level);

   //--- trailing positions

   void              Trailing(const double stop_level);

   //--- print CTrade result

   void              PrintResultModify(CTrade &trade,CSymbolInfo &symbol,CPositionInfo &position);

   //---

   double            m_trailing_stop;           // Trailing Stop           -> double

   double            m_trailing_step;           // Trailing Step           -> double

   double            m_adjusted_point;          // point value adjusted for 3 or 5 points

   datetime          m_last_trailing;           // "0" -> D'1970.01.01 00:00';

   datetime          m_prev_bars;               // "0" -> D'1970.01.01 00:00';



  };

//+------------------------------------------------------------------+

//| Event Handling                                                   |

//+------------------------------------------------------------------+

EVENT_MAP_BEGIN(CControlsDialog)

ON_EVENT(ON_CLICK,m_button_pause_start,OnClickButtonPauseStart)

EVENT_MAP_END(CAppDialog)

//+------------------------------------------------------------------+

//| Constructor                                                      |

//+------------------------------------------------------------------+

CControlsDialog::CControlsDialog(void) :

   m_TrailingFrequency(10),

   m_TrailingStop(25),

   m_TrailingStep(5),

   m_Deviation(10),

   m_AllMagic(true),

   m_OnlyMagic(200),

   m_PositionMagic(false),

   m_PrintLog(false),

   m_Magic(24571336)

  {

  }

//+------------------------------------------------------------------+

//| Destructor                                                       |

//+------------------------------------------------------------------+

CControlsDialog::~CControlsDialog(void)

  {

  }

//+------------------------------------------------------------------+

//| Create                                                           |

//+------------------------------------------------------------------+

bool CControlsDialog::Create(const long chart,const string name,const int subwin,const int x1,const int y1,const int x2,const int y2)

  {

   if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))

      return(false);

//--- create dependent controls

   if(!CreateButtonPauseStart())

      return(false);

//--- succeed

   return(true);

  }

//+------------------------------------------------------------------+

//| Init                                                             |

//+------------------------------------------------------------------+

int CControlsDialog::Init(const ushort Inp_TrailingFrequency,

                          const ushort Inp_TrailingStop,

                          const ushort Inp_TrailingStep,

                          const ulong Inp_Deviation,

                          const bool Inp_AllMagic,

                          const ulong Inp_OnlyMagic,

                          const bool Inp_PositionMagic,

                          const bool Inp_PrintLog,

                          const ulong Inp_Magic)

  {

   m_TrailingFrequency  = Inp_TrailingFrequency;

   m_TrailingStop       = Inp_TrailingStop;

   m_TrailingStep       = Inp_TrailingStep;

   m_Deviation          = Inp_Deviation;

   m_AllMagic           = Inp_AllMagic;

   m_OnlyMagic          = Inp_OnlyMagic;

   m_PositionMagic      = Inp_PositionMagic;

   m_PrintLog           = Inp_PrintLog;

   m_Magic              = Inp_Magic;

//---

   if(m_TrailingStop!=0 && m_TrailingStep==0)

     {

      string err_text=(TerminalInfoString(TERMINAL_LANGUAGE)=="Russian")?

                      ""@59;8=3 =52>7<>65=: ?0@0<5B@ \"Trailing Step\" @025= =C;N!":

                      "Trailing is not possible: parameter \"Trailing Step\" is zero!";

      //--- when testing, we will only output to the log about incorrect input parameters

      if(MQLInfoInteger(MQL_TESTER))

        {

         Print(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

         return(INIT_FAILED);

        }

      else // if the Expert Advisor is run on the chart, tell the user about the error

        {

         Alert(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

         return(INIT_PARAMETERS_INCORRECT);

        }

     }

//---

   if(!m_symbol.Name(Symbol())) // sets symbol name

     {

      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");

      return(INIT_FAILED);

     }

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(m_Magic);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(m_Deviation);

//--- 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=m_symbol.Point()*digits_adjust;



   m_trailing_stop         = m_TrailingStop          * m_adjusted_point;

   m_trailing_step         = m_TrailingStep          * m_adjusted_point;

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CControlsDialog::OnTickPanel(void)

  {

   if(m_button_pause_start.Pressed())

      return;

//---

   if(m_TrailingFrequency>=10) // trailing no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-m_last_trailing>10)

        {

         double level;

         if(FreezeStopsLevels(level))

            Trailing(level);

         else

            return;

         m_last_trailing=time_current;

        }

     }

//--- we work only at the time of the birth of new bar

   datetime time_0=iTime(m_symbol.Name(),Period(),0);

   if(time_0==m_prev_bars)

      return;

   m_prev_bars=time_0;

   if(m_TrailingFrequency<10) // trailing only at the time of the birth of new bar

     {

      double level;

      if(FreezeStopsLevels(level))

         Trailing(level);

     }

  }

//+------------------------------------------------------------------+

//| Create the "Close all" button                                    |

//+------------------------------------------------------------------+

bool CControlsDialog::CreateButtonPauseStart(void)

  {

//--- coordinates

   int x1=INDENT_LEFT;

   int y1=INDENT_TOP;

   int x2=x1+BUTTON_WIDTH;

   int y2=y1+BUTTON_HEIGHT;

//--- create

   if(!m_button_pause_start.Create(m_chart_id,m_name+"ButtonPauseStop",m_subwin,x1,y1,x2,y2))

      return(false);

   if(!m_button_pause_start.Text("Start"))

      return(false);

   if(!Add(m_button_pause_start))

      return(false);

   m_button_pause_start.Locking(true);

//--- succeed

   return(true);

  }

//+------------------------------------------------------------------+

//| Event handler                                                    |

//+------------------------------------------------------------------+

void CControlsDialog::OnClickButtonPauseStart(void)

  {

   bool pressed=m_button_pause_start.Pressed();

   if(m_button_pause_start.Pressed())

      m_button_pause_start.Text("Pause");

   else

      m_button_pause_start.Text("Start");

  }

//+------------------------------------------------------------------+

//| Refreshes the symbol quotes data                                 |

//+------------------------------------------------------------------+

bool CControlsDialog::RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      if(m_PrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");

      return(false);

     }

//--- protection against the return value of "zero"

   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)

     {

      if(m_PrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");

      return(false);

     }

//---

   return(true);

  }

//+------------------------------------------------------------------+

//| Check Freeze and Stops levels                                    |

//+------------------------------------------------------------------+

bool CControlsDialog::FreezeStopsLevels(double &level)

  {

//--- check Freeze and Stops levels

   /*

      Type of order/position  |  Activation price  |  Check

      ------------------------|--------------------|--------------------------------------------

      Buy Limit order         |  Ask               |  Ask-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

      Buy Stop order          |  Ask               |  OpenPrice-Ask  >= SYMBOL_TRADE_FREEZE_LEVEL

      Sell Limit order        |  Bid               |  OpenPrice-Bid  >= SYMBOL_TRADE_FREEZE_LEVEL

      Sell Stop order         |  Bid               |  Bid-OpenPrice  >= SYMBOL_TRADE_FREEZE_LEVEL

      Buy position            |  Bid               |  TakeProfit-Bid >= SYMBOL_TRADE_FREEZE_LEVEL

                              |                    |  Bid-StopLoss   >= SYMBOL_TRADE_FREEZE_LEVEL

      Sell position           |  Ask               |  Ask-TakeProfit >= SYMBOL_TRADE_FREEZE_LEVEL

                              |                    |  StopLoss-Ask   >= SYMBOL_TRADE_FREEZE_LEVEL



      Buying is done at the Ask price                 |  Selling is done at the Bid price

      ------------------------------------------------|----------------------------------

      TakeProfit        >= Bid                        |  TakeProfit        <= Ask

      StopLoss          <= Bid                        |  StopLoss          >= Ask

      TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL

      Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL

   */

   if(!RefreshRates() || !m_symbol.Refresh())

      return(false);

//--- FreezeLevel -> for pending order and modification

   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();

   if(freeze_level==0.0)

      freeze_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;

//--- StopsLevel -> for TakeProfit and StopLoss

   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();

   if(stop_level==0.0)

      stop_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;



   if(freeze_level<=0.0 || stop_level<=0.0)

      return(false);



   level=(freeze_level>stop_level)?freeze_level:stop_level;



   double spread=m_symbol.Spread()*m_symbol.Point()*3.0;

   level=(level>spread)?level:spread;

//---

   return(true);

  }

//+------------------------------------------------------------------+

//| Trailing                                                         |

//|   InpTrailingStop: min distance from price to Stop Loss          |

//+------------------------------------------------------------------+

void CControlsDialog::Trailing(const double stop_level)

  {

   /*

      Buying is done at the Ask price                 |  Selling is done at the Bid price

      ------------------------------------------------|----------------------------------

      TakeProfit        >= Bid                        |  TakeProfit        <= Ask

      StopLoss          <= Bid                        |  StopLoss          >= Ask

      TakeProfit - Bid  >= SYMBOL_TRADE_STOPS_LEVEL   |  Ask - TakeProfit  >= SYMBOL_TRADE_STOPS_LEVEL

      Bid - StopLoss    >= SYMBOL_TRADE_STOPS_LEVEL   |  StopLoss - Ask    >= SYMBOL_TRADE_STOPS_LEVEL

   */

   if(m_TrailingStop==0)

      return;

//---

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions

      if(m_position.SelectByIndex(i))

         if(m_position.Symbol()==m_symbol.Name() && ((m_AllMagic) || (!m_AllMagic && m_position.Magic()==m_OnlyMagic)))

           {

            if(m_PositionMagic)

               m_trade.SetExpertMagicNumber(m_position.Magic());

            //---

            double price_current = m_position.PriceCurrent();

            double price_open    = m_position.PriceOpen();

            double stop_loss     = m_position.StopLoss();

            double take_profit   = m_position.TakeProfit();

            double ask           = m_symbol.Ask();

            double bid           = m_symbol.Bid();

            //---

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(price_current-price_open>m_trailing_stop+m_trailing_step)

                  if(stop_loss<price_current-(m_trailing_stop+m_trailing_step))

                     if(m_trailing_stop>=stop_level && (take_profit-bid>=stop_level || take_profit==0.0))

                       {

                        if(!m_trade.PositionModify(m_position.Ticket(),

                                                   m_symbol.NormalizePrice(price_current-m_trailing_stop),

                                                   take_profit))

                           if(m_PrintLog)

                              Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify BUY ",m_position.Ticket(),

                                    " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),

                                    ", description of result: ",m_trade.ResultRetcodeDescription());

                        if(m_PrintLog)

                          {

                           RefreshRates();

                           m_position.SelectByIndex(i);

                           PrintResultModify(m_trade,m_symbol,m_position);

                          }

                        continue;

                       }

              }

            else

              {

               if(price_open-price_current>m_trailing_stop+m_trailing_step)

                  if((stop_loss>(price_current+(m_trailing_stop+m_trailing_step))) || (stop_loss==0))

                     if(m_trailing_stop>=stop_level && ask-take_profit>=stop_level)

                       {

                        if(!m_trade.PositionModify(m_position.Ticket(),

                                                   m_symbol.NormalizePrice(price_current+m_trailing_stop),

                                                   take_profit))

                           if(m_PrintLog)

                              Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify SELL ",m_position.Ticket(),

                                    " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),

                                    ", description of result: ",m_trade.ResultRetcodeDescription());

                        if(m_PrintLog)

                          {

                           RefreshRates();

                           m_position.SelectByIndex(i);

                           PrintResultModify(m_trade,m_symbol,m_position);

                          }

                       }

              }

           }

  }

//+------------------------------------------------------------------+

//| Print CTrade result                                              |

//+------------------------------------------------------------------+

void CControlsDialog::PrintResultModify(CTrade &trade,CSymbolInfo &symbol,CPositionInfo &position)

  {

   Print("File: ",__FILE__,", symbol: ",symbol.Name());

   Print("Code of request result: "+IntegerToString(trade.ResultRetcode()));

   Print("code of request result as a string: "+trade.ResultRetcodeDescription());

   Print("Deal ticket: "+IntegerToString(trade.ResultDeal()));

   Print("Order ticket: "+IntegerToString(trade.ResultOrder()));

   Print("Volume of deal or order: "+DoubleToString(trade.ResultVolume(),2));

   Print("Price, confirmed by broker: "+DoubleToString(trade.ResultPrice(),symbol.Digits()));

   Print("Current bid price: "+DoubleToString(symbol.Bid(),symbol.Digits())+" (the requote): "+DoubleToString(trade.ResultBid(),symbol.Digits()));

   Print("Current ask price: "+DoubleToString(symbol.Ask(),symbol.Digits())+" (the requote): "+DoubleToString(trade.ResultAsk(),symbol.Digits()));

   Print("Broker comment: "+trade.ResultComment());

   Print("Freeze Level: "+DoubleToString(symbol.FreezeLevel(),0),", Stops Level: "+DoubleToString(symbol.StopsLevel(),0));

   Print("Price of position opening: "+DoubleToString(position.PriceOpen(),symbol.Digits()));

   Print("Price of position's Stop Loss: "+DoubleToString(position.StopLoss(),symbol.Digits()));

   Print("Price of position's Take Profit: "+DoubleToString(position.TakeProfit(),symbol.Digits()));

   Print("Current price by position: "+DoubleToString(position.PriceCurrent(),symbol.Digits()));

  }

//+------------------------------------------------------------------+

//| Global Variables                                                 |

//+------------------------------------------------------------------+

CControlsDialog ExtDialog;

//--- input parameters

input ushort   InpTrailingFrequency = 10;          // Trailing, in seconds (< "10" -> only on a new bar)

input ushort   InpTrailingStop      = 25;          // Trailing Stop (min distance from price to Stop Loss, in pips

input ushort   InpTrailingStep      = 5;           // Trailing Step, in pips (1.00045-1.00055=1 pips)

input ulong    InpDeviation         = 10;          // Deviation, in points (1.00045-1.00055=10 points)

input bool     InpAllMagic          = true;        // Trailing All Magic

input ulong    InpOnlyMagic         = 200;         // Trailing Only Magic number (if 'Trailing All Magic' -> false)

input bool     InpPositionMagic     = false;       // Use Magic number from position

//---

input bool     InpPrintLog          = false;       // Print log

input ulong    InpMagic             = 24571336;    // Trailing Panel: Magic number

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//--- create application dialog

   if(!ExtDialog.Create(0,"Trailing Panel",0,40,40,170,111))

      return(INIT_FAILED);

   int init=ExtDialog.Init(InpTrailingFrequency,

                           InpTrailingStop,

                           InpTrailingStep,

                           InpDeviation,

                           InpAllMagic,

                           InpOnlyMagic,

                           InpPositionMagic,

                           InpPrintLog,

                           InpMagic);

   if(init!=INIT_SUCCEEDED)

      return(init);

//--- run application

   ExtDialog.Run();

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//--- destroy dialog

   ExtDialog.Destroy(reason);

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

   ExtDialog.OnTickPanel();

  }

//+------------------------------------------------------------------+

//| Expert chart event function                                      |

//+------------------------------------------------------------------+

void OnChartEvent(const int id,         // event ID

                  const long& lparam,   // event parameter of the long type

                  const double& dparam, // event parameter of the double type

                  const string& sparam) // event parameter of the string type

  {

   ExtDialog.ChartEvent(id,lparam,dparam,sparam);

  }

//+------------------------------------------------------------------+

Comments