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

 
Alexey Viktorov:

It is the same in mql5. It is even slightly extended. Isn't it what we need?

SYMBOL_TRADE_TICK_VALUE

SYMBOL_TRADE_TICK_VALUE_PROFITvalue

double

SYMBOL_TRADE_TICK_VALUE_PROFIT

Calculated tick value for profitable position

double

SYMBOL_TRADE_TICK_VALUE_LOSS

Calculated value of a tick for a losing position

double

SYMBOL_TRADE_TICK_SIZE

Minimum price change

double

Damn, I'm so dumb, I put TICK_SIZE instead of TICK_VALUE... I should go to bed.
 
Guys, what's wrong here, help me out!?
 
Alexey Viktorov:

The first thing that caught my eye was the sequence of buffers.

The build buffers must ALWAYS run in sequence. I.e. if the data buffers are number 2 and 3, then the colour buffer MUST be number 4

If this is not the only error, we will look further.

OK, did find such a feature in the instructions, here:

MQL5 Reference Guide / Custom Indicators / SetIndexBuffer
".....

boolSetIndexBuffer(
intindex,// index of the buffer
doublebuffer[],// array
ENUM_INDEXBUFFER_TYPEdata_type//what will be stored
);

Parameters

index

[in] Indicator buffer number. The numbering starts from 0. The number must be smaller than the value declared in #property indicator_buffers.

buffer[]

[in] Array declared in the custom indicator program.

data_type

[in] Type of data stored in the indicator array. Defaults to INDICATOR_DATA (values of the calculated indicator). Can also take INDICATOR_COLOR_INDEX value, then this buffer is intended for storing indices of colours for previous indicator buffer. Up to 64 colours can be specified in the line #property indicator_colorN. The value INDICATOR_CALCULATIONS means that this buffer participates in the intermediate calculations of the indicator, and it is not intended for drawing.

 

I tried to redo it and got even more bullshit. The histogram was gone altogether and the line indicator became strange to say the least. The signal one was cut off above 50 and the main one was lower. There are no such cutoffs in the code.

 
Artyom Trishkin:

I gave you a link to study not the histogram, but how to work with the colour buffer. Abstract away from the histogram, and focus on how you need to work with colour.

I studied it, but nothing new, apparently it is (new to me) of course, obvious to all the initiated, self-explanatory. I could not find anything new, except the above-described feature of mutual arrangement of buffers during indexing. This sequence respected, got an even cheesier picture.

Pictures below, file attached

//+------------------------------------------------------------------+
//|                                       Stoch_HISTOGRAM_MQL5_4.mq5 |
//|                   Copyright 2009-2017, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009-2017, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"

//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 8
#property indicator_plots   3

#property indicator_type1   DRAW_COLOR_HISTOGRAM2
#property indicator_color1  clrGreen,clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1 

#property indicator_type1   DRAW_LINE       // основная
#property indicator_color1  clrLightSeaGreen
#property indicator_style1  STYLE_SOLID
#property indicator_width2  3 

#property indicator_type2   DRAW_LINE       // сигнальная
#property indicator_color2  clrYellow
#property indicator_style2  STYLE_SOLID
#property indicator_width3  2 

//--- input parameters
input int InpKPeriod=5;  // K period
input int InpDPeriod=3;  // D period
input int InpSlowing=3;  // Slowing

//--- indicator buffers
double    ColorHistogram_2Buffer1[]; 
double    ColorHistogram_2Buffer2[]; 
double    ColorHistogram_2Colors[];
double    ExtMainBuffer[];
double    ExtSignalBuffer[];
double    ExtHighesBuffer[];
double    ExtLowesBuffer[];
color     colors[]={clrRed,clrGreen};
int       cl;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
//--- indicator buffers mapping

   SetIndexBuffer(0,ColorHistogram_2Buffer1,INDICATOR_DATA);
   SetIndexBuffer(1,ColorHistogram_2Buffer2,INDICATOR_DATA);
   SetIndexBuffer(2,ColorHistogram_2Colors,INDICATOR_COLOR_INDEX);
   SetIndexBuffer(3,ExtMainBuffer,INDICATOR_DATA);
   SetIndexBuffer(4,ExtSignalBuffer,INDICATOR_DATA);
   SetIndexBuffer(5,ExtHighesBuffer,INDICATOR_CALCULATIONS);
   SetIndexBuffer(6,ExtLowesBuffer,INDICATOR_CALCULATIONS);  
   
   //ArraySetAsSeries(ExtMainBuffer,true);
   //ArraySetAsSeries(ExtSignalBuffer,true);
   //ArraySetAsSeries(ExtHighesBuffer,true);
   //ArraySetAsSeries(ExtLowesBuffer,true);
   //ArraySetAsSeries(ColorHistogram_2Buffer1,true);
   //ArraySetAsSeries(ColorHistogram_2Buffer2,true);
   //ArraySetAsSeries(ColorHistogram_2Colors,true);
   
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//--- set accuracy
   IndicatorSetInteger(INDICATOR_DIGITS,2);
