Profit Control

Author: Copyright © 2021, Aleksandr Klapatyuk
Profit factor:
0.00
Price Data Components
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reached
Miscellaneous
It plays sound alertsIt issuies visual alerts to the screen
1 Views
0 Downloads
0 Favorites
Profit Control
ÿþ//+------------------------------------------------------------------+

//|                                               Profit Control.mq5 |

//|                           Copyright © 2021, Aleksandr Klapatyuk. |

//|                            https://www.mql5.com/ru/users/sanalex |

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

#property copyright   "Copyright © 2021, Aleksandr Klapatyuk"

#property link        "https://www.mql5.com/ru/users/sanalex"

#property description "Copyright © 2021, Vladimir Karputov"

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

#property description "Copyright © 2021, SEM "

#property description "https://www.mql5.com/ru/users/seliveru"

#property version     "1.00"

//---

#define InpMagic 451889285

//---

#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 group     "---- Balans Parameters ----"

input ENUM_TIMEFRAMES TimeFrame      = PERIOD_CURRENT; // Change TimeFrame - Current = dont changed

input string          Template       = "ADX";          // <O H01;>=0(without '.tpl')

input double          TargetProfit   = 1000000;        // 0;0=A + @81K;L(?@81028BL : 10;0=AC)

input double          TargetLoss     = 0;              // 0;0=A - #1KB>:(>B=OBL >B 10;0=A0)

input group     "---- Balans Parameters 1 ----"

input double          TargetProfit_1 = 1000000;        // 1I0O @81K;L 0;NB5 '0'--> 5;L7O

input double          TargetLoss_1   = 1000000;        // 1I89 #1KB>: 0;NB5 '0'--> 5;L7O

input group     "---- Balans BUY+SELL ----"

input double          TargetProfit_2 = 1000000;        // BUY+SELL @81K;L 0;NB5 '0'--> 5;L7O

input double          TargetLoss_2   = 1000000;        // BUY+SELL #1KB>: 0;NB5 '0'--> 5;L7O

input group     "---- TP SL In currency ----"

input double          InpTProfit     = 40000;          // In currency the amount 1I89 TP

input double          InpStopLoss    = 1000000;        // In currency the amount 1I89 SL

input group     "---- Lots Parameters ----"

input double          InpLots1       = 0.01;           // : Lots 1

input int             InpLots_01     = 3000;           // In currency the amount

input double          InpLots2       = 0.02;           // : Lots 2

input int             InpLots_02     = 6000;           // In currency the amount

input double          InpLots3       = 0.04;           // : Lots 3

input int             InpLots_03     = 12000;          // In currency the amount

input double          InpLots4       = 0.08;           // : Lots 4

//---

string m_name[]= {"BUY","SELL","BUY_Close","SELL_Close","CLOSE_ALL","without '.tpl'"};

uint   maxLimits=1;              // >;-2> >78F88 B:@KBL 2 >4=C AB>@>=C

int    ticks_to_close_Exp=1;     // :>;8G5AB2> B8:>2 4> A=OB8O M:A?5@B0

uint   SLEEPTIME=1;              // @5<O ?0C7K <564C ?>2B>@0<8 2 A5:C=40E

uint   RTOTAL=4;                 // '8A;> ?>2B>@>2 ?@8 =5C40G=KE A45;:0E

uint   Deviation_=10;            // B:;>=5=85 F5=K

bool   ObjRevers        = false; // Revers

//---

bool   ExtNeedOpenBuy   = false; //

bool   ExtNeedOpenSell  = false; //

bool   ExtNeedCloseBuy  = false; //

bool   ExtNeedCloseSell = false; //

bool   ExtNeedCloseAll  = false; //

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

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

//| Calculate optimal lot size                                       |

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

double OptimizedBuy(void)

  {

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

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

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

           }

        }

     }

   double Lots=InpLots1;

   double ab=PROFIT_BUY;

   if(ab<-1 && ab>=-InpLots_01)

      Lots=InpLots1;

   if(ab<-InpLots_01 && ab>=-InpLots_02)

      Lots=InpLots2;

   if(ab<-InpLots_02 && ab>=-InpLots_03)

      Lots=InpLots3;

   if(ab<-InpLots_03)

      Lots=InpLots4;

//--- return trading volume

   return(Lots);

  }

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

//| Calculate optimal lot size                                       |

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

