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

 
Hello!
Possibly from https://ru.investing.com/tools/correlation-calculator
Is it possible to transfer the information to the timetable?
How can this be done?
Thank you in advance.
 
Irina Dymura:
Hello!
Possibly from https://ru.investing.com/tools/correlation-calculator
Is it possible to transfer the information to the timetable?
How can this be done?
Thank you in advance.
TryWebRequest().
 
Ihor Herasko:

Yes. There's no reason to translate time into string, since time is a number of seconds. This number is much easier and faster to work with than strings.

You've corrected one thing and ruined another.)

In the second part instead of:

return:

You had that line correct in your previous attempt.


Thanks for the replies! I've tried both options.

I don't see what the catch is - it still goes right in when closing on a stop:

lil_lil:

Say your condition out loud and you'll see what's going on)

if ( TimeSeconds(TimeCurrent()) - TimeSeconds(OrderCloseTime()) > TimeSeconds(30*60) )
if ( TimeCurrent() -OrderCloseTime() > 30*60 )

In fact, there != condition everywhere, i.e. opposite > should be there, if I understood correctly what you mean. But all variants ran - still works.

 

Help to understand the logic, find the error

Commented out the code in detail.

I need it to draw fractals with a period, with a "zigzag" type, so that the lower upper upper lower fractals go in sequence and so on.

But as a result, the repeated fractals appear on the chart anyway

The basis is taken from the standard fractal indicator. Screenshot below with repeated fractal on period 5

//+------------------------------------------------------------------+
//|                                                     Fractals.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_chart_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_type1   DRAW_ARROW
#property indicator_type2   DRAW_ARROW
#property indicator_color1  Gray
#property indicator_color2  Gray
#property indicator_label1  "Fractal Up"
#property indicator_label2  "Fractal Down"
bool high_f, low_f, lastIsUpper = true, lastIsLower = true;
int lastLowerIndex, lastUpperIndex;
//---- input data
input int period = 5;
int per = period;
//---- indicator buffers
double ExtUpperBuffer[];
double ExtLowerBuffer[];
//--- 10 pixels upper from high price
int    ExtArrowShift=-10;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit()
  {
  if(per % 2 == 0) per++; //период фракталов только нечетный
//---- indicator buffers mapping
   SetIndexBuffer(0,ExtUpperBuffer,INDICATOR_DATA);
   SetIndexBuffer(1,ExtLowerBuffer,INDICATOR_DATA);
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
//---- sets first bar from what index will be drawn
   PlotIndexSetInteger(0,PLOT_ARROW,217);
   PlotIndexSetInteger(1,PLOT_ARROW,218);
//---- arrow shifts when drawing
   PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,ExtArrowShift);
   PlotIndexSetInteger(1,PLOT_ARROW_SHIFT,-ExtArrowShift);
//---- sets drawing line empty value--
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE);
   PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,EMPTY_VALUE);
//---- initialization done
  }

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,limit;
//---
   if(rates_total < per)
      return(0);
//---
   if(prev_calculated < per + (per - 1) / 2)
     {
      limit = (per - 1) / 2;
      //--- clean up arrays
      ArrayInitialize(ExtUpperBuffer,EMPTY_VALUE);
      ArrayInitialize(ExtLowerBuffer,EMPTY_VALUE);
     }
   else limit = rates_total - per;
   for(i = limit; i < rates_total - (per + 1) / 2 && !IsStopped(); i++)
     {
      high_f = true; low_f = true;//с самого начала считаем что есть фрактал в i свече
      for(int g = 1; g < (per+1)/2; g++){//проверка на наличие фрактала (одновременной справа и слева от свечи с возможным фракталом)
         //---- Upper Fractal
         if(high[i-g] >= high[i] || high[i+g] > high[i]){//если одно из условий выполнено (high какой либо свечи справа или слева выше чем исследуемый), то фрактала сверху нет
            ExtUpperBuffer[i] = EMPTY_VALUE;
            high_f = false;            
         }        
         //---- Lower Fractal
         if(low[i-g] <= low[i] || low[i+g] < low[i]){ //если одно из условий выполнено, то фрактала снизу нет        
            ExtLowerBuffer[i] = EMPTY_VALUE;
            low_f = false;   
         }  
      }  
       //устанавливаем верхний
      if(high_f){//если фрактал все таки есть (из цикла-проверки выше)
         if(lastIsLower){//еси последний фрактал был нижний
            ExtUpperBuffer[i] = high[i];//устанавливаем сверху
            lastUpperIndex = i;//записываем индекс в буффере установленного
            lastIsLower = false;//говорим что последний - не нижний
            lastIsUpper = true;//а верхний
         }else{
            if(lastIsUpper){//если последний верхний (а мы пытаемся установить верхний)
               if(high[i] > ExtUpperBuffer[lastUpperIndex]){//если устанавливаем выше предыдущего
                  ExtUpperBuffer[lastUpperIndex] = EMPTY_VALUE;//удаляем предыдущий
                  ExtUpperBuffer[i] = high[i];//устанавливаем новый
                  lastUpperIndex = i;//записываем индекс нового
               }
            }
         }
      }
      //аналогично для фрактала снизу
      if(low_f){
         if(lastIsUpper){
            ExtLowerBuffer[i] = low[i];
            lastLowerIndex = i;
            lastIsLower = true;
            lastIsUpper = false;
         }else{
            if(lastIsLower){
               if(low[i] < ExtLowerBuffer[lastLowerIndex]){
                  ExtLowerBuffer[lastLowerIndex] = EMPTY_VALUE;
                  ExtLowerBuffer[i] = low[i];
                  lastLowerIndex = i;
               }
            }
         }
      }   
    }
  
//--- OnCalculate done. Return new prev_calculated.
   return(rates_total);
  }

//+------------------------------------------------------------------+
Files:
6gvzow.JPG  149 kb
 
Can you advise how to get the volume of open positions in MQL4, if SYMBOL_SESSION_INTEREST is not supported? Thank you!
 
kotaries:
Can you please advise how to get the volume of open positions in MQL4, if SYMBOL_SESSION_INTEREST is not supported? Thank you!

Cycle through all positions and calculate their total volume:OrderLots()

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Возвращает сумму лотов открытых позиций                        |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   ( ""  - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - торговая операция          ( -1  - любая позиция)                  |
//|    mn - MagicNumber                ( -1  - любой магик)                    |
//+----------------------------------------------------------------------------+
double GetAmountLotFromOpenPos(string sy="", int op=-1, int mn=-1) {
  double l=0;
  int    i, k=OrdersTotal();

  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol()==sy || sy=="") {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (op<0 || OrderType()==op) {
            if (mn<0 || OrderMagicNumber()==mn) {
              l+=OrderLots();
            }
          }
        }
      }
    }
  }
  return(l);
}
Только "Полезные функции от KimIV".
Только "Полезные функции от KimIV".
  • 2011.02.18
  • www.mql5.com
Все функции взяты из этой ветки - http://forum.mql4...
 

I can't understand why a certain value of prev_calculated is returned?

How is it calculated in the first place?

 
Roman Sharanov:

I can't understand why a certain value of prev_calculated is returned?

How is it calculated in the first place?

The system will keep track of this. In fact, you should only be interested in its value, not how it is calculated internally.
 
Roman Sharanov:

I can't understand why a certain value of prev_calculated is returned?

How is it even calculated?

This is the value returned by OnCalculate() at the last iteration. This is explicitly stated in the documentation:

The relationship between the value returned by OnCalculate() and the second input parameter prev_calculated should be noted. The parameter prev_calculated, when the function is called, contains the valuereturned by OnCalculate() on the previous call. This allows for economical algorithms for calculation of the custom indicator in order to avoid repeated calculations for those bars that haven't changed since the previous call of this function.

 

The task is to find the bar with the minimum closure

for(int x=0; x<=xBars -1; x++)

{

counter++;

// Print(Close[x],",",counter);

int h = ArrayMinimum(Close[x]);

if(counter > 20) break;

}

Compiler swears at Close