iMA Close positions opened manually

Author: Copyright © 2021, Vladimir Karputov
Price Data Components
Indicators Used
Moving average indicator
0 Views
0 Downloads
0 Favorites
iMA Close positions opened manually
ÿþ//+------------------------------------------------------------------+

//|                          iMA Close positions opened manually.mq5 |

//|                              Copyright © 2021, Vladimir Karputov |

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

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

#property copyright "Copyright © 2021, Vladimir Karputov"

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

#property version   "1.001"

#property description "Close positions opened manually"

#property description "   if the bar closes above or below the 'Moving Average' indicator"

/*

   barabashkakvn Trading engine 3.157

*/

#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

//--- input parameters

input group             "Trading settings"

input ENUM_TIMEFRAMES      InpWorkingPeriod     = PERIOD_CURRENT; // Working timeframe

input uchar                InpBarCurrent        = 1;              // Bar Current

input group             "MA"

input int                  Inp_MA_ma_period     = 12;             // MA: averaging period

input int                  Inp_MA_ma_shift      = 2;              // MA: horizontal shift

input ENUM_MA_METHOD       Inp_MA_ma_method     = MODE_EMA;       // MA: smoothing type

input ENUM_APPLIED_PRICE   Inp_MA_applied_price = PRICE_MEDIAN;   // MA: type of price

input group             "Additional features"

input bool                 InpPrintLog          = true;           // Print log

input uchar                InpFreezeCoefficient = 1;              // Coefficient (if Freeze==0 Or StopsLevels==0)

input ulong                InpDeviation         = 10;             // Deviation

input ulong                InpMagic             = 464446358;      // Magic number

//---

int      handle_iMA;                            // variable for storing the handle of the iMA indicator



bool     m_need_close_buy           = false;    // close all buy positions

bool     m_need_close_sell          = false;    // close all sell positions

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

int      m_bar_current              = 0;

bool     m_init_error               = false;    // error on InInit

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//--- forced initialization of variables

   m_need_close_buy           = false;    // close all buy positions

   m_need_close_sell          = false;    // close all sell positions

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

   m_bar_current              = 0;

   m_init_error               = false;    // error on InInit

//---

   ResetLastError();

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

     {

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

      return(INIT_FAILED);

     }

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(InpMagic);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(InpDeviation);

//--- create handle of the indicator iMA

   handle_iMA=iMA(m_symbol.Name(),InpWorkingPeriod,Inp_MA_ma_period,Inp_MA_ma_shift,

                  Inp_MA_ma_method,Inp_MA_applied_price);

//--- if the handle is not created

   if(handle_iMA==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code

      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(InpWorkingPeriod),

                  GetLastError());

      //--- the indicator is stopped early

      m_init_error=true;

      return(INIT_SUCCEEDED);

     }

//---

   m_bar_current=InpBarCurrent;

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   int count_buys=0,count_sells=0;

   CalculateAllPositions(count_buys,count_sells);

//---

   if(m_need_close_buy || m_need_close_sell)

     {

      if(m_need_close_buy)

        {

         if(count_buys>0)

            ClosePositions(POSITION_TYPE_BUY);

         else

            m_need_close_buy=false;

        }

      if(m_need_close_sell)

        {

         if(count_sells>0)

            ClosePositions(POSITION_TYPE_SELL);

         else

            m_need_close_sell=false;

        }

      return;

     }

//---

   if(count_buys>0 || count_sells>0)

     {

      double ma_buffer[];

      MqlRates rates[];

      ArraySetAsSeries(ma_buffer,true);

      ArraySetAsSeries(rates,true);

      int start_pos=0,count=m_bar_current+2;

      if(!iGetArray(handle_iMA,0,start_pos,count,ma_buffer) || CopyRates(m_symbol.Name(),InpWorkingPeriod,start_pos,count,rates)!=count)

         return;

      if(rates[m_bar_current+1].low<ma_buffer[m_bar_current+1] && rates[m_bar_current].close>ma_buffer[m_bar_current])

        {

         if(count_buys>0)

            m_need_close_buy=true;

        }

      else

        {

         if(rates[m_bar_current+1].high>ma_buffer[m_bar_current+1] && rates[m_bar_current].close<ma_buffer[m_bar_current])

           {

            if(count_sells>0)

               m_need_close_sell=true;

           }

        }

     }

//---

  }

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

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

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

void FreezeStopsLevels(double &freeze,double &stops)

  {

//--- check Freeze and Stops levels

   /*

   SYMBOL_TRADE_FREEZE_LEVEL shows the distance of freezing the trade operations

      for pending orders and open positions in points

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

   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

   ------------------------------------------------------------------------------------------



   SYMBOL_TRADE_STOPS_LEVEL determines the number of points for minimum indentation of the

      StopLoss and TakeProfit levels from the current closing price of the open position

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

   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

   ------------------------------------------------------------------------------------------

   */

   double coeff=(double)InpFreezeCoefficient;

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

      return;

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

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

   if(freeze_level==0.0)

      if(InpFreezeCoefficient>0)

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

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

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

   if(stop_level==0.0)

      if(InpFreezeCoefficient>0)

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

//---

   freeze=freeze_level;

   stops=stop_level;

//---

   return;

  }

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

//| Get value of buffers                                             |

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

bool iGetArray(const int handle,const int buffer,const int start_pos,

               const int count,double &arr_buffer[])

  {

   bool result=true;

   if(!ArrayIsDynamic(arr_buffer))

     {

      if(InpPrintLog)

         PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);

      return(false);

     }

   ArrayFree(arr_buffer);

//--- reset error code

   ResetLastError();

//--- fill a part of the iBands array with values from the indicator buffer

   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);

   if(copied!=count)

     {

      //--- if the copying fails, tell the error code

      if(InpPrintLog)

         PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",

                     __FILE__,__FUNCTION__,count,copied,GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated

      return(false);

     }

   return(result);

  }

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

//| Close positions                                                  |

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

void ClosePositions(const ENUM_POSITION_TYPE pos_type)

  {

   double freeze=0.0,stops=0.0;

   FreezeStopsLevels(freeze,stops);

   /*

   SYMBOL_TRADE_FREEZE_LEVEL shows the distance of freezing the trade operations

      for pending orders and open positions in points

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

   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

   ------------------------------------------------------------------------------------------

   */

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

           {

            long reason=-1;

            if(m_position.InfoInteger(POSITION_REASON,reason))

               if((ENUM_POSITION_REASON)reason!=POSITION_REASON_EXPERT)

                  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()>=freeze) || m_position.TakeProfit()==0.0);

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

                        if(take_profit_level && stop_loss_level)

                           if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol

                              if(InpPrintLog)

                                 Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());

                       }

                     if(m_position.PositionType()==POSITION_TYPE_SELL)

                       {

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

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

                        if(take_profit_level && stop_loss_level)

                           if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol

                              if(InpPrintLog)

                                 Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());

                       }

                    }

           }

  }

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

//| Calculate all positions Buy and Sell                             |

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

void CalculateAllPositions(int &count_buys,int &count_sells)

  {

   count_buys=0;

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

           {

            long reason=-1;

            if(m_position.InfoInteger(POSITION_REASON,reason))

               if((ENUM_POSITION_REASON)reason!=POSITION_REASON_EXPERT)

                 {

                  if(m_position.PositionType()==POSITION_TYPE_BUY)

                     count_buys++;

                  if(m_position.PositionType()==POSITION_TYPE_SELL)

                     count_sells++;

                 }

           }

//---

   return;

  }

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

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