double OptimizedSell(void)

  {

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

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

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

           }

        }

     }

   double Lots=InpLots1;

   double ab=PROFIT_SELL;

   if(ab<-1 && ab>=-InpLots_01)

      Lots=InpLots1;

   if(ab<-InpLots_01 && ab>=-InpLots_02)

      Lots=InpLots2;

   if(ab<-InpLots_02 && ab>=-InpLots_03)

      Lots=InpLots3;

   if(ab<-InpLots_03)

      Lots=InpLots4;

//--- return trading volume

   return(Lots);

  }

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

//| 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());

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

//--- set default deviation for trading in adjusted points

   m_trade.SetDeviationInPoints(3*digits_adjust);

//---

   int _y=100;

   for(int i=0; i<ArraySize(m_name); i++)

     {

      ButtonCreate(m_name[i],5,_y,130,20,10);

      _y=_y+25;

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

   for(int i=0; i<ArraySize(m_name); i++)

     {

      ObjectDelete(0,Symbol()+m_name[i]);

     };

   EventKillTimer();

//---

   Print(TimeCurrent(),": ",__FUNCTION__," reason code = ",reason);

   Comment("");

   ObjectsDeleteAll(0,"cm");

//---

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

      return;

   ButtonOnTick();

   if(m_position.Select(Symbol()))

     {

      ProfitOnTick();

      ProfitTarget_2();

     }

   if(ProfitTarget())

     {

      return;

     }

   if(ProfitTarget_1())

     {

      return;

     }

//---

  }

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

//| Check for long position closing                                  |

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

bool ProfitTarget(void)

  {

   bool res=false;

   if(AccountInfoDouble(ACCOUNT_EQUITY)<=TargetLoss ||

      AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)

     {

      CloseAllProfit();

      CloseAllLoss();

      CloseAll();

      DeletePending();

      Sleep(SLEEPTIME*1000);

      CloseAllProfit();

      CloseAllLoss();

      Sleep(SLEEPTIME*1000);

      CloseAll();

      DeletePending();

      ExpertRemoves();

      DeleteChart();

      PlaySound("expert.wav");

      res=true;

     }

//--- result

   return(res);

  }

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

//| Check ProfitTarget closing                                       |

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

bool ProfitTarget_1(void)

  {

   bool res=false;

   double growth=0.00;

   static double bal=0.00;

   bal=AccountInfoDouble(ACCOUNT_BALANCE);

   growth=growth+bal-AccountInfoDouble(ACCOUNT_EQUITY);

   if(growth<=-TargetProfit_1 || growth>=TargetLoss_1)

     {

      CloseAllProfit();

      CloseAllLoss();

      CloseAll();

      Sleep(SLEEPTIME*1000);

      CloseAllProfit();

      CloseAllLoss();

      Sleep(SLEEPTIME*1000);

      CloseAll();

      res=true;

     }

//--- result

   return(res);

  }

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

//| Check ProfitTarget closing                                       |

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

bool ProfitTarget_2(void)

  {

   bool res=false;

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

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

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

           }

        }

     }

   double growth=0.00;

   static double balbuy=0.00;

   static double balsell=0.00;

   balbuy=PROFIT_BUY;

   balsell=PROFIT_SELL;

   growth=growth+balbuy+balsell;

   if(growth>=TargetProfit_2 || growth<=-TargetLoss_2)

     {

      ExtNeedCloseAll=true;

      LongShortObjClosed();

      res=true;

     }

//--- result

   return(res);

  }

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

//| Check for long position closing                                  |

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

bool ProfitOnTick(void)

  {

   bool res=false;

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

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

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

           }

        }

     }

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

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

         if(m_position.Symbol()==m_symbol.Name())

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(PROFIT_BUY<-InpStopLoss || PROFIT_BUY>=InpTProfit) // if the profit

                 {

                  ExtNeedCloseBuy=true;

                  LongObjClosed();

                 }

               res=true;

              }

           }

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

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

         if(m_position.Symbol()==m_symbol.Name())

           {

            if(m_position.PositionType()==POSITION_TYPE_SELL)

              {

               if(PROFIT_SELL<-InpStopLoss || PROFIT_SELL>=InpTProfit) // if the profit

                 {

                  ExtNeedCloseSell=true;

                  ShortObjClosed();

                 }

               res=true;

              }

           }

//--- result

   return(res);

  }

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

//| Check for long position closing                                  |

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

