Simple iMA Above Below

Author: Copyright © 2020, Vladimir Karputov
Price Data Components
Indicators Used
Moving average indicator
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Simple iMA Above Below
ÿþ//+------------------------------------------------------------------+

//|                                       Simple iMA Above Below.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.138

*/

#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

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

//| Enum Lor or Risk                                                 |

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

enum ENUM_LOT_OR_RISK

  {

   lots_min=0, // Lots Min

   lot=1,      // Constant lot

  };

//--- input parameters

input group             "Trading settings"

input ENUM_TIMEFRAMES      InpWorkingPeriod     = PERIOD_CURRENT; // Working timeframe

input uint                 InpStopLoss          = 150;            // Stop Loss

input uint                 InpTakeProfit        = 460;            // Take Profit

input group             "Position size management (lot calculation)"

input ENUM_LOT_OR_RISK     InpLotOrRisk         = lot;            // Money management: 

input double               InpVolumeLotOrRisk   = 1.0;            // The value for "Money management"

input group             "Moving Average"

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

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

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

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

input group             "Additional features"

input bool                 InpPrintLog          = false;          // Print log

input ulong                InpDeviation         = 10;             // Deviation

input ulong                InpMagic             = 715493688;      // Magic number

//---

double   m_stop_loss                = 0.0;      // Stop Loss                  -> double

double   m_take_profit              = 0.0;      // Take Profit                -> double



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



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

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

   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;

   m_stop_loss                = InpStopLoss                 * m_symbol.Point();

   m_take_profit              = InpTakeProfit               * m_symbol.Point();

