Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 672

 
inter78:

Actually, I did, but I don't like the long response time

It's not a long time, it's a tick... but in general, you need to read the help. you can't learn MQL by "gut feeling". MQL is based on C++, but it is tied to MT platform, so you may not learn it without reading the help.

You've got file handling and work with global variables and graphics in your code ... There's a lot of unnecessary operations on every tick

If you want a fast response, use OnChartEvent(), it's not generated in the tester, but first start studying the MQL4 help.

 
Igor Makanu:

The operation is not long, it is tick by tick... but in general, start reading the help, you cannot learn MQL by "gut feeling", MQL is based on C++, but it is tied to the MT platform, you cannot do it without reading the help.

You've got file handling and work with global variables and graphics in your code ... There's a lot of unnecessary operations on every tick

If you want fast execution, use OnChartEvent(), it's not generated in the tester, but first start studying the MQL4 help.

I will probably have to ask technicians to bring it to my senses. I will not be able to. This indicator is very convenient for working with an unlimited number of open charts. The buttons show the current profit of the symbol and the number of buy and sell orders.
 

Hi all.

Found a useful Ind-Fractals indicator in the code library. However, it draws fractals on every bar, instead of calculating them properly. I want to use this indicator, but it is "broken" (( Help me to find an error, I have tried to contact the author, but he does not respond to messages. For convenience, duplicated code here.

#property copyright "Copyright © 2005, MetaQuotes Software Corp.

#property link "http://www.metaquotes.net"

//----

#property indicator_chart_window

#property indicator_buffers 8

#property indicator_color1 Red

#property indicator_color2 Red

#property indicator_color3 Blue

#property indicator_color4 Blue

#property indicator_color5 Lime

#property indicator_color6 Lime

#property indicator_color7 Sienna

#property indicator_color8 Sienna

//---- input parameters

extern bool Comm=true;

//---- buffers

double ExtMapBuffer1[];

double ExtMapBuffer2[];

double ExtMapBuffer3[];

double ExtMapBuffer4[];

double ExtMapBuffer5[];

double ExtMapBuffer6[];

double ExtMapBuffer7[];

double ExtMapBuffer8[];

//+------------------------------------------------------------------+

//| Custom indicator initialisation function |

//+------------------------------------------------------------------+

int init()

{

//---- indicators

SetIndexStyle(0,DRAW_ARROW);//the indicator line style

SetIndexArrow(0,217); //prescribes arrow type

SetIndexBuffer(0,ExtMapBuffer1);//bindsindicator buffer with one-dimensional dynamic array of double type. There are 2 versions of the function.

SetIndexEmptyValue(0,0.0);//Sets the empty value for the indicator line.

SetIndexStyle(1,DRAW_ARROW);

SetIndexArrow(1,218);

SetIndexBuffer(1,ExtMapBuffer2);

SetIndexEmptyValue(1,0.0);

SetIndexStyle(2,DRAW_ARROW);

SetIndexArrow(2,217);

SetIndexBuffer(2,ExtMapBuffer3);

SetIndexEmptyValue(2,0.0);

SetIndexStyle(3,DRAW_ARROW);

SetIndexArrow(3,218);

SetIndexBuffer(3,ExtMapBuffer4);

SetIndexEmptyValue(3,0.0);

SetIndexStyle(4,DRAW_ARROW);

SetIndexArrow(4,217);

SetIndexBuffer(4,ExtMapBuffer5);

SetIndexEmptyValue(4,0.0);

SetIndexStyle(5,DRAW_ARROW);

SetIndexArrow(5,218);

SetIndexBuffer(5,ExtMapBuffer6);

SetIndexEmptyValue(5,0.0);

SetIndexStyle(6,DRAW_ARROW);

SetIndexArrow(6,217);

SetIndexBuffer(6,ExtMapBuffer7);

SetIndexEmptyValue(6,0.0);

SetIndexStyle(7,DRAW_ARROW);

SetIndexArrow(7,218);

SetIndexBuffer(7,ExtMapBuffer8);

SetIndexEmptyValue(7,0.0);

return(0); }

//+------------------------------------------------------------------+

//| Custor indicator deinitialization function |

//+------------------------------------------------------------------+

int deinit() {return(0); }

//------------------------------------------------------------------

bool Fractal(string F,int Per,int shift) {

if(Period()>Per) return(-1);

Per=Per/Period()*2+MathCeil(Per/Period()/2);

if(shift<Per)return(-1);

if(shift>Bars-Per)return(-1);

for(int i=1;i<=Per;i++) {

if(shift+i>=Bars || shift-i<0) return(-1);

if(F=="U") {

if(High[shift+i]>High[shift])return(-1);

if(High[shift-i]>=High[shift])return(-1); }

if(F=="L") {

if(Low[shift+i]<Low[shift])return(-1);

if(Low[shift-i]<=Low[shift])return(-1); } }

return(1); }

//------------------------------------------------------------------

int start()

{

int D1=1440,H4=240,H1=60,M15=15,B;

double P;

int counted_bars=IndicatorCounted();// number of bars unchanged after the last indicator call

B=Bars-counted_bars;

if(counted_bars==0) B--;

if(Period()==D1)P=150*Point;// period returns the current chart period

if(Period()==H4)P=70*Point;

if(Period()==H1)P=40*Point;

if(Period()==30)P=30*Point;

if(Period()==M15)P=20*Point;

if(Period()==5)P=10*Point;

if(Period()==1)P=5*Point;

for(int shift=B;shift>0;shift--)

{

if(Fractal("U",M15,shift)==1) ExtMapBuffer1[shift]=High[shift]+P;

else ExtMapBuffer1[shift]=0;

if(Fractal("L",M15,shift)==1) ExtMapBuffer2[shift]=Low[shift]-P;

else ExtMapBuffer2[shift]=0;

if(Fractal("U",H1,shift)==1) ExtMapBuffer3[shift]=High[shift]+P;

else ExtMapBuffer3[shift]=0;

if(Fractal("L",H1,shift)==1) ExtMapBuffer4[shift]=Low[shift]-P;

else ExtMapBuffer4[shift]=0;

if(Fractal("U",H4,shift)==1) ExtMapBuffer5[shift]=High[shift]+P;

else ExtMapBuffer5[shift]=0;

if(Fractal("L",H4,shift)==1) ExtMapBuffer6[shift]=Low[shift]-P;

else ExtMapBuffer6[shift]=0;

if(Fractal("U",D1,shift)==1) ExtMapBuffer7[shift]=High[shift]+P;

else ExtMapBuffer7[shift]=0;

if(Fractal("L",D1,shift)==1) ExtMapBuffer8[shift]=Low[shift]-P;

else ExtMapBuffer8[shift]=0;

}

if(Comm) Comment("D1 - brown\n H4 - green\n H1 - blue\nM15 - red ");


return(0);

}

MetaQuotes Software Corp.
MetaQuotes Software Corp.
  • www.metaquotes.net
Миллионы трейдеров и сотни брокеров не могут ошибаться — они выбрали MetaTrader 5 для торговли на Форексе и финансовых рынках! Узнать больше
 

I've been scolded here for this kind of code, it's the first time I've had it :-)

The code should be inserted into a form that opens with Alt+S.

 
psyman:

I've been scolded here for this kind of code, it's the first time I've had it :-)

You have to paste the code into a form that opens on Alt+S.

Do you get scolded? Not in any way. Write the code however you want. But... if you want an answer to your question, try to respect those you are asking for help. It's as simple as that.

 

Forum on trading, automated trading systems & strategy testing

Any questions for newbies on MQL4, help and discussion on algorithms and codes

Artyom Trishkin, 2018.10.18 08:07

Let's put it this way: create an indicator template in the editor, add the right number of input variables and drawing buffers when you create it.

Next, let's analyze what to do from the specific task.

That's what I did last time, just changed the variable and array name.

When using iMA it works only on weeks and daires, where the candle contains more than 100 points, it does not do anything on lower timeframes. The reason seems to be rounding.




If iMAOnArray is used, i-ras window is empty at all TFs. There are no errors in the log.




//+------------------------------------------------------------------+
//|                                                        _null.mq4 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
//--- plot OC
#property indicator_label1  "O-C"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrSteelBlue
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- indicator buffers
double         ip1Buf[];

input int ip1=100;
double tmp1[];


//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
  
IndicatorBuffers(2);
string s_name1;

s_name1="O-C (" + IntegerToString(ip1) + ")";

IndicatorShortName(s_name1);
SetIndexLabel(0, s_name1);
SetIndexBuffer(1, tmp1);


//--- indicator buffers mapping
   SetIndexBuffer(0,ip1Buf);
   
//---
   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[])
  {


int i;

      Print("rates_total = ",rates_total);
      for(i=1; i<rates_total-1; i++)
      {
      //Print("i = ",i);
      tmp1[i]=MathMax(open[i],close[i])-MathMin(open[i],close[i]);      
     // tmp1[i]=close[i];      
      //ip1Buf[i]=iMA(NULL,0,1,0,0,tmp1[i],0);
      ip1Buf[i]=iMAOnArray(tmp1,1,1,0,0,0);
      
      }
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+


 
psyman:

If iMAOnArray is used, i-ra window is empty on all TFs. There are no errors in the log.

You are using iMAOnArray() with period 1, i.e. iMAOnArray() value will essentially be the value of array tmp1

If you want to make out what you're calculating, make the loop shorterfor(i=1; i<10; i++)

and unprint all data you want to calculate, although it may be easier not to calculate some complex formula, but use iMAOnArray() to build iMA and iMAOnArray() - both iMA and iMAOnArray() are the same calculations.... alas, if you can get an answer to a technical question on this forum, you alone should learn to calculate and deal with the information.

 
psyman:

Last time I did this, only I changed the name of the variable and the array.

When using iMA i-r worked only on weeks and days, where there is more than 100 pips in a candle, it does not draw anything on lower TFs. The reason seems to be rounding.




If iMAOnArray is used, i-ras window is empty at all TFs. There are no errors in the log.





The first cycle calculates the values of the first buffer;

The second cycle calculates MA by values calculated in the first cycle.

Consider what iMAOnArray() means. Write MA on Array. How do you translate it? Everyone has a Google-translator at his fingertips. Put-translate-receive: MA on Array.

It means that it is a moving average based on a preliminarily calculated and filled array.

Correspondingly: the first cycle - preparation of the necessary array, and the second cycle - construction of a moving average based on the array prepared in the first cycle.

And what do you do? You enter a value into the first array (the other values have not yet been prepared) and try to build the MA on this value.

I gave you a template:

Forum on trading, automated trading systems and strategy testing

Any MQL4 beginners questions, help and discussion on algorithms and codes

Artyom Trishkin, 2018.10.18 09:39

Indicator:

//+------------------------------------------------------------------+
//|                                                       TestMA.mq5 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                             https://mql5.com/ru/users/artmedia70 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://mql5.com/ru/users/artmedia70"
#property version   "1.00"
#property indicator_chart_window
#ifdef __MQL4__
#property strict
#property indicator_buffers 2
#else 
#property indicator_buffers 3
#property indicator_plots   2
#endif 
//--- plot MAstd
#property indicator_label1  "Calculation MA"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrBlue
#property indicator_style1  STYLE_SOLID
#property indicator_width1  4
//--- plot MAcalc
#property indicator_label2  "Standart MA"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrDarkOrange
#property indicator_style2  STYLE_DOT
#property indicator_width2  2
//--- input parameters
input int      InpPeriod                     =  10;            // Period
input ENUM_MA_METHOD       InpMethod         =  MODE_EMA;      // Method
input ENUM_APPLIED_PRICE   InpAppliedPrice   =  PRICE_CLOSE;   // Applied price  
//--- indicator buffers
double         BufferMAcalc[];
double         BufferMAstd[];
double         BufferPrice[];
//---
int            digits;
int            period_ma;
int            handle_ma;
CAvg           avg();
//--- includes

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
#ifdef __MQL4__
   IndicatorBuffers(3);
#endif 
    period_ma=(InpPeriod<1? 1 : InpPeriod);
   digits=Digits()+1;
//--- indicator buffers mapping
   SetIndexBuffer(0,BufferMAcalc,INDICATOR_DATA);
   SetIndexBuffer(1,BufferMAstd,INDICATOR_DATA);
   SetIndexBuffer(2,BufferPrice,INDICATOR_CALCULATIONS);
//---
   ArraySetAsSeries(BufferMAcalc,true);
   ArraySetAsSeries(BufferMAstd,true);
   ArraySetAsSeries(BufferPrice,true);
//---
#ifdef __MQL5__
   ResetLastError();
   handle_ma=iMA(NULL,PERIOD_CURRENT,period_ma,0,InpMethod,InpAppliedPrice);
   if(handle_ma==INVALID_HANDLE)
     {
      Print("Error creation iMA(",(string)period_ma,"): ",GetLastError());
      return INIT_FAILED;
     }
#endif 
//---
   Comment("\nMA type: ",avg.MethodToString(InpMethod),", price: ",avg.PriceToString(InpAppliedPrice),", period: ",(string)period_ma);
//---
   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[])
  {
//--- Установка массивов буферов как таймсерий
#ifdef __MQL5__
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
#endif 
//--- Проверка количества доступных баров
   if(rates_total<fmax(period_ma,4)) return 0;
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated;
   if(limit>1)
     {
      limit=rates_total-1;
      ArrayInitialize(BufferMAcalc,EMPTY_VALUE);
      ArrayInitialize(BufferMAstd,EMPTY_VALUE);
      ArrayInitialize(BufferPrice,0);
     }
//--- Подготовка данных
#ifdef __MQL5__
   int count=(limit>1 ? rates_total : 1),copied=0;
   copied=CopyBuffer(handle_ma,0,0,count,BufferMAstd);
   if(copied!=count) return 0;
#endif 
//--- Расчёт индикатора
   for(int i=limit; i>=0 && !IsStopped(); i--)
     {
      #ifdef __MQL4__ BufferMAstd[i]=iMA(NULL,PERIOD_CURRENT,period_ma,0,InpMethod,InpAppliedPrice,i); #endif 
       BufferPrice[i]=avg.AppliedPrice(InpAppliedPrice,NULL,PERIOD_CURRENT,i);
      BufferMAcalc[i]=avg.GetMA(rates_total,InpMethod,period_ma,i,BufferPrice);
     }

//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

You can throw out everything related to fives and get a template for fours. Although this template is multiplatform - you can use it for both terminals - just set your buffers and their number. In this template there are two drawing and one calculation, which can be seen here:

//--- indicator buffers mapping
   SetIndexBuffer(0,BufferMAcalc,INDICATOR_DATA);
   SetIndexBuffer(1,BufferMAstd,INDICATOR_DATA);
   SetIndexBuffer(2,BufferPrice,INDICATOR_CALCULATIONS);
//---
 

=also, you use iMAOnArray() with period 1, i.e. the value of iMAOnArray() will essentially be the value of array tmp1


I've tried different values to use, 1 remains as the last variant of these experiments.

For some reason, the ip1Buf[4] = 2147483647.0 writes the same number in the i-r buffer on all TFs, for example, while the array values are all different tmp1[4] = 0.1300000000000097, etc.

But even then a straight line should be drawn, and there is absolutely nothing on the i-r chart, the scale is marked from 0 to 0.



 
psyman:

=also, you use iMAOnArray() with period 1, i.e. the value of iMAOnArray() will essentially be the value of array tmp1


I've tried different values to use, 1 remains as the last variant of these experiments.

For some reason, the same number is written to the i-ras buffer on all TFs, for example ip1Buf[4] = 2147483647.0, even though the array values are all different tmp1[4] = 0.1300000000000097, etc.

But even in this case a straight line should be drawn, and there is absolutely nothing on the i-r chart, the scale is marked from 0 to 0.



2147483647.0 Well start using the search engine!https://www.mql5.com/ru/forum/224831

Once again, I just wrote Artem, you need to read it yourself, start with a simple one... Draw a close price on a chart with an indicator, then try to make it more complicated, do the same in one cycle and in the second cycle do МА calculation based on the already calculated buffer where close lies

2147483647 в буфере
2147483647 в буфере
  • 2018.01.15
  • www.mql5.com
День Добрый! Подскажите, пожалуйста, что это за хрень. Не первый раз сталкиваюсь...