How to start with MQL5 - page 15

 

How to use the CSymbolInfo trade class

The code:

//+------------------------------------------------------------------+
//|                                               Display prices.mq5 |
//|                         Copyright © 2018-2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2018-2020, Vladimir Karputov"
#property version   "1.001"
//---
#include <Trade\SymbolInfo.mqh>
//---
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(!RefreshRates())
      return;
   Comment("Ask: ",DoubleToString(m_symbol.Ask(),m_symbol.Digits()),"\n",
           "Bid: ",DoubleToString(m_symbol.Bid(),m_symbol.Digits()));
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
Documentation on MQL5: Standard Library / Trade Classes / CSymbolInfo
Documentation on MQL5: Standard Library / Trade Classes / CSymbolInfo
  • www.mql5.com
CSymbolInfo - Trade Classes - Standard Library - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Files:
 
Hey, since i use loops to iterate through symbols and timeframes how can i place orders, modify and close them ?
 
Ahmad861 :
Hey, since i use loops to iterate through symbols and timeframes how can i place orders, modify and close them ?

Your question is not clear. I don’t understand your goal - you open a POSITION (not an order !!!) for a symbol. The timeframe does not matter here - the POSITION will be opened by the symbol. It's another matter when several strategies want to trade on a hedge account at once - then for each strategy you need to use its own 'Magic number'.

The simplest example is - Simple example One position

How to start with MQL5
How to start with MQL5
  • 2020.07.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 
Vladimir Karputov:

Your question is not clear. I don’t understand your goal - you open a POSITION (not an order !!!) for a symbol. The timeframe does not matter here - the POSITION will be opened by the symbol. It's another matter when several strategies want to trade on a hedge account at once - then for each strategy you need to use its own 'Magic number'.

The simplest example is - Simple example One position

Sorry for not making it clear, it's a scalping strategy, the EA will find a setup on M3 chart as well as M5 chart and open a position, i want to set take profit based on an indicator, in this case M3 chart, how would i go about this ?

 
Ahmad861 :

Sorry for not making it clear, it's a scalping strategy, the EA will find a setup on M3 chart as well as M5 chart and open a position, i want to set take profit based on an indicator, in this case M3 chart, how would i go about this ?

If Stop Loss is set using the indicator from the M3 timeframe, then you must create an indicator handle and specify the timeframe when creating it.

For example like this:

//+------------------------------------------------------------------+
//|                                                            1.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property link      "https://www.mql5.com"
#property version   "1.00"
//--- input parameters
input group             "MA"
input ENUM_TIMEFRAMES      Inp_MA_period        = PERIOD_M3;   // MA: timeframe
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
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iMA
   handle_iMA=iMA(m_symbol.Name(),Inp_MA_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(Inp_MA_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()
  {
//---
  }
//+------------------------------------------------------------------+
 

can you help me understand how to code the part that opens and closes positions, checks for existing postions etc.

I cant find an article that  clearly explains how to go about it, any suggestions from you would be grateful

 
Ahmad861:

can you help me understand how to code the part that opens and closes positions, checks for existing postions etc.

I cant find an article that  clearly explains how to go about it, any suggestions from you would be grateful

Simple Advisor with Stop Loss and Take Profit

How to start with MQL5
How to start with MQL5
  • 2020.03.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 

Intersection of two iMAs

Code: ' Example Intersection of two iMAs.mq5'

Task: determine the moment of intersection of two iMAs. 

The Expert Advisor code demonstrates how to get values from two iMA indicators (a dash of the 'Fast' value and three values for the 'Slow' are displayed).

Also, if an intersection is detected, a message is displayed on the screen.

//+------------------------------------------------------------------+
//|                             Example Intersection of two iMAs.mq5 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.000"
//--- input parameters
input group             "Moving Average 'Fast'"
input int                  Inp_MA_Fast_ma_period      = 3;           // MA Fast: averaging period
input int                  Inp_MA_Fast_ma_shift       = 0;           // MA Fast: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Fast_ma_method      = MODE_SMA;    // MA Fast: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Fast_applied_price  = PRICE_CLOSE; // MA Fast: type of price
input group             "Moving Average 'Slow'"
input int                  Inp_MA_Slow_ma_period      = 12;          // MA Slow: averaging period
input int                  Inp_MA_Slow_ma_shift       = 1;           // MA Slow: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Slow_ma_method      = MODE_SMA;    // MA Slow: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Slow_applied_price  = PRICE_CLOSE; // MA Slow: type of price
input group             "Additional features"
input bool                 InpPrintLog                = false;       // Print log
//---
bool     m_init_error               = false;    // error on InInit

int      handle_iMA_Fast;                       // variable for storing the handle of the iMA indicator
int      handle_iMA_Slow;                       // variable for storing the handle of the iMA indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iMA
   handle_iMA_Fast=iMA(Symbol(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift,
                       Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price);
//--- if the handle is not created
   if(handle_iMA_Fast==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Fast\") for the symbol %s/%s, error code %d",
                  Symbol(),Period(),GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Slow=iMA(Symbol(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift,
                       Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price);
//--- if the handle is not created
   if(handle_iMA_Slow==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator (\"Slow\") for the symbol %s/%s, error code %d",
                  Symbol(),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()
  {
//---
   double ma_fast[],ma_slow[];
   ArraySetAsSeries(ma_fast,true);
   ArraySetAsSeries(ma_slow,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iMA_Fast,0,start_pos,count,ma_fast) || !iGetArray(handle_iMA_Slow,0,start_pos,count,ma_slow))
      return;
   string ima_values="";
   for(int i=0; i<count; i++)
      ima_values=ima_values+IntegerToString(i)+": Fast "+DoubleToString(ma_fast[i],Digits()+1)+", Slow "+DoubleToString(ma_slow[i],Digits()+1)+"\n";
   string ima_intersections="no crossing";
   if(ma_fast[1]<ma_slow[1] && ma_fast[0]>ma_slow[0])
      ima_intersections="crossing up";
   else
      if(ma_fast[1]>ma_slow[1] && ma_fast[0]<ma_slow[0])
         ima_intersections="crossing down";
   Comment(ima_values+"\n"+ima_intersections);
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+


Result:

Example Intersection of two iMAs

How to start with MQL5
How to start with MQL5
  • 2020.03.05
  • www.mql5.com
This thread discusses MQL5 code examples. There will be examples of how to get data from indicators, how to program advisors...
 

We are waiting for the size of the current bar to reach the specified size

Code: Example Current candle size.mq5

//+------------------------------------------------------------------+
//|                                  Example Current candle size.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.001"
//+------------------------------------------------------------------+
//| Enum Pips Or Points                                              |
//+------------------------------------------------------------------+
enum ENUM_PIPS_OR_POINTS
  {
   pips=0,     // Pips (1.00045-1.00055=1 pips)
   points=1,   // Points (1.00045-1.00055=10 points)
  };
//--- input parameters
input ENUM_PIPS_OR_POINTS  InpPipsOrPoints   = pips;           // Pips Or Points:
input uint                 InpCandleSize     = 80;             // Candle: Size
//---
double   m_candle_size           = 0.0;      // Candle: Size               -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(Digits()==3 || Digits()==5)
      digits_adjust=10;
   double m_adjusted_point=Point()*digits_adjust;
   if(InpPipsOrPoints==pips) // Pips (1.00045-1.00055=1 pips)
     {
      m_candle_size              = InpCandleSize               * m_adjusted_point;
     }
   else // Points (1.00045-1.00055=10 points)
     {
      m_candle_size              = InpCandleSize               * Point();
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=3;
   if(CopyRates(Symbol(),Period(),start_pos,count,rates)!=count)
      return;
//--- signal search
   if(MathAbs(rates[0].open-rates[0].close)>=m_candle_size)
     {
      //--- the current candle has reached the specified size
      //--- Your code is here ...
      int d=0;
     }
  }
//+------------------------------------------------------------------+
 
So once bar size is reached, how can we get it to call on buy or sell?