//--- check the input parameter "Lots"

   string err_text="";

   if(InpLotOrRisk==lot)

     {

      if(!CheckVolumeValue(InpVolumeLotOrRisk,err_text))

        {

         //--- when testing, we will only output to the log about incorrect input parameters

         if(MQLInfoInteger(MQL_TESTER))

           {

            Print(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

            return(INIT_FAILED);

           }

         else // if the Expert Advisor is run on the chart, tell the user about the error

           {

            Alert(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

            return(INIT_PARAMETERS_INCORRECT);

           }

        }

     }

//--- create handle of the indicator iMA

   handle_iMA=iMA(m_symbol.Name(),Period(),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(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()

  {

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

   datetime time_0=iTime(m_symbol.Name(),InpWorkingPeriod,0);

   if(time_0==m_prev_bars)

      return;

   m_prev_bars=time_0;

   if(IsPositionExists())

      return;

   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 the correctness of the position volume                     |

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

bool CheckVolumeValue(double volume,string &error_description)

  {

//--- minimal allowed volume for trade operations

   double min_volume=m_symbol.LotsMin();

   if(volume<min_volume)

     {

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

         error_description=StringFormat("1J5< <5=LH5 <8=8<0;L=> 4>?CAB8<>3> SYMBOL_VOLUME_MIN=%.2f",min_volume);

      else

         error_description=StringFormat("Volume is less than the minimal allowed SYMBOL_VOLUME_MIN=%.2f",min_volume);

      return(false);

     }

//--- maximal allowed volume of trade operations

   double max_volume=m_symbol.LotsMax();

   if(volume>max_volume)

     {

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

         error_description=StringFormat("1J5< 1>;LH5 <0:A8<0;L=> 4>?CAB8<>3> SYMBOL_VOLUME_MAX=%.2f",max_volume);

      else

         error_description=StringFormat("Volume is greater than the maximal allowed SYMBOL_VOLUME_MAX=%.2f",max_volume);

      return(false);

     }

//--- get minimal step of volume changing

   double volume_step=m_symbol.LotsStep();

   int ratio=(int)MathRound(volume/volume_step);

   if(MathAbs(ratio*volume_step-volume)>0.0000001)

     {

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

         error_description=StringFormat("1J5< =5 :@0B5= <8=8<0;L=><C H03C SYMBOL_VOLUME_STEP=%.2f, 1;8609H89 ?@028;L=K9 >1J5< %.2f",

                                        volume_step,ratio*volume_step);

      else

         error_description=StringFormat("Volume is not a multiple of the minimal step SYMBOL_VOLUME_STEP=%.2f, the closest correct volume is %.2f",

                                        volume_step,ratio*volume_step);

      return(false);

     }

   error_description="Correct volume value";

   return(true);

  }

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

//| Open position                                                    |

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

void OpenPosition(const ENUM_POSITION_TYPE pos_type)

  {

   double stops=0.0; // the lightest example: "SYMBOL_TRADE_STOPS_LEVEL" are not checked

   /*

   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

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

   */

//--- buy

   if(pos_type==POSITION_TYPE_BUY)

     {

      double sl=(m_stop_loss==0.0)?0.0:m_symbol.Ask()-m_stop_loss;

      if(sl>0.0)

         if(m_symbol.Bid()-sl<stops)

            sl=m_symbol.Bid()-stops;

      double tp=(m_take_profit==0.0)?0.0:m_symbol.Ask()+m_take_profit;

      if(tp>0.0)

         if(tp-m_symbol.Ask()<stops)

            tp=m_symbol.Ask()+stops;

      OpenBuy(sl,tp);

      return;

     }

//--- sell

   if(pos_type==POSITION_TYPE_SELL)

     {

      double sl=(m_stop_loss==0.0)?0.0:m_symbol.Bid()+m_stop_loss;

      if(sl>0.0)

         if(sl-m_symbol.Ask()<stops)

            sl=m_symbol.Ask()+stops;

      double tp=(m_take_profit==0.0)?0.0:m_symbol.Bid()-m_take_profit;

      if(tp>0.0)

         if(m_symbol.Bid()-tp<stops)

            tp=m_symbol.Bid()-stops;

      OpenSell(sl,tp);

      return;

     }

  }

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

//| Open Buy position                                                |

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

void OpenBuy(double sl,double tp)

  {

   sl=m_symbol.NormalizePrice(sl);

   tp=m_symbol.NormalizePrice(tp);

   double long_lot=0.0;

//---

   if(InpLotOrRisk==lot)

      long_lot=InpVolumeLotOrRisk;

   else

      if(InpLotOrRisk==lots_min)

         long_lot=m_symbol.LotsMin();

      else

         return;

//--- check volume before OrderSend to avoid "not enough money" error (CTrade)

   double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),ORDER_TYPE_BUY,long_lot,m_symbol.Ask());

   double margin_check=m_account.MarginCheck(m_symbol.Name(),ORDER_TYPE_BUY,long_lot,m_symbol.Ask());

   if(free_margin_check>margin_check)

     {

      if(!m_trade.Buy(long_lot,m_symbol.Name(),m_symbol.Ask(),sl,tp)) // CTrade::Buy -> "false"

         if(InpPrintLog)

            Print(__FILE__," ",__FUNCTION__,", ERROR: ","#1 Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),

                  ", description of result: ",m_trade.ResultRetcodeDescription());

     }

   else

     {

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","CAccountInfo.FreeMarginCheck returned the value ",DoubleToString(free_margin_check,2));

      return;

     }

//---

  }

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

//| Open Sell position                                               |

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

void OpenSell(double sl,double tp)

  {

   sl=m_symbol.NormalizePrice(sl);

   tp=m_symbol.NormalizePrice(tp);

   double short_lot=0.0;

//---

   if(InpLotOrRisk==lot)

      short_lot=InpVolumeLotOrRisk;

   else

      if(InpLotOrRisk==lots_min)

         short_lot=m_symbol.LotsMin();

      else

         return;

//--- check volume before OrderSend to avoid "not enough money" error (CTrade)

   double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),ORDER_TYPE_SELL,short_lot,m_symbol.Bid());

   double margin_check=m_account.MarginCheck(m_symbol.Name(),ORDER_TYPE_SELL,short_lot,m_symbol.Bid());

   if(free_margin_check>margin_check)

     {

      if(!m_trade.Sell(short_lot,m_symbol.Name(),m_symbol.Bid(),sl,tp)) // CTrade::Sell -> "false"

         if(InpPrintLog)

            Print(__FILE__," ",__FUNCTION__,", ERROR: ","#1 Sell -> false. Result Retcode: ",m_trade.ResultRetcode(),

                  ", description of result: ",m_trade.ResultRetcodeDescription());

     }

   else

     {

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", ERROR: ","CAccountInfo.FreeMarginCheck returned the value ",DoubleToString(free_margin_check,2));

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

  }

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

//| Search trading signals                                           |

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

bool SearchTradingSignals(void)

  {

   double ma[];

   MqlRates rates[];

   ArraySetAsSeries(ma,true);

   ArraySetAsSeries(rates,true);

   int start_pos=0,count=6;

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

      return(false);

//---

   if(rates[1].open<rates[1].close && rates[1].close>ma[1])

     {

      OpenPosition(POSITION_TYPE_BUY);

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", OK: ","Signal BUY");

      return(true);

     }

   if(rates[1].close<rates[1].open && rates[1].close<ma[1])

     {

      OpenPosition(POSITION_TYPE_SELL);

      if(InpPrintLog)

         Print(__FILE__," ",__FUNCTION__,", OK: ","Signal SELL");

      return(true);

     }

//---

   return(true);

  }

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

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

            return(true);

//---

   return(false);

  }

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

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