Close all Equity control

Author: Copyright © 2020, Vladimir Karputov
Miscellaneous
It opens Message Boxes to the user
0 Views
0 Downloads
0 Favorites
Close all Equity control
ÿþ//+------------------------------------------------------------------+

//|                                     Close all Equity control.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"

/*

   barabashkakvn Trading engine 3.144

*/

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\AccountInfo.mqh>

//---

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CAccountInfo   m_account;                    // account info wrapper

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

//| Enum Money Or Percentages                                        |

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

enum ENUM_MONEY_OR_PERCENTAGES

  {

   money=0,       // Money

   percentages=1, // Percentages

  };

//--- input parameters

input ushort                     InpSignalsFrequency           = 10;          // Search signals, in seconds (< '10' -> only on a new bar on Current Symbol)

input bool                       InpAllSymbols                 = true;        // All Symbol: ('true' -> all symbols, 'false' -> only Current Symbol)

input ENUM_MONEY_OR_PERCENTAGES  InpMoneyOrPercentages         = percentages; // Money Or Percentages:

input double                     InpVolumeMoneyOrPercentages   = 100.0;       // The value for 'Money Or Percentages'

input bool                       InpReset                      = false;       // Reset Start Equity

input ulong                      InpMagic                      = 0;           // Magic number ('0' -> all magic's)

//---

string   m_global_variable       = "Close all Equity control";

double   m_new_global_equity     = 0.0;

bool     m_need_close_all        = false;

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

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

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

   m_trade.SetExpertMagicNumber(InpMagic);

   m_trade.SetMarginMode();

   m_trade.SetDeviationInPoints(10);

//--- Global Variable

   bool     global_variable_check   = GlobalVariableCheck(m_global_variable);

   ResetLastError();

   double   prev_global_variable    = GlobalVariableGet(m_global_variable);

   int      last_error=GetLastError();

   double   equity                  = m_account.Equity();

   string   currency                = m_account.Currency();

//---

   if(InpReset)

     {

      GlobalVariableSet(m_global_variable,equity);

      m_new_global_equity=GlobalVariableGet(m_global_variable);

     }

   else

     {

      if(prev_global_variable==0.0) // first start

         GlobalVariableSet(m_global_variable,equity);

      m_new_global_equity=GlobalVariableGet(m_global_variable);

     }

//---

   string text="-";

   if(TerminalInfoString(TERMINAL_LANGUAGE)=="Russian")

     {

      text="@54K4CI55 7=0G5=85 Equity: "+DoubleToString(prev_global_variable,2)+" "+currency;

      if(prev_global_variable==0.0 || InpReset)

         text=text+", =>2>5 7=0G5=85 Equity: "+DoubleToString(m_new_global_equity,2)+" "+currency;

     }

   else

     {

      text="Previous Equity: "+DoubleToString(prev_global_variable,2)+" "+currency;

      if(prev_global_variable==0.0 || InpReset)

         text=text+", new Equity value: "+DoubleToString(m_new_global_equity,2)+" "+currency;

     }

   Print(text);

   MessageBox(text);

//---

   /*string arr_symbols[6]= {"EURUSD","USDJPY","GBPUSD","AUDUSD","EURPLN","GBPCAD"};

   for(int i=0; i<6; i++)

     {

      bool res=false;

      while(!res)

        {

         if(!SymbolInfoInteger(arr_symbols[i],SYMBOL_EXIST))

            res=true;

         else

            res=m_trade.Sell(0.10,arr_symbols[i]);

        }

      Sleep(1000*3600*5);

     }*/

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   if(m_need_close_all)

     {

      if(IsPositionExists())

        {

         CloseAllPositions();

         return;

        }

      else

        {

         m_need_close_all=false;

         GlobalVariableSet(m_global_variable,m_account.Equity());

         m_new_global_equity=GlobalVariableGet(m_global_variable);

         /*//---

         string arr_symbols[6]= {"EURUSD","USDJPY","GBPUSD","AUDUSD","EURPLN","GBPCAD"};

         for(int i=0; i<6; i++)

           {

            bool res=false;

            while(!res)

              {

               if(!SymbolInfoInteger(arr_symbols[i],SYMBOL_EXIST))

                  res=true;

               else

                  res=m_trade.Sell(0.10,arr_symbols[i]);

              }

            Sleep(1000*3600*5);

           }*/

        }

     }

//---

   if(InpSignalsFrequency>=10) // search for trading signals no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-m_last_signal>InpSignalsFrequency)

        {

         //--- search for trading signals

         SearchTradingSignals();

         m_last_signal=time_current;

        }

     }

   else

     {

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

      if(InpSignalsFrequency<10)

        {

         datetime time_0=iTime(Symbol(),Period(),0);

         if(time_0==m_prev_bars)

            return;

         m_prev_bars=time_0;

         if(InpSignalsFrequency<10) // search for trading signals only at the time of the birth of new bar

           {

            //--- search for trading signals

            SearchTradingSignals();

           }

        }

     }

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//---

  }

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

//| Profit all positions                                             |

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

double ProfitAllPositions(void)

  {

   double profit=0.0;

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

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

         if(m_position.Symbol()==Symbol() || InpAllSymbols)

            if(m_position.Magic()==InpMagic || InpMagic==0)

               profit+=m_position.Commission()+m_position.Swap()+m_position.Profit();

//---

   return(profit);

  }

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

//| 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

         if(m_position.Symbol()==Symbol() || InpAllSymbols)

            if(m_position.Magic()==InpMagic || InpMagic==0)

               return(true);

//---

   return(false);

  }

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

//| Close all positions                                              |

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

void CloseAllPositions()

  {

   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

         if(m_position.Symbol()==Symbol() || InpAllSymbols)

            if(m_position.Magic()==InpMagic || InpMagic==0)

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

  }

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

//| Search trading signals                                           |

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

void SearchTradingSignals(void)

  {

   if(InpVolumeMoneyOrPercentages<=0.0)

      return;

   double equity=m_account.Equity();

   double profit_all_positions=ProfitAllPositions();

   /*

   m_new_global_equity  ->    100%  $120 - 100%

   m_account.Equity()   ->    x%    $180 - x% -> 150%



   ProfitAllPositions() ->    100%

   m_account.Equity()   ->    x%

   */

   if(InpMoneyOrPercentages==money)

     {

      if(!InpAllSymbols && profit_all_positions==0.0)

         return;

      double profit_money=(InpAllSymbols)?equity-m_new_global_equity:profit_all_positions;

      if(profit_money>=InpVolumeMoneyOrPercentages)

         m_need_close_all=true;

     }

   else

     {

      if((InpAllSymbols && m_new_global_equity==0.0) || (!InpAllSymbols && profit_all_positions==0.0))

         return;

      double profit_percent=(InpAllSymbols)?(equity*100.0/m_new_global_equity)-100.0:(equity*100.0/profit_all_positions)-100.0;

      if(profit_percent>=InpVolumeMoneyOrPercentages)

         m_need_close_all=true;

     }

  }

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

Comments