bool LongObjClosed(void)

  {

   bool res=false;

//--- should it be closed?

   if(!ObjRevers)

     {

      if(ExtNeedCloseBuy)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_BUY,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseBuy=false;

     }

//--- result

   if(ObjRevers)

     {

      if(ExtNeedCloseBuy)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_SELL,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseBuy=false;

     }

//--- result

   return(res);

  }

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

//| Check for short position closing                                 |

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

bool ShortObjClosed(void)

  {

   bool res=false;

//--- should it be closed?

   if(!ObjRevers)

     {

      if(ExtNeedCloseSell)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_SELL,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseSell=false;

     }

//--- result

   if(ObjRevers)

     {

      if(ExtNeedCloseSell)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_BUY,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseSell=false;

     }

//--- result

   return(res);

  }

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

//| Check for short position closing                                 |

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

bool LongShortObjClosed(void)

  {

   bool res=false;

//--- should it be closed?

   if(ExtNeedCloseAll)

     {

      //--- close position

      double level;

      if(FreezeStopsLevels(level))

         ClosePositions(POSITION_TYPE_BUY,level);

      if(FreezeStopsLevels(level))

         ClosePositions(POSITION_TYPE_SELL,level);

      //--- processed and cannot be modified

      res=true;

     }

   else

      ExtNeedCloseAll=false;

//--- result

   return(res);

  }

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

//| Check for long position opening                                  |

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

bool LongObjOpened(void)

  {

   bool res=false;

//--- check for long position (BUY) possibility

   if(!ObjRevers)

     {

      if(ExtNeedOpenBuy)

        {

         double price=m_symbol.Ask();

         for(uint i=0; i<maxLimits; i++)

           {

            //--- open position

            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,OptimizedBuy(),price,0.0,0.0))

               printf("Position by %s to be opened",m_symbol.Name());

            else

              {

               printf("Error opening BUY position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

               printf("Open parameters : price=%f,TP=%f",price,0.0);

              }

            res=true;

           }

         ExtNeedOpenBuy=false;

         //--- in any case we must exit from expert

        }

     }

//--- check for long position (BUY) possibility

   if(ObjRevers)

      if(ExtNeedOpenBuy)

        {

           {

            double price=m_symbol.Bid();

            for(uint y=0; y<maxLimits; y++)

              {

               if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,OptimizedSell(),price,0.0,0.0))

                  printf("Position by %s to be opened",m_symbol.Name());

               else

                 {

                  printf("Error opening SELL position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

                  printf("Open parameters : price=%f,TP=%f",price,0.0);

                 }

               res=true;

              }

            ExtNeedOpenBuy=false;

            //--- in any case we must exit from expert

           }

        }

//--- result

   return(res);

  }

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

//| Check for short position opening                                 |

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

bool ShortObjOpened(void)

  {

   bool res=false;

//--- check for short position (SELL) possibility

   if(!ObjRevers)

     {

      if(ExtNeedOpenSell)

        {

         double price=m_symbol.Bid();

         for(uint y=0; y<maxLimits; y++)

           {

            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,OptimizedSell(),price,0.0,0.0))

               printf("Position by %s to be opened",m_symbol.Name());

            else

              {

               printf("Error opening SELL position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

               printf("Open parameters : price=%f,TP=%f",price,0.0);

              }

            res=true;

           }

         ExtNeedOpenSell=false;

         //--- in any case we must exit from expert

        }

     }

//--- check for short position (SELL) possibility

   if(ObjRevers)

     {

      if(ExtNeedOpenSell)

        {

         double price=m_symbol.Ask();

         for(uint i=0; i<maxLimits; i++)

           {

            //--- open position

            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,OptimizedBuy(),price,0.0,0.0))

               printf("Position by %s to be opened",m_symbol.Name());

            else

              {

               printf("Error opening BUY position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

               printf("Open parameters : price=%f,TP=%f",price,0.0);

              }

            res=true;

           }

         ExtNeedOpenSell=false;

         //--- in any case we must exit from expert

        }

     }

//--- result

   return(res);

  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

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

      return(false);

     }

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

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

     {

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

      return(false);

     }

//---

   return(true);

  }

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

//| Check Freeze and Stops levels                                    |

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

bool FreezeStopsLevels(double &level)

  {

//--- check Freeze and Stops levels

   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_adjusted_point;

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

//---

   return(true);

  }

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

//| Close positions                                                  |

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

