Trailing Equity

Author: Copyright © 2019, Vladimir Karputov
Price Data Components
0 Views
0 Downloads
0 Favorites
Trailing Equity
ÿþ//+------------------------------------------------------------------+

//|                                              Trailing Equity.mq5 |

//|                              Copyright © 2019, Vladimir Karputov |

//|                                           http://wmua.ru/slesar/ |

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

#property copyright "Copyright © 2019, Vladimir Karputov"

#property link      "http://wmua.ru/slesar/"

#property version   "1.000"

/*

   barabashkakvn Trading engine 2.003

*/

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Trade\AccountInfo.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

CAccountInfo   m_account;                    // account info wrapper

//--- input parameters

input double   InpProfitPercentStart      = 1.0;      // Trailing start, in %

input double   InpProfitPercentRollback   = 0.5;      // Rollback for all closing, in %

//---

input ulong    InpMagic=22155098;   // Magic number

//---

ulong  ExtSlippage      = 10;                   // Slippage

bool   ExtNeedCloseAll  = false;                // "true" -> need to close all

string ExtPrefix        = "Trailing Equity. ";  // Prefix all OBJ_LABEL's

double ExtStartEquity=0.0;

double ExtRollbackEquity=0.0;

double ExtPercentStartCoeff=0.0;

double ExtPercentRollbackCoeff=0.0;

bool   ExtStarTrailing=false;                   // "true" -> start trailing

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

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

      return(INIT_FAILED);

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(InpMagic);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(ExtSlippage);

//---

   if(!LabelCreate(0,ExtPrefix+"Equity",0,5,35,CORNER_LEFT_UPPER,"Equity ") || 

      !LabelCreate(0,ExtPrefix+"Trailing start",0,5,50,CORNER_LEFT_UPPER,"Equity start ") || 

      !LabelCreate(0,ExtPrefix+"Rollback",0,5,65,CORNER_LEFT_UPPER,"Equity rollback "))

      return(INIT_FAILED);

//---

   ExtPercentStartCoeff=InpProfitPercentStart/100.0+1.0;

   ExtPercentRollbackCoeff=InpProfitPercentRollback/100.0+1.0;

//---

   double equity=m_account.Equity();



   ExtStartEquity=equity*ExtPercentStartCoeff;

   ExtRollbackEquity=equity*ExtPercentRollbackCoeff;

   LabelTextChange(0,ExtPrefix+"Equity","Equity "+DoubleToString(equity,2),clrBlueViolet);

   LabelTextChange(0,ExtPrefix+"Trailing start","Equity start "+DoubleToString(ExtStartEquity,2));

   LabelTextChange(0,ExtPrefix+"Rollback","Equity rollback "+DoubleToString(ExtRollbackEquity,2));

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

   ObjectsDeleteAll(0,ExtPrefix,0,OBJ_LABEL);

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//---

   if(ExtNeedCloseAll)

     {

      if(IsPositionExists())

        {

         CloseAllPositions();

         return;

        }

      else

        {

         ExtNeedCloseAll=false;  // "true" -> need to close all

        }

     }

