Close All Current

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

//|                                            Close All Current.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 3.012

*/

#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

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

//| Enum Mode                                                        |

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

enum ENUM_MODE

  {

   all   = 0,  // manual and EA

   manual= 1,  // manual

   ea    = 2,  // EA

  };

//--- input parameters

input ulong             InpMagic=200;                 // Magic number ("0" - all positions)

input ENUM_MODE         InpMode=all;                  // Close: 

//--- Button 

input string            InpName="Button Close All";   // Button name 

input int               InpX=50;                      // Button X coordinate

input int               InpY=50;                      // Button Y coordinate

input int               InpWidth=180;                 // Button width 

input int               InpHeight=21;                 // Button height 

input ENUM_BASE_CORNER  InpCorner=CORNER_LEFT_UPPER;  // Chart corner for anchoring 

input string            InpFont="Courier New";        // Font 

input int               InpFontSize=10;               // Font size 

input color             InpColor=clrBlack;            // Text color 

input color             InpBackColor=C'236,233,216';  // Background color 

input color             InpBorderColor=clrNONE;       // Border color 

input bool              InpState=false;               // Pressed/Released 

input bool              InpBack=false;                // Background object 

input bool              InpSelection=false;           // Highlight to move 

input bool              InpHidden=true;               // Hidden in the object list 

input long              InpZOrder=0;                  // Priority for mouse click 

//---

ulong    ExtSlippage=10;            // Slippage

double   ExtAdjustedPoint;

bool     ExtNeedCloseAll=false;     //

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//--- create a timer with a 1 second period 

   if(!EventSetTimer(1))

      return(INIT_FAILED);

//---

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

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)

      digits_adjust=10;

   ExtAdjustedPoint=m_symbol.Point()*digits_adjust;



//--- create the button 

   string text="Close: ";

   switch(InpMode)

     {

      case  manual:

         text=text+"manual";

         break;

      case  ea:

         text=text+" EA";

         break;

      default:

         text=text+"manual and EA";

         break;

     }

   if(!ButtonCreate(0,InpName,0,InpX,InpY,InpWidth,InpHeight,InpCorner,text,InpFont,InpFontSize,

      InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,InpZOrder))

     {

      return(INIT_FAILED);

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//--- destroy the timer after completing the work 

   EventKillTimer();

//---

   ButtonDelete(0,InpName);

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   if(ExtNeedCloseAll)

     {

      long magic=0;

      if(IsPositionExists(InpMode))

        {

         double level;

         if(FreezeStopsLevels(level))

           {

            CloseAllPositions(level,InpMode);  return;

           }

         else

            return;

        }

      else

        {

         ExtNeedCloseAll=false;

         ObjectSetInteger(0,InpName,OBJPROP_STATE,0);

        }

     }

//if(!IsPositionExists(all))

//   m_trade.Buy(m_symbol.LotsMin());

//---

  }

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

//| Timer function                                                   |

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

void OnTimer()

  {

//---

   if(ExtNeedCloseAll)

      return;

   long state=ObjectGetInteger(0,InpName,OBJPROP_STATE);

   if(state==1)

     {

      ExtNeedCloseAll=true;

      OnTick();

     }

  }

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

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

  }

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

//| Check Freeze and Stops levels                                    |

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

bool 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()*ExtAdjustedPoint;

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

//---

   return(true);

  }

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

//| Is position exists                                               |

//|   mode:                                                          |

//|      all   = 0,  // manual and EA                                |

//|      manual= 1,  // manual                                       |

//|      ea    = 2,  // EA                                           |

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

bool IsPositionExists(const ENUM_MODE mode)

  {

   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()==m_symbol.Name())

            if(((mode==all) || (mode==manual && m_position.Magic()==0) || (ea==manual && m_position.Magic()!=0)))

               return(true);

//---

   return(false);

  }

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

//| Close all positions                                              |

//|   mode:                                                          |

//|      all   = 0,  // manual and EA                                |

//|      manual= 1,  // manual                                       |

//|      ea    = 2,  // EA                                           |

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

void CloseAllPositions(const double level,const ENUM_MODE mode)

  {

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

            if(((mode==all) || (mode==manual && m_position.Magic()==0) || (ea==manual && m_position.Magic()!=0)))

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                  if(MathAbs(m_symbol.Bid()-m_position.PriceOpen())>=level)

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

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                  if(MathAbs(m_symbol.Ask()-m_position.PriceOpen())>=level)

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

              }

  }

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

//| Create the button                                                | 

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

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

                  const string            name="Button",// button name 

                  const int               sub_window=0,             // subwindow index 

                  const int               x=0,                      // X coordinate 

                  const int               y=0,                      // Y coordinate 

                  const int               width=50,                 // button width 

                  const int               height=18,                // button height 

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

                  const string            text="Button",            // text 

                  const string            font="Arial",             // font 

                  const int               font_size=10,             // font size 

                  const color             clr=clrBlack,             // text color 

                  const color             back_clr=C'236,233,216',  // background color 

                  const color             border_clr=clrNONE,       // border color 

                  const bool              state=false,              // pressed/released 

                  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 the button 

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

     {

      Print(__FUNCTION__,

            ": failed to create the button! Error code = ",GetLastError());

      return(false);

     }

//--- set button coordinates 

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);

   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);

//--- set button size 

   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);

   ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);

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

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- set background color 

   ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);

//--- set border color 

   ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);

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

   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);

//--- set button state 

   ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);

//--- enable (true) or disable (false) the mode of moving the button 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);

  }

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

//| Delete the button                                                | 

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

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

                  const string name="Button") // button name 

  {

//--- reset the error value 

   ResetLastError();

//--- delete the button 

   if(!ObjectDelete(chart_ID,name))

     {

      Print(__FUNCTION__,

            ": failed to delete the button! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution 

   return(true);

  }



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

Comments