void ClosePositions(const ENUM_POSITION_TYPE pos_type,const double level)

  {

   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()==m_symbol.Name()/* && m_position.Magic()==InpMagic*/)

            if(m_position.PositionType()==pos_type)

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                 {

                  bool take_profit_level=(m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=level) || m_position.TakeProfit()==0.0;

                  bool stop_loss_level=(m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=level) || m_position.StopLoss()==0.0;

                  if(take_profit_level && stop_loss_level)

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

                 }

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                 {

                  bool take_profit_level=(m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=level) || m_position.TakeProfit()==0.0;

                  bool stop_loss_level=(m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=level) || m_position.StopLoss()==0.0;

                  if(take_profit_level && stop_loss_level)

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

                 }

               PlaySound("ok.wav");

              }

  }

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

//| start function                                                   |

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

void CloseAll(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

        {

         ClosePosition(m_position.Symbol()); // close a position by the specified symbo

        }

  }

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

//| start function                                                   |

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

void CloseAllProfit(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

        {

         if(m_position.Commission()+m_position.Swap()+m_position.Profit()>0.0)

            ClosePosition(m_position.Symbol()); // close a position by the specified symbo

        }

  }

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

//| start function                                                   |

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

void CloseAllLoss(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

        {

         if(m_position.Commission()+m_position.Swap()+m_position.Profit()<0.0)

            ClosePosition(m_position.Symbol());  // close a position by the specified symbo

        }

  }

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

//| Close selected position                                          |

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

void ClosePosition(const string symbol)

  {

   if(InitTrade(symbol))

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

   PlaySound("ok.wav");

  }

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

//| Init trade object                                                |

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

bool InitTrade(const string symbol)

  {

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

      return(false);

//---

   if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_FOK))

      m_trade.SetTypeFilling(ORDER_FILLING_FOK);

   else

      if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_IOC))

         m_trade.SetTypeFilling(ORDER_FILLING_IOC);

      else

         m_trade.SetTypeFilling(ORDER_FILLING_RETURN);

//---

   return(true);

//---

  }

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

//| Checks if the specified filling mode is allowed                  |

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

bool IsFillingTypeAllowed(string symbol,int fill_type)

  {

//--- Obtain the value of the property that describes allowed filling modes

   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);

//--- Return true, if mode fill_type is allowed

   return((filling & fill_type)==fill_type);

  }

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

//| start function                                                   |

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

void ExpertRemoves(void)

  {

   static int tick_counter=0;

//---

   tick_counter++;

   Comment("\n> 2K3@C7:8 M:A?5@B0 ",__FILE__," >AB0;>AL ",

           (ticks_to_close_Exp-tick_counter)," B8:>2 ");

//--- 4>

   if(tick_counter>=ticks_to_close_Exp)

     {

      ExpertRemove();

      Print(TimeCurrent(),": ",__FUNCTION__," M:A?5@B 1C45B 2K3@C65=");

     }

   Print("tick_counter = ",tick_counter);

//---

  }

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

//| start function                                                   |

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

void DeleteChart(void)

  {

   long currChart,prevChart=ChartFirst();

   int i=0,limit=100;

   bool errTemplate;

   while(i<limit)

     {

      currChart=ChartNext(prevChart);

      if(TimeFrame!=PERIOD_CURRENT)

        {

         ChartSetSymbolPeriod(prevChart,ChartSymbol(prevChart),TimeFrame);

        }

      errTemplate=ChartApplyTemplate(prevChart,Template+".tpl");

      if(!errTemplate)

        {

         Print("Error ",ChartSymbol(prevChart),"-> ",GetLastError());

        }

      if(currChart<0)

         break;

      Print(i,ChartSymbol(currChart)," ID =",currChart);

      prevChart=currChart;

      i++;

     }

  }

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

//| start function                                                   |

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

void DeletePending(void)

  {

   Print("!@01>B0;0 DC=:F8O 70:@K205< 2A5 2KAB02;5==K5 >@45@0");

//----

   for(uint count=0; count<=RTOTAL && !IsStopped(); count++)

     {

      //---- 70:@K205< 2A5 2KAB02;5==K5 >@45@0 ?> B5:CI5<C A8<2>;C

      int total=OrdersTotal();

      if(!total)

         return; // 2A5 >@45@0 70:@KBK

      for(int pos=total-1; pos>=0; pos--)

        {

         ulong ticket=ulong(OrderGetTicket(pos));

         if(!OrderSelect(ticket))

            continue;

         string symbol=OrderGetString(ORDER_SYMBOL);

         bool _Close=true;

         OrderCloseByTicket(_Close,symbol,ticket,Deviation_);

        }

      if(!OrdersTotal())

         break;

      Sleep(SLEEPTIME*1000);

     }

//----

  }

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

