Simple Correlation EA

Author: Copyright © 2020, Vladimir Karputov
Price Data Components
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Simple Correlation EA
ÿþ//+------------------------------------------------------------------+

//|                                        Simple Correlation 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 "Trading strategy based on the article https://www.mql5.com/en/articles/5481"

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

#property tester_indicator "PearsonCorrelation"

#property tester_indicator "SpearmanCorrelation"

#property tester_indicator "KendallCorrelation"

#property tester_indicator "FechnerCorrelation"

/*

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

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

enum ENUM_STRATEGY_TYPE

  {

   DECREASE=0, // On Decrease

   INCREASE=1, // On Increase

  };

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

//| Enum Correlation type                                            |

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

enum ENUM_CORRELATION_TYPE

  {

   PEARSON=0,  // Pearson

   SPEARMAN=1, // Spearman

   KENDALL=2,  // Kendall

   FECHNER=3,  // Fechner

  };

//--- input parameters

input group             "Trading settings"

input ENUM_TIMEFRAMES         InpWorkingPeriod     = PERIOD_CURRENT; // Working timeframe

input uint                    InpStopLoss          = 600;            // Stop Loss

input uint                    InpTakeProfit        = 900;            // Take Profit

input group             "Position size management (lot calculation)"

input double                  InpLots              = 1.0;            // Lots

input group             "Strategy"

input ENUM_STRATEGY_TYPE      InpStrategyType      = DECREASE;       // Strategy type

input ENUM_CORRELATION_TYPE   InpCorrelationType   = PEARSON;        // Correlation type

input group             "Indicator"

input int                     InpRangeN            = 8;              // Rang Calculation

input double                  InpKeyLevel          = 0.7;            // Key Level

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_iCustom;                        // variable for storing the handle of the iCustom indicator



bool     m_need_close_buys          = false;    // close all BUY positions

bool     m_need_close_sells         = false;    // close all SELL 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();

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

   string err_text="";

   if(!CheckVolumeValue(InpLots,err_text))

     {

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

      if(MQLInfoInteger(MQL_TESTER))

        {

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

         return(INIT_FAILED);

        }

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

        {

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

         return(INIT_PARAMETERS_INCORRECT);

        }

     }

   string path="";

   switch(InpCorrelationType)

     {

      case 1:

         path="PearsonCorrelation";

         break;

      case 2:

         path="SpearmanCorrelation";

         break;

      case 3:

         path="KendallCorrelation";

         break;

      default:

         path="FechnerCorrelation";

         break;

     }

//--- create handle of the indicator iCustom

   handle_iCustom=iCustom(m_symbol.Name(),InpWorkingPeriod,path,InpRangeN);

//--- if the handle is not created

   if(handle_iCustom==INVALID_HANDLE)

     {

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

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

                  path,

                  m_symbol.Name(),

                  EnumToString(InpWorkingPeriod),

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

  {

//--- need close BUY positions OR SELL positions

   if(m_need_close_buys || m_need_close_sells)

     {

      int count_buys    = 0;

      int count_sells   = 0;

      CalculateAllPositions(count_buys,count_sells);

      //---

      if(m_need_close_buys)

        {

         if(count_buys>0)

           {

            ClosePositions(POSITION_TYPE_BUY);

            return;

           }

         else

            m_need_close_buys=false;

        }

      //---

      if(m_need_close_sells)

        {

         if(count_sells>0)

           {

            ClosePositions(POSITION_TYPE_SELL);

            return;

           }

         else

            m_need_close_sells=false;

        }

     }

//--- open BUY position

   if(m_need_open_buy)

     {

      if(!RefreshRates())

         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,

                               InpLots,

                               m_symbol.Ask());

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

                          ORDER_TYPE_BUY,

                          InpLots,

                          m_symbol.Ask());

      if(free_margin_check>margin_check)

        {

         if(InpPrintLog)

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

         m_trade.Buy(InpLots,m_symbol.Name(),m_symbol.Ask());

        }

      m_need_open_buy=false;

     }

//--- open SELL position

   if(m_need_open_sell)

     {

      if(!RefreshRates())

         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,

                               InpLots,

                               m_symbol.Ask());

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

                          ORDER_TYPE_SELL,

                          InpLots,

                          m_symbol.Ask());

      if(free_margin_check>margin_check)

        {

         if(InpPrintLog)

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

         m_trade.Sell(InpLots,m_symbol.Name(),m_symbol.Bid());

        }

      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 correlation[];

   ArraySetAsSeries(correlation,true);

   int start_pos=0,count=6;

   if(!iGetArray(handle_iCustom,0,start_pos,count,correlation))

     {

      m_prev_bars=0;

      return;

     }

   int count_buys    = 0;

   int count_sells   = 0;

   CalculateAllPositions(count_buys,count_sells);

//--- buy signal

   bool buy_signal=false;

   if(InpStrategyType==DECREASE)

      buy_signal=(correlation[2]<-InpKeyLevel && correlation[1]>-InpKeyLevel);

   else

      buy_signal=(correlation[2]<InpKeyLevel && correlation[1]>InpKeyLevel);

//--- sell signal

   bool sell_signal=false;

   if(InpStrategyType==DECREASE)

      sell_signal=(correlation[2]>InpKeyLevel && correlation[1]<InpKeyLevel);

   else

      sell_signal=(correlation[2]>-InpKeyLevel && correlation[1]<-InpKeyLevel);

//---

   if(buy_signal && sell_signal) // error, there cannot be two signals at once

      return;

   if(buy_signal && count_buys==0)

     {

      m_need_close_sells=true;

      m_need_open_buy=true;

      return;

     }

   if(sell_signal && count_sells==0)

     {

      m_need_close_buys=true;

      m_need_open_sell=true;

      return;

     }

  }

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

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

  }

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

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

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

void ClosePositions(const ENUM_POSITION_TYPE pos_type)

  {

   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_position.PositionType()==pos_type)

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