Different moving average value...

 

Hi guys,

I've made a simple code to buy when the price is above the moving average and sell is the price is below the moving average everytime that there is no position open.  I checked the backtest and saw that the code is not performing as I wanted and only performs buy trades.  I printed the moving average value to make sure that the buy signal is really triggered only if the price is above the MA value.  The moving average value printed in the journal tab is very different from the one that is displayed in the chart:

Here's my short code: 

//+------------------------------------------------------------------+
//|                                                     MAATRGas.mq5 |
//|                        Copyright 2010, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"

#include "D:\Metatrader 5\MQL5\Include\ExpertAdvisor.mqh"

input int    SL        =  25; // Stop Loss distance
input int    TP        =  45; // Take Profit distance
input int    TS        =  45; // Trailing Stop distance
input int    MAPer     =  8; // MA period
input double Risk      = 0.1; // Risk

//---
class CMyEA : public CExpertAdvisor
  {
protected:
   double            m_risk;          // size of risk
   int               m_sl;            // Stop Loss
   int               m_tp;            // Take Profit
   int               m_ts;            // Trailing Stop
   int               m_MAPer;         // MA period
   int               m_hma;           // SMA indicator handle       
public:
   void              CMyEA();
   void             ~CMyEA();
   virtual bool      Init(string smb,ENUM_TIMEFRAMES tf); // initialization
   virtual bool      Main();                              // main function
   virtual void      OpenPosition(long dir);              // open position on signal
   virtual void      ClosePosition(long dir);             // close position on signal
   virtual long      CheckSignal(bool bEntry);            // check signal
  };
//------------------------------------------------------------------    CMyEA
void CMyEA::CMyEA() { }
//------------------------------------------------------------------    ~CMyEA
void CMyEA::~CMyEA()
  {
   IndicatorRelease(m_hma);   // delete MA indicator
  }
//------------------------------------------------------------------    Init
bool CMyEA::Init(string smb,ENUM_TIMEFRAMES tf)
  {
   if(!CExpertAdvisor::Init(0,smb,tf)) return(false);                                // initialize parent class

   m_risk=Risk; m_tp=TP; m_sl=SL; m_ts=TS;                                           // copy parameters
   m_MAPer=MAPer;
   m_hma=iMA(m_smb,PERIOD_D1,m_MAPer,0,MODE_EMA,PRICE_CLOSE);                     // create MA indicator
   if(m_hma==INVALID_HANDLE) return(false);              // if there is an error, then exit
  
   m_bInit=true; return(true);                                                       // trade allowed
  }
//------------------------------------------------------------------    Main
bool CMyEA::Main() // main function
  {
   if(!CExpertAdvisor::Main()) return(false); // call function of parent class

   if(Bars(m_smb,m_tf)<=100) return(false);   // if there are insufficient number of bars

   if(!CheckNewBar()) return(true);           // check new bar

                                              // check each direction
   long dir;
   dir=ORDER_TYPE_BUY;
   OpenPosition(dir); ClosePosition(dir); TrailingPosition(dir,m_ts);
   dir=ORDER_TYPE_SELL;
   OpenPosition(dir); ClosePosition(dir); TrailingPosition(dir,m_ts);

   return(true);
  }
//------------------------------------------------------------------    OpenPos
void CMyEA::OpenPosition(long dir)
  {
// if there is an order, then exit
   if(PositionSelect(m_smb)) return;
// if there is no signal for current direction
   if(dir!=CheckSignal(true)) return;
   double lot=CountLotByRisk(m_sl,m_risk,0);
// if lot is not defined
   if(lot<=0) return;
// open position
   {
   Print("position opened");
   DealOpen(dir,lot,m_sl,m_tp);
   }
  // printf(atr[1]);
  }
//------------------------------------------------------------------    ClosePos
void CMyEA::ClosePosition(long dir)
  {
// if there is no position, then exit
   if(!PositionSelect(m_smb)) return;
// if position of unchecked direction
   if(dir!=PositionGetInteger(POSITION_TYPE)) return;
// if the close signal didn't match the current position
   if(dir!=CheckSignal(false)) return;
// close position
   {
   Print("position closed");
   m_trade.PositionClose(m_smb,1);
   }
  }
