How to start with MQL5 - page 8

 

Simple EA Three iMA

Code: Simple EA Three iMA.mq5

You are making a gross mistake: in MQL5, the work with receiving indicator data is divided into two steps.

  1. Step 1: create the HANDL of the indicator (THIS IS DONE ONLY ONCE - In OnInit !!!). 
  2. Step 2: get the data (as a rule, this is done in OnTick ().

//+------------------------------------------------------------------+
//|                                              Simple EA Three iMA |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//---
#include <Trade\Trade.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input int                  Inp_Small_MA_ma_period        = 20;          // Small MA: averaging period
input int                  Inp_Small_MA_ma_shift         = 0;           // Small MA: horizontal shift
input ENUM_MA_METHOD       Inp_Small_MA_ma_method        = MODE_EMA;    // Small MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_Small_MA_applied_price    = PRICE_CLOSE; // Small MA: type of price
input int                  Inp_Middle_MA_ma_period       = 50;          // Middle MA: averaging period
input int                  Inp_Middle_MA_ma_shift        = 0;           // Middle MA: horizontal shift
input ENUM_MA_METHOD       Inp_Middle_MA_ma_method       = MODE_EMA;    // Middle MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_Middle_MA_applied_price   = PRICE_CLOSE; // Middle MA: type of price
input int                  Inp_Big_MA_ma_period          = 1000;        // Big MA: averaging period
input int                  Inp_Big_MA_ma_shift           = 0;           // Big MA: horizontal shift
input ENUM_MA_METHOD       Inp_Big_MA_ma_method          = MODE_EMA;    // Big MA: smoothing type
input ENUM_APPLIED_PRICE   Inp_Big_MA_applied_price      = PRICE_CLOSE; // Big MA: type of price
//---
input ushort   InpStopLossBuy    = 100;      // Stop Loss Buy, in points (1.00045-1.00055=10 points)
input ushort   InpTakeProfitBuy  = 100;      // Take Profit Buy, in points (1.00045-1.00055=10 points)
input ushort   InpStopLossSell   = 100;      // Stop Loss Sell, in points (1.00045-1.00055=10 points)
input ushort   InpTakeProfitSell = 100;      // Take Profit Sell, in points (1.00045-1.00055=10 points)
//---
double   m_stop_loss_buy            = 0.0;      // Stop Loss Buy           -> double
double   m_take_profit_buy          = 0.0;      // Take Profit Buy         -> double
double   m_stop_loss_sell           = 0.0;      // Stop Loss Sell          -> double
double   m_take_profit_sell         = 0.0;      // Take Profit Sell        -> double

int      handle_iMA_Small;                      // variable for storing the handle of the iMA indicator
int      handle_iMA_Middle;                     // variable for storing the handle of the iMA indicator
int      handle_iMA_Big;                        // variable for storing the handle of the iMA indicator

datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   m_trade.SetExpertMagicNumber(159);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(30);
//---
   m_stop_loss_buy         = InpStopLossBuy     * Point();
   m_take_profit_buy       = InpTakeProfitBuy   * Point();
   m_stop_loss_sell        = InpStopLossSell    * Point();
   m_take_profit_sell      = InpTakeProfitSell  * Point();
//--- create handle of the indicator iMA
   handle_iMA_Small=iMA(Symbol(),Period(),Inp_Small_MA_ma_period,Inp_Small_MA_ma_shift,
                        Inp_Small_MA_ma_method,Inp_Small_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA_Small==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Small\") for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Middle=iMA(Symbol(),Period(),Inp_Middle_MA_ma_period,Inp_Middle_MA_ma_shift,
                         Inp_Middle_MA_ma_method,Inp_Middle_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA_Middle==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Middle\") for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Big=iMA(Symbol(),Period(),Inp_Big_MA_ma_period,Inp_Big_MA_ma_shift,
                      Inp_Big_MA_ma_method,Inp_Big_MA_applied_price);
//--- if the handle is not created
   if(handle_iMA_Big==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Big\") for the symbol %s/%s, error code %d",
                  Symbol(),
                  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(Symbol(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;

   if(PositionsTotal()>0)
      return;
//---
   double SmallMovingAverageArray[],MiddleMovingAverageArray[],BigMovingAverageArray[];
   ArraySetAsSeries(SmallMovingAverageArray,true);
   ArraySetAsSeries(MiddleMovingAverageArray,true);
   ArraySetAsSeries(BigMovingAverageArray,true);
   int start_pos=0,count=6;
   if(!iGetArray(handle_iMA_Small,0,start_pos,count,SmallMovingAverageArray) ||
      !iGetArray(handle_iMA_Middle,0,start_pos,count,MiddleMovingAverageArray) ||
      !iGetArray(handle_iMA_Big,0,start_pos,count,BigMovingAverageArray))
     {
      return;
     }

   MqlTick tick;
   if(!SymbolInfoTick(Symbol(),tick))
      return;

   if(SmallMovingAverageArray[1]<MiddleMovingAverageArray[1]&&MiddleMovingAverageArray[1]<BigMovingAverageArray[1])
     {
      m_trade.Buy(1.00,Symbol(),tick.ask,tick.ask-m_stop_loss_buy,tick.ask+m_take_profit_buy);
      return;
     }

   if(SmallMovingAverageArray[1]>MiddleMovingAverageArray[1]&&MiddleMovingAverageArray[1]>BigMovingAverageArray[1])
     {
      m_trade.Sell(1.00,Symbol(),tick.bid,tick.bid+m_stop_loss_sell,tick.bid-m_take_profit_sell);
      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))
     {
      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
      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);
  }
//+------------------------------------------------------------------+
Files:
 
Can someone help me plot vertical lines and trend lines on chart based on close of specific candles, like close[10] and close[1], vertical lines on both candles and a trend line connecting them both. Thanks
 
GeorgeReji :
Can someone help me plot vertical lines and trend lines on chart based on close of specific candles, like close[10] and close[1], vertical lines on both candles and a trend line connecting them both. Thanks

Here is the code (use Lines of specific candles.mq5)

Lines of specific candles

The code from the help (s) is almost completely used. A little optimization was introduced (to reduce the number of redrawing objects) and a check for the presence of objects was introduced (we check every three seconds: if one of the lines is deleted, we create it again).

Vertical lines are created in 'VLineCreate'. The trend line is created in 'TrendCreate'. Moving vertical lines is done in 'VLineMove', and the trend line is moved by moving anchor points in 'TrendPointChange'.

 
I'm new here. Do you have any advice how I best evaluate and measure performance between different expert and signals I run after a few weeks?
 
Magnus Thysell :
I'm new here. Do you have any advice how I best evaluate and measure performance between different expert and signals I run after a few weeks?

Read carefully the first post of this thread. You have come to the wrong address.

 
Vladimir Karputov:

Here is the code (use Lines of specific candles.mq5)


The code from the help (s) is almost completely used. A little optimization was introduced (to reduce the number of redrawing objects) and a check for the presence of objects was introduced (we check every three seconds: if one of the lines is deleted, we create it again).

Vertical lines are created in 'VLineCreate'. The trend line is created in 'TrendCreate'. Moving vertical lines is done in 'VLineMove', and the trend line is moved by moving anchor points in 'TrendPointChange'.

Thanks man, cleared it out for me 
 
How would one code heiken ashi candles ? For example using CopyClose to copy to aray close[] and if close[1]>ma11[1] is the logic, how would i go about coding this ?
 
GeorgeReji :
How would one code heiken ashi candles ? For example using CopyClose to copy to aray close[] and if close[1]>ma11[1] is the logic, how would i go about coding this ?

Specify: Are you asking about what type of program - an advisor or an indicator?

 
Vladimir Karputov:

Specify: Are you asking about what type of program - an advisor or an indicator?

i want to use heiken ashi in an expert advisor, confused as to how i get OHLC of heiken ashi

 
GeorgeReji :

i want to use heiken ashi in an expert advisor, confused as to how i get OHLC of heiken ashi

is heiken ashi an indicator? Where is the link to the indicator?

Reason: