How to start with MQL5 - page 33

 
DroidM # :
Im confused as to how i can go about accessing a desired candle on a higher timeframe. For example, an array of candle closes for 1 min candles is close[]
My strategy picked out close[8] which was at 1.69230 how can i find out on which candle in the m5 chart was at 1.69230

CopyRates must be used.

Example:

//+------------------------------------------------------------------+
//|                                                     Script 1.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.000"
#property script_show_inputs
//--- input parameters
input ENUM_TIMEFRAMES   Inp_period  = PERIOD_D1;   // Timeframe
//---
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=9;
   if(CopyRates(Symbol(),Inp_period,start_pos,count,rates)==count)
     {
      string text="";
      for(int i=0; i<count; i++)
         text=text+"Close #"+IntegerToString(i)+" "+DoubleToString(rates[i].close,Digits())+"\n";
      Print(text);
     }
//---
  }
//+------------------------------------------------------------------+

Result:

2021.11.13 10:12:04.265 Script 1 (AUDCAD,M20)   Close #0 0.91977
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #1 0.91685
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #2 0.91525
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #3 0.91752
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #4 0.92345
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #5 0.92193
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #6 0.92177
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #7 0.92280
2021.11.13 10:12:04.266 Script 1 (AUDCAD,M20)   Close #8 0.92194
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
  • www.mql5.com
CopyRates - Timeseries and Indicators Access - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Files:
Script_1.mq5  3 kb
 
Vladimir Karputov #:

CopyRates must be used.

Example:

Result:

I guess i confused you with my question, i use an ea that looks for divergence using Bollinger bands, on a sell trade, the high and the higher high need to close above the Bollinger band , the higher high is the 1st candle i.e close[1], and the high candle can be any candle from close[5] to close[50], for example the high is at close[11] i would like to check to see if that price(close[11]) had crossed Bollinger band on m5 chart as well
 
DroidM # :
I guess i confused you with my question, i use an ea that looks for divergence using Bollinger bands, on a sell trade, the high and the higher high need to close above the Bollinger band , the higher high is the 1st candle i.e close[1], and the high candle can be any candle from close[5] to close[50], for example the high is at close[11] i would like to check to see if that price(close[11]) had crossed Bollinger band on m5 chart as well

Do not rush to answer - carefully study my example.

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

Do not rush to answer - carefully study my example.

Yes, i understood that bit, on audcad m20, you were able to get closing prices of the daily candles.
But in my case close[11]  will neither be open, high, low, close on the m5 candle, just in between, how do i grab the index of the m5 candle that i want to check ?
 

How to get iFrAMA indicator data

Code: 'iFrAMA get value.mq5'

Remember - according to the MQL5 style, the indicator handle must be created in OnInit !!!

Example:

//+------------------------------------------------------------------+
//|                                             iFrAMA get value.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//--- input parameters
input group             "FrAMA"
input int                  Inp_FrAMA_ma_period           = 14;             // FrAMA: averaging period
input int                  Inp_FrAMA_ma_shift            = 0;              // FrAMA: horizontal shift of indicator
input ENUM_APPLIED_PRICE   Inp_FrAMA_applied_price       = PRICE_CLOSE;    // FrAMA: type of price
input group                "Additional features"
input bool                 InpPrintLog          = false;       // Print log
//---
int      handle_iFrAMA;                         // variable for storing the handle of the iFrAMA indicator
bool     m_init_error               = false;    // error on InInit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator
   handle_iFrAMA=iFrAMA(Symbol(),Period(),Inp_FrAMA_ma_period,
                        Inp_FrAMA_ma_shift,Inp_FrAMA_applied_price);
//--- if the handle is not created
   if(handle_iFrAMA==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iFrAMA indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//---
   ChartIndicatorAdd(ChartID(),0,handle_iFrAMA);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   if(handle_iFrAMA!=INVALID_HANDLE)
      IndicatorRelease(handle_iFrAMA);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(m_init_error)
      return;
//---
   double frama[];
   ArraySetAsSeries(frama,true);
   int start_pos=0,count=3;
   if(!iGetArray(handle_iFrAMA,0,start_pos,count,frama))
      return;
//---
   string text="";
   int limit=(count>3)?3:count;
   for(int i=0; i<limit; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " FrAMA "+DoubleToString(frama[i],Digits()+1)+"\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+
//| 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:

iFrAMA get value

Pic. 1. iFrAMA get value

Files:
 

An example of using 'CopyRates' and 'MqlRates'

Code: 'CopyRates and MqlRates.mq5'

We will use 'CopyRates', the first form of the call:

Call by the first position and the number of required elements

int  CopyRates(
   string           symbol_name,       // symbol name
   ENUM_TIMEFRAMES  timeframe,         // period
   int              start_pos,         // start position
   int              count,             // data count to copy
   MqlRates         rates_array[]      // target array to copy
   );

Code:

//+------------------------------------------------------------------+
//|                                       CopyRates and MqlRates.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.00"
//--- input parameters
input int      Input1=9;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
  }
//+------------------------------------------------------------------+
//| 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;
//---
   string text="";
   for(int i=0; i<count; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " time "+TimeToString(rates[i].time,TIME_DATE|TIME_MINUTES)+": "+
           " open "+DoubleToString(rates[i].open,Digits())+"\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+

Result:




Documentation on MQL5: Timeseries and Indicators Access / CopyRates
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
  • www.mql5.com
CopyRates - Timeseries and Indicators Access - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

Opening and modifying positions:

Opening and modifying positions

 

A simple advisor: there are always two opposite positions in the market

Code: 'Open Two Positions.mq5'

//+------------------------------------------------------------------+
//|                                           Open Two Positions.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input group             "Trading settings"
input uint                 InpStopLoss             = 450;            // Stop Loss
input uint                 InpTakeProfit           = 450;            // Take Profit
input group             "Position size management (lot calculation)"
input double               InpLots                 = 0.01;           // Lots
input group             "Additional features"
input ulong                InpDeviation            = 10;             // Deviation, in Points (1.00045-1.00055=10 points)
input ulong                InpMagic                = 200;            // Magic number
//---
double   m_stop_loss                = 0.0;      // Stop Loss                  -> double
double   m_take_profit              = 0.0;      // Take Profit                -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   double point=0.0;
   if(!SymbolInfoDouble(Symbol(),SYMBOL_POINT,point))
      return(INIT_FAILED);
   m_stop_loss                = InpStopLoss                 * point;
   m_take_profit              = InpTakeProfit               * point;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   int count_buys=0,count_sells=0;
   CalculateAllPositions(count_buys,count_sells);
   if(count_buys==0 || count_sells==0)
     {
      MqlTick tick;
      if(!SymbolInfoTick(Symbol(),tick))
         return;
      if(count_buys==0)
         m_trade.Buy(InpLots,Symbol(),tick.ask,tick.ask-m_stop_loss,tick.ask+m_take_profit);
      if(count_sells==0)
         m_trade.Sell(InpLots,Symbol(),tick.bid,tick.bid+m_stop_loss,tick.bid-m_take_profit);
     }
  }
//+------------------------------------------------------------------+
//| Calculate all positions Buy and Sell                             |
//+------------------------------------------------------------------+
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()==Symbol() && m_position.Magic()==InpMagic)
           {
            if(m_position.PositionType()==POSITION_TYPE_BUY)
               count_buys++;
            if(m_position.PositionType()==POSITION_TYPE_SELL)
               count_sells++;
           }
//---
   return;
  }
//+------------------------------------------------------------------+
Files:
 

Dear Vladimir,


i want to ask about PostitionCloseBy.

Say BuyStop triggered, it closes Sell Position.. Thanks in advance..