//--- set levels
   IndicatorSetInteger(INDICATOR_LEVELS,3);
   IndicatorSetDouble(INDICATOR_LEVELVALUE,0,20);
   IndicatorSetDouble(INDICATOR_LEVELVALUE,1,50);
   IndicatorSetDouble(INDICATOR_LEVELVALUE,2,80);
//--- set maximum and minimum for subwindow 
   IndicatorSetDouble(INDICATOR_MINIMUM,0);
   IndicatorSetDouble(INDICATOR_MAXIMUM,100);
//--- name for DataWindow and indicator subwindow label
   IndicatorSetString(INDICATOR_SHORTNAME,"Stoch_HISTOGRAM("+(string)InpKPeriod+","+(string)InpDPeriod+","+(string)InpSlowing+")");
   PlotIndexSetString(3,PLOT_LABEL,"Main");
   PlotIndexSetString(4,PLOT_LABEL,"Signal");
   //PlotIndexSetString(2,PLOT_LABEL,"UP");
   //PlotIndexSetString(3,PLOT_LABEL,"LOW");
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(3,PLOT_DRAW_BEGIN,InpKPeriod+InpSlowing-2);
   PlotIndexSetInteger(4,PLOT_DRAW_BEGIN,InpKPeriod+InpDPeriod);
   PlotIndexSetInteger(5,PLOT_DRAW_BEGIN,InpKPeriod+InpSlowing-2);
   PlotIndexSetInteger(6,PLOT_DRAW_BEGIN,InpKPeriod+InpSlowing-2);
//--- initialization done
  }
//+------------------------------------------------------------------+
//| Stochastic Oscillator                                            |
//+------------------------------------------------------------------+
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,k,start;
//--- check for bars count
   if(rates_total<=InpKPeriod+InpDPeriod+InpSlowing)
      return(0);
//---
   start=InpKPeriod-1;
   if(start+1<prev_calculated) start=prev_calculated-2;
   else
     {
      for(i=0;i<start;i++)
        {
         ExtLowesBuffer[i]=0.0;
         ExtHighesBuffer[i]=0.0;
        }
     }
//--- calculate HighesBuffer[] and ExtHighesBuffer[]
   for(i=start;i<rates_total && !IsStopped();i++)
     {
      double dmin=1000000.0;
      double dmax=-1000000.0;
      for(k=i-InpKPeriod+1;k<=i;k++)
        {
         if(dmin>low[k])  dmin=low[k];
         if(dmax<high[k]) dmax=high[k];
        }
      ExtLowesBuffer[i]=dmin;
      ExtHighesBuffer[i]=dmax;
     }
//--- %K
   start=InpKPeriod-1+InpSlowing-1;
   if(start+1<prev_calculated) start=prev_calculated-2;
   else
     {
      for(i=0;i<start;i++) ExtMainBuffer[i]=0.0;
     }
//--- main cycle
   for(i=start;i<rates_total && !IsStopped();i++)
     {
      double sumlow=0.0;
      double sumhigh=0.0;
      for(k=(i-InpSlowing+1);k<=i;k++)
        {
         sumlow +=(close[k]-ExtLowesBuffer[k]);
         sumhigh+=(ExtHighesBuffer[k]-ExtLowesBuffer[k]);
        }
      if(sumhigh==0.0) ExtMainBuffer[i]=100.0;
         else ExtMainBuffer[i]=sumlow/sumhigh*100;
      if(ExtMainBuffer[i]>50){
         cl=1;
         ColorHistogram_2Buffer1[i]=50; 
         ColorHistogram_2Buffer2[i]=ExtMainBuffer[i]; 
         ColorHistogram_2Colors[i]=colors[cl];
     Print("ExtMainBuffer[i]=",ExtMainBuffer[i],
           " cl=",cl,
           " ColorHistogram_2Buffer1[i]=",ColorHistogram_2Buffer1[i],
           " ColorHistogram_2Buffer2[i]=",ColorHistogram_2Buffer2[i],
           " ColorHistogram_2Colors[i]=",ColorHistogram_2Colors[i]);
         } 
      if(ExtMainBuffer[i]<50){
         cl=0;
         ColorHistogram_2Buffer1[i]=ExtMainBuffer[i]; 
         ColorHistogram_2Buffer2[i]=50; 
         ColorHistogram_2Colors[i]=colors[cl];
     Print("ExtMainBuffer[i]=",ExtMainBuffer[i],
           " cl=",cl,
           " ColorHistogram_2Buffer1[i]=",ColorHistogram_2Buffer1[i],
           " ColorHistogram_2Buffer2[i]=",ColorHistogram_2Buffer2[i],
           " ColorHistogram_2Colors[i]=",ColorHistogram_2Colors[i]);
         } 
     }
