Questions from Beginners MQL5 MT5 MetaTrader 5 - page 649

 
Artyom Trishkin:

I saw a piece of your code for finding zigzag vertices - I think it is from Igor Kim. Here, in the code of extremum search insert additionally the saving of the time of extremum found. You are looking for it in the loop... When identifying it, remember the time the loop index points to when the extremum is already identified - before returning the value of its price. I.e., additionally pass the datetime variable by reference into the function where the time at finding the extremum of the zigzag is to be written. When the function returns the value of the price, it will additionally write into this variable the value of the time of the bar opening where the required extremum of the zigzag is located.

I'm sorry, but I'm away from my work computer and I can't give you a code example.

It all worked out, Thanks!
 
Hello! I do a little writing in MQL4, but I'm not very good at MQL5. I need a little helper to calculate the difference between high and low for the day. The 4th version has good functions for this purpose iHigh and iLow, but they are absent here. I tried to use copyHigh and copyLow, but it keeps getting a lot of errors after subtracting the minimum value from the maximum one. Could you please tell me how to solve this problem, preferably with a code snippet. Thanks in advance!
 
Александр Богданов:
Hello! I do a little writing in MQL4, but I'm not very good at MQL5. I need a little helper to calculate the difference between high and low for the day. The 4th version has good functions for this purpose iHigh and iLow, but they are absent here. I tried to use copyHigh and copyLow, but it keeps getting a lot of errors after subtracting the minimum value from the maximum one. Could you please tell me how to solve this problem, preferably with a code snippet. Thanks in advance!
You'd better show me your code fragment with lots of errors and get a bunch of comments about what's wrong.
 
Александр Богданов:
Hello! I write a little bit in MQL4, however I am a complete zero in MQL5. Needed to write a little helper to calculate the difference between high and low for the day. The 4th version has good functions for this purpose iHigh and iLow, but they are absent here. I tried to use copyHigh and copyLow, but it keeps getting a lot of errors after subtracting the minimum value from the maximum one. Could you please tell me how to solve this problem, preferably with a code snippet. Thank you in advance!
Insert it at the beginning of the code

Forum on trading, automated trading systems and testing trading strategies

Testing 'CopyTicks'

fxsaber, 2016.10.19 07:59