//---

   double equity=m_account.Equity();

   LabelTextChange(0,ExtPrefix+"Equity","Equity "+DoubleToString(equity,2),clrBlueViolet);



   if(!IsPositionExists())

     {

      ExtStartEquity    = equity*ExtPercentStartCoeff;

      ExtRollbackEquity = equity*ExtPercentRollbackCoeff;

      LabelTextChange(0,ExtPrefix+"Trailing start","Equity start "+DoubleToString(ExtStartEquity,2));

      LabelTextChange(0,ExtPrefix+"Rollback","Equity rollback "+DoubleToString(ExtRollbackEquity,2));

      ExtStarTrailing=false;     // "true" -> start trailing

     }

   else

     {

      if(equity>(ExtStartEquity+ExtRollbackEquity)/2.0)

        {

         LabelTextChange(0,ExtPrefix+"Trailing start","Equity start "+DoubleToString(ExtStartEquity,2),clrRed);

         LabelTextChange(0,ExtPrefix+"Rollback","Equity rollback "+DoubleToString(ExtRollbackEquity,2),clrRed);

         ExtStarTrailing=true;   // "true" -> start trailing

        }

      if(equity>ExtStartEquity)

        {

         ExtStartEquity=equity;

         ExtRollbackEquity=equity/ExtPercentStartCoeff*ExtPercentRollbackCoeff;

         ExtStarTrailing=false;  // "true" -> start trailing

         LabelTextChange(0,ExtPrefix+"Trailing start","Equity start "+DoubleToString(ExtStartEquity,2));

         LabelTextChange(0,ExtPrefix+"Rollback","Equity rollback "+DoubleToString(ExtRollbackEquity,2));

         return;

        }

      if(ExtStarTrailing)

        {

         if(equity<=ExtRollbackEquity)

            ExtNeedCloseAll=true;  // "true" -> need to close all

        }

     }

//---

  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates(void)

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      Print("RefreshRates error");

      return(false);

     }

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

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

      return(false);

//---

   return(true);

  }

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

//| Is position exists                                               |

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

bool IsPositionExists(void)

  {

   for(int i=PositionsTotal()-1;i>=0;i--)

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

         return(true);

//---

   return(false);

  }

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

//| Close all positions                                              |

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

void CloseAllPositions(void)

  {

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

      if(m_position.SelectByIndex(i))     // selects the position by index for further access to its properties

         m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol

  }

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

//| Create a text label                                              | 

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

bool LabelCreate(const long              chart_ID=0,// chart's ID

                 const string            name="Label",             // label name 

                 const int               sub_window=0,             // subwindow index 

                 const int               x=0,                      // X coordinate 

                 const int               y=0,                      // Y coordinate 

                 const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // chart corner for anchoring 

                 const string            text="Label",             // text 

                 const string            font="Lucida Console",    // font 

                 const int               font_size=10,             // font size 

                 const color             clr=clrLime,              // color 

                 const double            angle=0.0,                // text slope 

                 const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type 

                 const bool              back=false,               // in the background 

                 const bool              selection=false,          // highlight to move 

                 const bool              hidden=true,              // hidden in the object list 

                 const long              z_order=0)                // priority for mouse click 

  {

//--- reset the error value 

   ResetLastError();

//--- create a text label 

   if(!ObjectCreate(chart_ID,name,OBJ_LABEL,sub_window,0,0))

     {

      Print(__FUNCTION__,

            ": failed to create text label! Error code = ",GetLastError());

      return(false);

     }

//--- set label coordinates 

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);

   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);

//--- set the chart's corner, relative to which point coordinates are defined 

   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);

//--- set the text 

   ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);

//--- set text font 

   ObjectSetString(chart_ID,name,OBJPROP_FONT,font);

//--- set font size 

   ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);

//--- set the slope angle of the text 

   ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);

//--- set anchor type 

   ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);

//--- set color 

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- display in the foreground (false) or background (true) 

   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);

//--- enable (true) or disable (false) the mode of moving the label by mouse 

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);

//--- hide (true) or display (false) graphical object name in the object list 

   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

//--- set the priority for receiving the event of a mouse click in the chart 

   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);

//--- successful execution 

   return(true);

  }

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

//| Change the label text                                            | 

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

bool LabelTextChange(const long   chart_ID=0,   // chart's ID 

                     const string name="Label", // object name 

                     const string text="Text",  // text 

                     const color  clr=clrLime)  // color 

  {

//--- reset the error value 

   ResetLastError();

//--- change object text 

   if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))

     {

      Print(__FUNCTION__,

            ": failed to change the text! Error code = ",GetLastError());

      return(false);

     }

//--- set color 

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- successful execution 

   return(true);

  }

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

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---