//------------------------------------------------------------------    CheckSignal
long CMyEA::CheckSignal(bool bEntry)
  {
   double ma[],     // Array of MA indicator values
          atr[3];
   MqlRates rt[];   
   ArraySetAsSeries(rt,true);
   ArraySetAsSeries(ma,true);
   if(CopyRates(m_smb,m_tf,0,100,rt)<0) // Copy price values of last 100 bars to array
     { Print("CopyRates ",m_smb," history is not loaded"); return(WRONG_VALUE); }
   // Copy indicator values to array
   if(CopyBuffer(m_hma,0,0,100,ma)<0)
     { Print("CopyBuffer - no data"); return(WRONG_VALUE); }
   if(rt[0].close>ma[0])
   {      
      if(bEntry)
         {
         Print("price: " + rt[0].open + " MA: " + ma[0] + "CONDITION 1"); //display value
         return(ORDER_TYPE_BUY);
         }
   }
   else if(rt[0].close<ma[0])
   {
      if(bEntry)
         {
         Print("price: " + rt[0].open + "MA: " + ma[0] + "CONDITION 2"); //display value
         return(ORDER_TYPE_SELL);
         }
   }
   return(WRONG_VALUE); // if there is no signal
  }

CMyEA ea; // class instance
//------------------------------------------------------------------    OnInit
int OnInit()
  {
   ea.Init(Symbol(),Period());   // initialize expert
                                 // initialization example
// ea.Init(Symbol(), PERIOD_M5); // for fixed timeframe
// ea.Init("USDJPY", PERIOD_H2); // for fixed symbol and timeframe

   return(0);
  }
//------------------------------------------------------------------    OnDeinit
void OnDeinit(const int reason) { }
//------------------------------------------------------------------    OnTick
void OnTick()
  {
   ea.Main(); // process incoming tick
  }
//+------------------------------------------------------------------+

 Appreciate if anyone could help me solve this issue, probably I'm not using the iMA() function correctly? 

Thanks in advance!:D 

 

 
Also, I tried changing the moving average period from 8 to 100.  The results did not change(same profit/loss, statistics etc), it seems that the moving average is not being used properly in my program or not being used at all.  
 
polymath:

Hi guys,

I've made a simple code to buy when the price is above the moving average and sell is the price is below the moving average everytime that there is no position open.  I checked the backtest and saw that the code is not performing as I wanted and only performs buy trades.  I printed the moving average value to make sure that the buy signal is really triggered only if the price is above the MA value.  The moving average value printed in the journal tab is very different from the one that is displayed in the chart:

Here's my short code: 

 Appreciate if anyone could help me solve this issue, probably I'm not using the iMA() function correctly? 

Thanks in advance!:D 

 

The problem might be in your 'main' function here

   long dir;
   dir=ORDER_TYPE_BUY;
   OpenPosition(dir); ClosePosition(dir); TrailingPosition(dir,m_ts);
   dir=ORDER_TYPE_SELL;
   OpenPosition(dir); ClosePosition(dir); TrailingPosition(dir,m_ts);


Assuming this is your source, or you acquired it legally, try this

dir=CheckSignal(true);
OpenPosition(dir); ClosePosition(dir); TrailingPosition(dir,m_ts);
 
ssn:

The problem might be in your 'main' function here

Assuming this is your source, or you acquired it legally, try this

Hi ssn,

I think this will solve the problem for the order types, but do you know how I can fix the wrong MA value being displayed?  

Thank you very much! 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Trade Constants / Order Properties
  • www.mql5.com
Standard Constants, Enumerations and Structures / Trade Constants / Order Properties - Documentation on MQL5
 
polymath:

Hi ssn,

I think this will solve the problem for the order types, but do you know how I can fix the wrong MA value being displayed?  

Thank you very much! 

Hi Polymath,

For the incorrect MA value I may not be of much help because I actually use the standard library class CiMA and I have now forgotten (or am out of touch) with the first principles initialization of an indicator. However you could try tweaking the MA setting of Set as Series... beyond that I cannot help much besides encouraging you to also use CiMA... :-)


 
ssn:

Hi Polymath,

For the incorrect MA value I may not be of much help because I actually use the standard library class CiMA and I have now forgotten (or am out of touch) with the first principles initialization of an indicator. However you could try tweaking the MA setting of Set as Series... beyond that I cannot help much besides encouraging you to also use CiMA... :-)


Thanks ssn!  I'll try to spend some time reading about CiMA :D Thanks a lot for your help! 
 

Hi Polymath,

I wonder if you managed to find a solution to your problem. As I understand it, you're getting a difference to what's displayed on the graph & what's being

returned to you in the program. I have a similar problem in that my returned values for high,low,open & close values (MqlRates mrate[];) & entirely different from from the

ones displayed on the graph. Consequently, I find that the EA behaves randomly & erracticly producing erronous results. Thus I'm searching this forum

to see if anybody else has experienced similar problems.

 

If anybody else has found this type of bug, please feel free to comment. I want to be able to make progress & this issue has completely stopped me in 

my tracks.

 

Thanks in advance. 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Data Structures / History Data Structure
  • www.mql5.com
Standard Constants, Enumerations and Structures / Data Structures / History Data Structure - Documentation on MQL5