//| 0:@K205< 4;8==CN ?>78F8N                                        |

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

bool OrderCloseByTicket

(

   bool &Signal,         // D;03 @07@5H5=8O =0 A45;:C

   const string symbol,  // B>@3>20O ?0@0 A45;:8

   ulong ticket,         // B8:5B

   uint deviation        // A;8??06

)

  {

//----

   if(!Signal)

      return(true);

//---- 1JO2;5=85 AB@C:BC@ B>@3>2>3> 70?@>A0 8 @57C;LB0B0 B>@3>2>3> 70?@>A0

   MqlTradeRequest request;

   MqlTradeResult result;

//---- 1JO2;5=85 AB@C:BC@K @57C;LB0B0 ?@>25@:8 B>@3>2>3> 70?@>A0

   MqlTradeCheckResult check;

//---- >1=C;5=85 AB@C:BC@

   ZeroMemory(request);

   ZeroMemory(result);

   ZeroMemory(check);

//---- =8F80;870F8O AB@C:BC@K B>@3>2>3> 70?@>A0 MqlTradeRequest 4;O C40;5=8O >B;>65==>3> >@45@0

   request.action=TRADE_ACTION_REMOVE;

   request.deviation=deviation;

   request.order=ticket;

//----

   string comment="";

   string ordertype=EnumToString(ENUM_ORDER_TYPE(OrderGetInteger(ORDER_TYPE)));

   StringConcatenate(comment,"<<< ============ ",__FUNCTION__,"(): #40;O5< >B;>65==K9 ",ordertype," >@45@ ?> ",symbol," A B8:5B>< ",string(ticket)," ============ >>>");

   Print(comment);

//---- B?@02:0 ?@8:070 =0 70:@K20=85 ?>78F88 =0 B>@3>2K9 A5@25@

   if(!OrderSend(request,result) || result.retcode!=TRADE_RETCODE_DONE)

     {

      Print(__FUNCTION__,"(): 52>7<>6=> C40;8BL ",ordertype," >@45@ A B8:5B>< ",string(ticket),"!");

      Print(__FUNCTION__,"(): OrderSend(): ",m_trade.ResultComment());

      return(false);

     }

   else

      if(result.retcode==TRADE_RETCODE_DONE)

        {

         Signal=false;

         comment="";

         StringConcatenate(comment,"<<< ============ ",__FUNCTION__,"(): B;>65==K9 ",ordertype," >@45@ ?> ",symbol," A B8:5B>< ",string(ticket)," C40;Q= ============ >>>");

         Print(comment);

         PlaySound("ok.wav");

        }

      else

        {

         Print(__FUNCTION__,"(): 52>7<>6=> C40;8BL ",ordertype," >@45@ A B8:5B>< ",string(ticket),"!");

         Print(__FUNCTION__,"(): OrderSend(): ",m_trade.ResultComment());

         return(false);

        }

//----

   return(true);

  }

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

//|                                                                  |

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

void ButtonCreate(string name,int Xdist,

                  int Ydist,int Xsize,int Ysize,int FONTSIZE=12)

  {

   if(ObjectFind(0,m_symbol.Name()+name)<0)

      ObjectCreate(0,m_symbol.Name()+name,OBJ_BUTTON,0,100,100);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_COLOR,clrWhite);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_BGCOLOR,clrBlack);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_XDISTANCE,Xdist);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_YDISTANCE,Ydist);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_XSIZE,Xsize);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_YSIZE,Ysize);

   ObjectSetString(0,m_symbol.Name()+name,OBJPROP_FONT,"Sans Serif");

   ObjectSetString(0,m_symbol.Name()+name,OBJPROP_TEXT,name);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_FONTSIZE,FONTSIZE);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_SELECTABLE,false);

  }

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

//| Check for long position closing                                  |

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

