Simple iFractal EA

Author: Copyright © 2020, Vladimir Karputov
Price Data Components
Indicators Used
Fractals
0 Views
0 Downloads
0 Favorites
Simple iFractal EA
ÿþ//+------------------------------------------------------------------+

//|                                           Simple iFractal EA.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"

#property description "There is only one position in the market"

#property description "We check the signal only at the moment of the birth of a new bar"

#property description "The position volume is always equal to the minimum lot. No trailing"

#property description " "

#property description "If there is a BUY position in the market and We have received a signal to open SELL:"

#property description "--- close the BUY position and open SELL"

#property description "If there is a SELL position in the market and We have received a signal to open a BUY:"

#property description "--- close the SELL position and open a BUY"

/*

   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

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

//--- input parameters

input group             "Trading settings"

input uint     InpStopLoss          = 600;         // Stop Loss

input uint     InpTakeProfit        = 900;         // Take Profit

input group             "Additional features"

input bool     InpPrintLog          = false;       // Print log

input ulong    InpDeviation         = 10;          // Deviation

input ulong    InpMagic             = 610108050;   // Magic number

//---

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

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



int      handle_iFractals;                      // variable for storing the handle of the iFractals indicator

bool     m_need_close_all           = false;    // close all positions

bool     m_need_open_buy            = false;    // open BUY position

bool     m_need_open_sell           = false;    // open SELL position

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

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

//| Expert initialization function                                   |

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

int OnInit()

  {

//---

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

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

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

      digits_adjust=10;

   m_stop_loss                = InpStopLoss                 * m_symbol.Point();

   m_take_profit              = InpTakeProfit               * m_symbol.Point();

//--- create handle of the indicator iFractals

   handle_iFractals=iFractals(m_symbol.Name(),Period());

//--- if the handle is not created

   if(handle_iFractals==INVALID_HANDLE)

     {

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

      PrintFormat("Failed to create handle of the iFractals 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()

  {

   if(m_need_close_all)

     {

      int count_buys    = 0;

      int count_sells   = 0;

      CalculateAllPositions(count_buys,count_sells);

      if(count_buys+count_sells>0)

        {

         CloseAllPositions();

         return;

        }

      else

         m_need_close_all=false;

     }

   if(m_need_open_buy)

     {

      if(!RefreshRates())

         return;

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

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

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

      double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),

                               ORDER_TYPE_BUY,

                               m_symbol.LotsMin(),

                               m_symbol.Ask());

      double margin_check=m_account.MarginCheck(m_symbol.Name(),

                          ORDER_TYPE_BUY,

                          m_symbol.LotsMin(),

                          m_symbol.Ask());

      if(free_margin_check>margin_check)

        {

         if(InpPrintLog)

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

         m_trade.Buy(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Ask(),sl,tp);

        }

      m_need_open_buy=false;

     }

   if(m_need_open_sell)

     {

      if(!RefreshRates())

         return;

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

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

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

      double free_margin_check=m_account.FreeMarginCheck(m_symbol.Name(),

                               ORDER_TYPE_SELL,

                               m_symbol.LotsMin(),

                               m_symbol.Ask());

      double margin_check=m_account.MarginCheck(m_symbol.Name(),

                          ORDER_TYPE_SELL,

                          m_symbol.LotsMin(),

                          m_symbol.Ask());

      if(free_margin_check>margin_check)

        {

         if(InpPrintLog)

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

         m_trade.Sell(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Bid(),sl,tp);

        }

      m_need_open_sell=false;

     }

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

//---

   double upper[],lower[];

   ArraySetAsSeries(upper,true);

   ArraySetAsSeries(lower,true);

   int start_pos=0,count=6;

   if(!iGetArray(handle_iFractals,UPPER_LINE,start_pos,count,upper) ||!iGetArray(handle_iFractals,LOWER_LINE,start_pos,count,lower))

     {

      m_prev_bars=0;

      return;

     }

   /*

   Fractal on bar #3 | Market

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

   Upper             | Buy

   Lower             | Sell

   */

   if(upper[3]!=0.0 && upper[3]!=EMPTY_VALUE)

     {

      int count_buys    = 0;

      int count_sells   = 0;

      CalculateAllPositions(count_buys,count_sells);

      if(count_buys>0)

         return;

      if(count_sells>0)

         m_need_close_all=true;

      m_need_open_buy=true;

      //---

      return;

     }

   if(lower[3]!=0.0 && lower[3]!=EMPTY_VALUE)

     {

      int count_buys    = 0;

      int count_sells   = 0;

      CalculateAllPositions(count_buys,count_sells);

      if(count_buys>0)

         m_need_close_all=true;

      if(count_sells>0)

         return;

      m_need_open_sell=true;

      //---

      return;

     }

  }

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

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

  }

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

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

  }

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

//| Calculate all positions                                          |

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

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

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

               count_buys++;

            else

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                  count_sells++;

           }

  }

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

//| Close all positions                                              |

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

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

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

  }

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



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

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