iAlligator Closing Positions

Author: Copyright © 2019, Vladimir Karputov
Price Data Components
Series array that contains tick volumes of each bar
Indicators Used
Bill Williams Alligator
0 Views
0 Downloads
0 Favorites
iAlligator Closing Positions
ÿþ//+------------------------------------------------------------------+

//|                                 iAlligator Closing Positions.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.043

*/

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>

#include <Trade\AccountInfo.mqh>

//---

CPositionInfo  m_position;                   // object of CPositionInfo class

CTrade         m_trade;                      // object of CTrade class

CSymbolInfo    m_symbol;                     // object of CSymbolInfo class

CAccountInfo   m_account;                    // object of CAccountInfo class

//--- input parameters

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

input ulong    InpDeviation         = 10;          // Deviation, in points (1.00045-1.00055=10 points)

//--- Alligator

input ENUM_TIMEFRAMES      Inp_Alligator_period          = PERIOD_CURRENT; // Alligator: timeframe

input int                  Inp_Alligator_jaw_period      = 13;             // Alligator: period for the calculation of jaws

input int                  Inp_Alligator_jaw_shift       = 8;              // Alligator: horizontal shift of jaws

input int                  Inp_Alligator_teeth_period    = 8;              // Alligator: period for the calculation of teeth

input int                  Inp_Alligator_teeth_shift     = 5;              // Alligator: horizontal shift of teeth

input int                  Inp_Alligator_lips_period     = 5;              // Alligator: period for the calculation of lips

input int                  Inp_Alligator_lips_shift      = 3;              // Alligator: horizontal shift of lips

input ENUM_MA_METHOD       Inp_Alligator_ma_method       = MODE_SMMA;      // Alligator: type of smoothing

input ENUM_APPLIED_PRICE   Inp_Alligator_applied_price   = PRICE_MEDIAN;   // Alligator: type of price

//---

input bool     InpPrintLog          = false;       // Print log

//---

int      handle_iAlligator;                  // variable for storing the handle of the iAlligator indicator



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

bool     m_need_close_buy        = false;    // close buy positions

bool     m_need_close_sell       = false;    // close sell positions

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

  {

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

     {

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

      return(INIT_FAILED);

     }

   RefreshRates();

//---

   m_trade.SetExpertMagicNumber(399);

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(m_symbol.Name());

   m_trade.SetDeviationInPoints(InpDeviation);

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

//--- create handle of the indicator iAlligator

   handle_iAlligator=iAlligator(m_symbol.Name(),Inp_Alligator_period,

                                Inp_Alligator_jaw_period,Inp_Alligator_jaw_shift,

                                Inp_Alligator_teeth_period,Inp_Alligator_teeth_shift,

                                Inp_Alligator_lips_period,Inp_Alligator_lips_shift,

                                MODE_SMMA,PRICE_MEDIAN);

//--- if the handle is not created

   if(handle_iAlligator==INVALID_HANDLE)

     {

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

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

                  m_symbol.Name(),

                  EnumToString(Inp_Alligator_period),

                  GetLastError());

      //--- the indicator is stopped early

      return(INIT_FAILED);

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Expert deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---



  }

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

//| Expert tick function                                             |

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

void OnTick()

  {

   if(m_need_close_buy || m_need_close_sell)

     {

      int      count_buys           = 0;

      double   volume_buys          = 0.0;

      double   volume_biggest_buys  = 0.0;

      int      count_sells          = 0;

      double   volume_sells         = 0.0;

      double   volume_biggest_sells = 0.0;

      CalculateAllPositions(count_buys,volume_buys,volume_biggest_buys,

                            count_sells,volume_sells,volume_biggest_sells);

      //--- close buy

      if(m_need_close_buy && count_buys>0)

        {

         double level;

         if(FreezeStopsLevels(level))

           {

            ClosePositions(POSITION_TYPE_BUY,level);

            return;

           }

         else

            return;

        }

      else

         m_need_close_buy=false;

      //--- close sell

      if(m_need_close_sell && count_sells>0)

        {

         double level;

         if(FreezeStopsLevels(level))

           {

            ClosePositions(POSITION_TYPE_SELL,level);

            return;

           }

         else

            return;

        }

      else

         m_need_close_sell=false;

     }

//---

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

     {

      datetime time_current=TimeCurrent();

      if(time_current-m_last_signal>10)

        {

         //--- search for trading signals

         if(!RefreshRates())

           {

            m_prev_bars=0;

            return;

           }

         if(!SearchTradingSignals())

           {

            m_prev_bars=0;

            return;

           }

         m_last_signal=time_current;

        }

     }

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

   datetime time_0=iTime(m_symbol.Name(),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

     {

      if(!RefreshRates())

        {

         m_prev_bars=0;

         return;

        }

      //--- search for trading signals

      if(!SearchTradingSignals())

        {

         m_prev_bars=0;

         return;

        }

     }

//---

  }

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

//| TradeTransaction function                                        |

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

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//---



  }

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

//| Refreshes the symbol quotes data                                 |

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

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      if(InpPrintLog)

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

      return(false);

     }

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

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

     {

      if(InpPrintLog)

         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

   /*

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

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

//---

   return(true);

  }

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

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

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","This a no dynamic array!");

      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

      PrintFormat(__FILE__," ",__FUNCTION__,", ERROR: ","Failed to copy data from the indicator, error code %d",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,const double 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

   */

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

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

                        if(InpPrintLog)

                           Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.PositionClose ",m_position.Ticket());

                 }

               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(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol

                     if(InpPrintLog)

                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","CTrade.PositionClose ",m_position.Ticket());

                 }

              }

  }

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

//| Calculate all positions                                          |

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

void CalculateAllPositions(int &count_buys,double &volume_buys,double &volume_biggest_buys,

                           int &count_sells,double &volume_sells,double &volume_biggest_sells)

  {

   count_buys  = 0;

   volume_buys   = 0.0;

   volume_biggest_buys  = 0.0;

   count_sells = 0;

   volume_sells  = 0.0;

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

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               count_buys++;

               volume_buys+=m_position.Volume();

               if(m_position.Volume()>volume_biggest_buys)

                  volume_biggest_buys=m_position.Volume();

               continue;

              }

            else

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                 {

                  count_sells++;

                  volume_sells+=m_position.Volume();

                  if(m_position.Volume()>volume_biggest_sells)

                     volume_biggest_sells=m_position.Volume();

                 }

           }

  }

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

//| Search trading signals                                           |

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

bool SearchTradingSignals(void)

  {

   double jaw[],teeth[],lips[];

   MqlRates rates[];

   ArraySetAsSeries(jaw,true);

   ArraySetAsSeries(teeth,true);

   ArraySetAsSeries(lips,true);

   ArraySetAsSeries(rates,true);

   int start_pos=0,count=3;

   if(!iGetArray(handle_iAlligator,GATORJAW_LINE,start_pos,count,jaw) ||

      !iGetArray(handle_iAlligator,GATORTEETH_LINE,start_pos,count,teeth) ||

      !iGetArray(handle_iAlligator,GATORLIPS_LINE,start_pos,count,lips) ||

      CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

     {

      return(false);

     }

//---

   if(lips[0]>teeth[0] && lips[0]>jaw[0])

      if(rates[0].high>lips[0] && rates[0].low<lips[0])

         m_need_close_buy=true;

   if(lips[0]<teeth[0] && lips[0]<jaw[0])

      if(rates[0].high>lips[0] && rates[0].low<lips[0])

         m_need_close_sell=true;

//---

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