bool ButtonOnTick(void)

  {

   bool res=false;

   double level;

   if(ObjectGetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_STATE,0)==true)

     {

      if(FreezeStopsLevels(level))

         ClosePositions(POSITION_TYPE_SELL,level);

      PlaySound("ok.wav");

      ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_STATE,false);

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE,false);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_STATE,0)==true)

     {

      if(FreezeStopsLevels(level))

         ClosePositions(POSITION_TYPE_BUY,level);

      PlaySound("ok.wav");

      ObjectSetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_STATE,false);

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE,false);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_STATE,0)==true)

     {

      CloseAllProfit();

      CloseAllLoss();

      CloseAll();

      DeletePending();

      Sleep(SLEEPTIME*1000);

      CloseAllProfit();

      CloseAllLoss();

      Sleep(SLEEPTIME*1000);

      CloseAll();

      DeletePending();

      ExpertRemoves();

      DeleteChart();

      PlaySound("expert.wav");

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_STATE,false);

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_STATE,false);

     }

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

   double PROFIT_CLOSE=0.00;

   double PROFIT_BUY_Lot=0.00;

   double PROFIT_SELL_Lot=0.00;

   double PROFIT_CLOSE_Lot=0.00;

   int _all =0;

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

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         PROFIT_CLOSE_Lot=AccountInfoDouble(ACCOUNT_EQUITY);

         _all=_all+1;

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

            PROFIT_BUY_Lot=PROFIT_BUY_Lot+PositionGetDouble(POSITION_VOLUME);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

            PROFIT_SELL_Lot=PROFIT_SELL_Lot+PositionGetDouble(POSITION_VOLUME);

           }

           {

            PROFIT_CLOSE=AccountInfoDouble(ACCOUNT_PROFIT);

            PROFIT_CLOSE_Lot=AccountInfoDouble(ACCOUNT_PROFIT);

           }

        }

     }

   ObjectSetString(0,m_symbol.Name()+"BUY_Close",OBJPROP_TEXT,"BUY Close ("+DoubleToString(PROFIT_BUY,2)+")");

   if(PROFIT_BUY>0)

     {

      ObjectSetInteger(0,Symbol()+"BUY_Close",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_BUY==0)

        {

         ObjectSetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_BGCOLOR,clrBlack);

        }

      else

        {

         ObjectSetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_BGCOLOR,clrCrimson);

        };

   ObjectSetString(0,m_symbol.Name()+"SELL_Close",OBJPROP_TEXT,"SELL Close ("+DoubleToString(PROFIT_SELL,2)+")");

   if(PROFIT_SELL>0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_SELL==0)

        {

         ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_BGCOLOR,clrBlack);

        }

      else

        {

         ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_BGCOLOR,clrCrimson);

        }

   ObjectSetString(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_TEXT,"CLOSE ALL ("+DoubleToString(PROFIT_CLOSE,2)+")");

   if(PROFIT_CLOSE>0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_CLOSE==0)

        {

         ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrBlack);

        }

      else

        {

         ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrCrimson);

        }

   ObjectSetString(0,m_symbol.Name()+"BUY",OBJPROP_TEXT,"BUY Lot ("+DoubleToString(PROFIT_BUY_Lot,2)+")");

   ObjectSetString(0,m_symbol.Name()+"SELL",OBJPROP_TEXT,"SELL Lot ("+DoubleToString(PROFIT_SELL_Lot,2)+")");

   ObjectSetString(0,m_symbol.Name()+"CLOSE",OBJPROP_TEXT,"CLOSE Lot ("+DoubleToString(PROFIT_CLOSE_Lot,2)+")");

   ObjectSetString(0,m_symbol.Name()+"without '.tpl'",OBJPROP_TEXT,".tpl"+",Tool="+DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2));

   if(ObjectGetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE,0)==true)

     {

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_BGCOLOR,clrDeepSkyBlue);

     }

   else

     {

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_BGCOLOR,clrBlack);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE,0)==true)

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_BGCOLOR,clrRed);

     }

   else

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_BGCOLOR,clrBlack);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_STATE,0)==true)

     {

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_BGCOLOR,clrRed);

     }

   else

     {

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_BGCOLOR,clrBlack);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"without '.tpl'",OBJPROP_STATE,0)==true)

     {

      Alert("DeleteChart ''"+Template+"' on "+m_symbol.Name());

      DeleteChart();

     };

   if(ObjectGetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE,0);

      ExtNeedOpenSell=true;

      ShortObjOpened();

      PlaySound("ok.wav");

      res=true;

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE,0);

      ExtNeedOpenBuy=true;

      LongObjOpened();

      PlaySound("ok.wav");

      res=true;

     }

//--- result

   return(res);

  }

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

Comments