// Позволяет, как в MT4, работать с таймсериями: Open[Pos], High[Pos], Low[Pos], Close[Pos], Time[Pos], Volume[Pos].
// А так же задает привычные MT4-функции: iOpen, iHigh, iLow, iClose, iTime, iVolume.
#define DEFINE_TIMESERIE(NAME,FUNC,T)                                                                         \
  class CLASS##NAME                                                                                           \
  {                                                                                                           \
  public:                                                                                                     \
    static T Get( const string Symb, const int TimeFrame, const int iShift )                                  \
    {                                                                                                         \
      T tValue[];                                                                                             \
                                                                                                              \
      return((Copy##FUNC((Symb == NULL) ? _Symbol : Symb, _Period, iShift, 1, tValue) > 0) ? tValue[0] : -1); \
    }                                                                                                         \
                                                                                                              \
    T operator []( const int iPos ) const                                                                     \
    {                                                                                                         \
      return(CLASS##NAME::Get(_Symbol, _Period, iPos));                                                       \
    }                                                                                                         \
  };                                                                                                          \
                                                                                                              \
  CLASS##NAME NAME;                                                                                           \
                                                                                                              \
  T i##NAME( const string Symb, const int TimeFrame, const int iShift )                                       \
  {                                                                                                           \
    return(CLASS##NAME::Get(Symb, TimeFrame, iShift));                                                        \
  }

DEFINE_TIMESERIE(Volume, TickVolume, long)
DEFINE_TIMESERIE(Time, Time, datetime)
DEFINE_TIMESERIE(Open, Open, double)
DEFINE_TIMESERIE(High, High, double)
DEFINE_TIMESERIE(Low, Low, double)
DEFINE_TIMESERIE(Close, Close, double)
This allows you to use iHigh and iLow as you are used to in MT5.
 
fxsaber:
fxsaber:
Insert this at the beginning of the code
This will allow you to use the familiar iHigh and iLow in MT5.
Thank you very much! This will make it very easy
 
Александр Богданов:
Hello! I do a little writing in MQL4, but I'm not familiar with MQL5. I need a little helper to calculate the difference between high and low for the day. The 4th version has good functions for this purpose iHigh and iLow, but they are absent here. I tried to use copyHigh and copyLow, but it keeps getting a lot of errors after subtracting the minimum value from the maximum one. Could you please tell me how to solve this problem, preferably with a code snippet. Thanks in advance!

If the task is only to display on the screen, then the best solution is an indicator. The indicator, in OnCalculate() has all necessary time series:

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {

By default, in MQL5 indicator, the rightmost bar has index rates_total-1. And your task comes down to elementary subtraction:

   double difference=high[rates_total-1]-low[rates_total-1];


Although, this simple approach will only display correctly if the indicator is running on the D1 timeframe. If it is run on other timeframes, then CopyHigh and CopyLow should be used - basically, nothing complicated.

Now I will write an example....

//+------------------------------------------------------------------+
//|                                               High minus Low.mq5 |
//|                              Copyright © 2016, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2016, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.00"
#property indicator_chart_window
#property indicator_plots 0
//--- input parameter
input ENUM_TIMEFRAMES period=PERIOD_D1;   // для какого периода считать High-Low
//---
double multiplier=0.0;
double High[],Low[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   multiplier=MathPow(10,Digits());
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//--- разницу цен переводим в пункты
   double difference=(iHigh(Symbol(),period,0)-iLow(Symbol(),period,0))*multiplier;
//--- вывод результата на экран
   Comment("High-Low=",DoubleToString(difference,0));
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Получим Low для заданного номера бара                            |
//+------------------------------------------------------------------+
double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)
  {
   double low=0;
   ArraySetAsSeries(Low,true);
   int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low);
   if(copied>0 && index<copied) low=Low[index];
   return(low);
  }
//+------------------------------------------------------------------+
//| Получим High для заданного номера бара                           |
//+------------------------------------------------------------------+
double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)
  {
   double high=0;
   ArraySetAsSeries(High,true);
   int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High);
   if(copied>0 && index<copied) high=High[index];
   return(high);
  }
//+------------------------------------------------------------------+


Now you can run the indicator on any timeframe of the current symbol and select for which timeframe to calculate the difference between High and Low.
Files:
 
Александр Богданов:
Hello! I do some writing in MQL4, but I'm not very good at MQL5. I need a little helper to calculate the difference between high and low for the day. The 4th version has good functions for this purpose iHigh and iLow, but they are absent here. I tried to use copyHigh and copyLow, but it keeps getting a lot of errors after subtracting the minimum value from the maximum one. Could you please tell me how to solve this problem, preferably with a code snippet. Thanks in advance!
If you want to get the daily Highs and Lows (Highs and Lows of the current day), you may use SymbolInfoDouble() with identifiers SYMBOL_BIDHIGH and SYMBOL_BIDLOW (or any other, as you may prefer).
 
Hello 2016.10.21_19:58 MSC. Checking the EA in the strategy tester. The EA works, opens and closes a trade. But strategy tester gives error: incorrect start position 0 for ArrayMinimum function; -1; array out of range in 'CLose.mqh' (86,59); Testing pass stopped due to a critical error in the EA. There is a screenshot of the Expert Advisor and the code of the file CLose.mqh to be activated. I do not see any error outside the array in this code. That is why I do not understand what the error is. Please, advise me if you can. That's all for now. 20:08 MSC. Critical error
//+------------------------------------------------------------------+
//|                                                        CLose.mqh |
//|                                              Nickityuk N., 2016. |
//|                             https://www.mql5.com/users/nicityuk/ |
//+------------------------------------------------------------------+
#property copyright "Nickityuk N., 2016."
#property link      "https://www.mql5.com/users/nicityuk/"
#property strict
#include <Expert\OPen.mqh>
//#include <ARrayMinimum.mqh>
double AOmax,AOmax2,AOmin,AOmin2,AOm0,AOn0,z5max0,z5min0,clm,cln,AO[];
int aom,aom2,aon,aon2;
datetime ttm,ttn,hm,hn;
//+------------------------------------------------------------------+
//| Calculate for close order                                        |
//+------------------------------------------------------------------+
void CLose()
  {if(buy==0 && sell==0) {return;}
   else if(OrderType()==OP_BUY) {CloseBuy();}
        else                     CloseSell();}
//+------------------------------------------------------------------+
void St()
  {St0=iStochastic(NULL,0,24,5,3,MODE_SMA,0,MODE_MAIN,0);
   Si0=iStochastic(NULL,0,24,5,3,MODE_SMA,0,MODE_SIGNAL,0);
   St1=iStochastic(NULL,0,24,5,3,MODE_SMA,0,MODE_MAIN,1);
   Si1=iStochastic(NULL,0,24,5,3,MODE_SMA,0,MODE_SIGNAL,1);}
void CloseBuy()
  {St(); if(St0-20>0 && Si0-20>0)
           {if(St1-Si1>0 && St0-Si0<0) {AOm0=iAO(NULL,0,0);
               if(AOm0-AOm1>=0) {AOm1=iAO(NULL,0,0); return;}
               else if(St0-80>0 && St0-100<=0 && Si0-80>0)
                      {if(Si0-100<=0 && St1-Si1>0 && St0-Si0<0)
                         {TwoExtremeAO_Buy(); OneExtremeBuy(); ExpirationBuy();}
                       else return;}            
                    else return;}
            else return;}        
         else return;}
void CloseSell()
  {St(); if(St0-80<0 && Si0-80<0)
           {if(St1-Si1<0 && St0-Si0>0) {AOn0=iAO(NULL,0,0);
               if(AOn0-AOn1<=0) {AOn1=iAO(NULL,0,0); return;}
               else if(St0-20<0 && St0>=0 && Si0-20<0)
                      {if(Si0>=0 && St1-Si1<0 && St0-Si0>0)
                         {TwoExtremeAO_Sell(); OneExtremeSell(); ExpirationSell();}
                       else return;}  
                    else return;}
            else return;}        
         else return;}
//+------------------------------------------------------------------+                      
void CalculateClose()
  {v0=iVolume(NULL,PERIOD_M1,0); //--- go trading only for first tiks of new bar
   v1=iVolume(NULL,PERIOD_M1,1);
   v2=iVolume(NULL,PERIOD_M1,2);
   v3=iVolume(NULL,PERIOD_M1,3);
   v4=iVolume(NULL,PERIOD_M1,4);
   if(v0+v1+v2+v3+v4-10/12>0) return;  
   for(index=0;index<24;index++)
     {AO[index]=iAO(NULL,PERIOD_M5,index);}
   ArrayResize(AO,24,4);
   ArraySetAsSeries(AO,true);}
   //index=0; AO[index]=iAO(NULL,PERIOD_M5,index);}
//+------------------------------------------------------------------+      
void TwoExtremeAO_Buy()
  {CalculateClose();
   if(ArrayMaximum(AO,23,0)==0) return;
   else aom=ArrayMaximum(AO,23,0); AOmax=AO[aom];
   if(ArrayMinimum(AO,aom,0)>0) {aon=ArrayMinimum(AO,aom,0);}
   else return;
   if(ArrayMaximum(AO,aon,0)==0) return;
   else aom2=ArrayMaximum(AO,aon,0); AOmax2=AO[aom2];
     if(AOmax2-AOmax>0) {return;}
     else if(AOmax2-AOmax<0) {if(OrderClose(OrderTicket(),OrderLots(),Bid,300,White)==false)
                                {Print("OrderClose error.",GetLastError());}
                              else //index=2;
                                   //while(iFractals(NULL,0,MODE_UPPER,index)==0) {index++;}
                                   //Sleep(3000); luf=iFractals(NULL,0,MODE_UPPER,index);
                                   //SL=NormalizeDouble(luf+(Ask-Bid)+(1*_Point),_Digits);
                                   TP=NormalizeDouble(Ask-tp*_Point,_Digits);
                                   tic=OrderSend(Symbol(),OP_SELL,LotsCalculated(),Bid,50,0,TP,"",MAGIC,0,Red);
                                   AOn1=iAO(NULL,0,index); return;}
          else return;}
//+------------------------------------------------------------------+          
void TwoExtremeAO_Sell()
  {CalculateClose();
   if(ArrayMinimum(AO,23,0)==0) return;
   else aon=ArrayMinimum(AO,23,0); Print(aon,""); AOmin=AO[aon];
   if(ArrayMaximum(AO,aon,0)>0) {aom=ArrayMaximum(AO,aon,0);}
   else return;
   if(ArrayMinimum(AO,aom,0)==0) return;
   else aon2=ArrayMinimum(AO,aom,0); AOmin2=AO[aon2]; //Print(aon2,"");
     if(AOmin2-AOmin>0) {return;}
     else if(AOmin2-AOmin<0) {if(OrderClose(OrderTicket(),OrderLots(),Bid,300,White)==false)
                                {Print("OrderClose error.",GetLastError());}
                              else //index=2;
                                   //while(iFractals(NULL,0,MODE_LOWER,index)==0) {index++;}
                                   //Sleep(3000); ldf=iFractals(NULL,0,MODE_LOWER,index);
                                   //SL=NormalizeDouble(ldf-(1*_Point),_Digits);
                                   TP=NormalizeDouble(Bid+tp*_Point,_Digits);
                                   tic=OrderSend(Symbol(),OP_BUY,LotsCalculated(),Ask,50,0,TP,"",MAGIC,0,Blue);
                                   AOm1=iAO(NULL,0,0); return;}
          else return;}
//+------------------------------------------------------------------+                      
void OneExtremeBuy()
  {index=0;
   while(iCustom(NULL,PERIOD_M5,"ZigZag",12,5,3,1,index)==0) {index++;}
   z5max0=iCustom(NULL,PERIOD_M5,"ZigZag",12,5,3,1,index); ttm=iTime(NULL,0,index); clm=iClose(NULL,PERIOD_M5,0); //Sleep(3000);
   if((clm-(z5max0-300*Point))<0) {if(OrderClose(OrderTicket(),OrderLots(),Bid,300,White)==false)
                                       {Print("OrderClose error.",GetLastError());}
                                   else return;}
   else return;}
void OneExtremeSell()
  {index=0;
   while(iCustom(NULL,PERIOD_M5,"ZigZag",12,5,3,2,index)==0) {index++;}
   z5min0=iCustom(NULL,PERIOD_M5,"ZigZag",12,5,3,2,index); ttn=iTime(NULL,0,index); cln=iClose(NULL,PERIOD_M5,0); //Sleep(3000);
   if((cln-(z5min0+300*Point))>0) {if(OrderClose(OrderTicket(),OrderLots(),Bid,300,White)==false)
                                       {Print("OrderClose error.",GetLastError());}
                                   else return;}
   else return;}
//+------------------------------------------------------------------+                                                                      
void ExpirationBuy()
  {hm=TimeHour(ttm); if((hm+3)-TimeCurrent()<0) {if(OrderClose(OrderTicket(),OrderLots(),Bid,300,White)==false)
                                                   {Print("OrderClose error.",GetLastError());}
                                                 else return;}
                     else return;}
void ExpirationSell()
  {hn=TimeHour(ttn); if((hn+3)-TimeCurrent()<0) {if(OrderClose(OrderTicket(),OrderLots(),Bid,300,White)==false)
                                                   {Print("OrderClose error.",GetLastError());}
                                                 else return;}
                     else return;}
//+------------------------------------------------------------------+          
 
Николай Никитюк:
Hello 2016.10.21_19:58 MSC. Checking the advisor in the strategy tester. The advisor works, opens and closes a trade. But strategy tester gives error: incorrect start position 0 for ArrayMinimum function; -1; array out of range in 'CLose.mqh' (86,59); Testing pass stopped due to a critical error in the EA. There is a screenshot of the Expert Advisor and the code of the file CLose.mqh to be activated. I do not see any error outside the array in this code. That is why I do not understand what the error is. Please, advise me if you can. That's all for now. 20:08 MSC.

Can this be converted to int (with aon=NormalizeDouble(aon,0)), because it looks like double and it's not quite clear what the result is?

:

if(ArrayMinimum(AO,aom,0)>0) {aon=ArrayMinimum(AO,aom,0);}
 
Karputov Vladimir:

Simply enter an input parameter into your EA and, depending on the value assigned to it when you start, you will either buy only or sell only:

input bool Long=true;            // allow only "Long"
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
...
void OnTick()
  {
   if(!Long)
      trade.Sell(0.01);
   if(Long)
      trade.Buy(0.01);
  }
And for manual trading, what do you suggest?