//--- signal
   start=InpDPeriod-1;
   if(start+1<prev_calculated) start=prev_calculated-2;
   else
     {
      for(i=0;i<start;i++) ExtSignalBuffer[i]=0.0;
     }
   for(i=start;i<rates_total && !IsStopped();i++)
     {
      double sum=0.0;
      for(k=0;k<InpDPeriod;k++) sum+=ExtMainBuffer[i-k];
      ExtSignalBuffer[i]=sum/InpDPeriod;
     }
//--- OnCalculate done. Return new prev_calculated.
   return(rates_total);
  }
//+------------------------------------------------------------------+ 
 

Hello.

Can you please tell me where I can find the algorithm for "reliable" order opening (so far I am only interested in market orders), because I am stumped.

The problem is that in my account (Alpari) the StopLevel and FreezeLevel levels are zero and if I use only thesehttps://book.mql4.com/ru/appendix/limits limitations it means that a StopLoss on buying can be set at Bid level and on selling at Ask level, but this is not true. In this case OrderSend returns a "No price" error (ERR_OFF_QUOTES, code 136).

At the same time, trades without stops or with stops of 50 or more points open without any problems.

I found out by experience that the minimum SlopLoss is 19 pips. I don't know how to determine this margin programmatically.

 
These levels should be set from the closing price of the order, not from the opening price. And the closing price when setting these levels must not be equal to the value set
 
klok79:

Hello.

Can you please tell me where I can find the algorithm for "reliable" order opening (so far I am only interested in market orders), because I am stumped.

The problem is that in my account (Alpari) the StopLevel and FreezeLevel levels are zero and if I use only thesehttps://book.mql4.com/ru/appendix/limits limitations it means that a StopLoss on buying can be set at Bid level and on selling at Ask level, but this is not true. In this case OrderSend returns a "No price" error (ERR_OFF_QUOTES, code 136).

At the same time, trades without stops or with stops of 50 or more points open without any problems.

I found out by experience that the minimum SlopLoss is 19 pips. I do not know how to determine this margin programmatically.

Try minStopLoss = Current price +/- (MaxValue(2*Spread, StopLoss));

 
Why aren't objects destroyed when debugging is stopped? I understand that OnDeinit() is not called at all. After debug stop I have to kill the terminal every time.
 

Good afternoon the code below problem is often updated array adx_sig[9] . I wanted to get a dependency of data update on time. But something went wrong.

//+------------------------------------------------------------------+
//|                                                          123.mq5 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
input int                  ADX_adx_period          = 14;                                                 // adx period ADX 
input int                  ADX_lower_level         = 20;                                                 // Lower level ADX 
int h_adx[9];
double adx1_buffer[3];
double adx2_buffer[3];
double adx3_buffer[3];
ENUM_TIMEFRAMES handle_period[9]={PERIOD_CURRENT,PERIOD_M1,PERIOD_M5,PERIOD_M15,PERIOD_M30,PERIOD_H1,PERIOD_H4,PERIOD_D1,PERIOD_W1};
int adx_sig[9];
int OnInit()
  {
//---
   for(int i=0; i<ArraySize(handle_period); i++)
     {
      //--- Установим хэндлы для индикаторов
      h_adx[i]=iADX(_Symbol,handle_period[i],ADX_adx_period);
        if(h_adx[i]<0) 
        {
         Alert("Ошибка при создании индикаторов - : ",GetLastError(),"!!");
        }
     }   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
    for(int i=0; i<ArraySize(handle_period); i++)
     {
      //--- Удаляем хэндлы для индикаторов
      IndicatorRelease(h_adx[i]);
     }
     //---
       
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   for(int i_sig=0; i_sig<ArraySize(handle_period); i_sig++)
     {
      if(CopyBuffer(h_adx[i_sig],0,0,3,adx1_buffer)<3)Print("CopyBuffer adx1_buffer ",GetLastError());
      if(CopyBuffer(h_adx[i_sig],1,0,3,adx2_buffer)<3)Print("CopyBuffer adx2_buffer ",GetLastError());
      if(CopyBuffer(h_adx[i_sig],2,0,3,adx3_buffer)<3)Print("CopyBuffer adx3_buffer ",GetLastError());
      if(adx3_buffer[1]<adx2_buffer[1] && adx3_buffer[1]>=ADX_lower_level && adx3_buffer[1]>adx3_buffer[2])adx_sig[i_sig]=1;
      else if(adx3_buffer[1]>adx2_buffer[1] && adx3_buffer[1]>=ADX_lower_level && adx3_buffer[1]<adx3_buffer[2])adx_sig[i_sig]=-1;
      else adx_sig[i_sig]=0;
      }
      PrintFormat("ADX sig0=%i sig1=%i sig2=%i sig3=%i sig4=%i sig5=%i sig6=%i sig7=%i sig8=%i",adx_sig[0],adx_sig[1],adx_sig[2],adx_sig[3],adx_sig[4],adx_sig[5],adx_sig[6],adx_sig[7],adx_sig[8]); 
  }
Reason: