Questions from Beginners MQL4 MT4 MetaTrader 4 - page 219

 
Vitaly Muzichenko:
Vitaly Muzichenko:
void OnTick()
  {
     ......здесь работаем с закрытием (тралом и прочим)....
if (Hour()>=10 && Hour()<11) return (0);
     ......остальной код, в частности для открытия....
  }


выдает ошибку: 'return' - 'void' function returns a value Vitaly Muzichenko:
 
Oventu:
void OnTick()
  {
     ......здесь работаем с закрытием (тралом и прочим)....
if (Hour()>=10 && Hour()<11) return;
     ......остальной код, в частности для открытия....
  }
 
Vitaly Muzichenko:
Vitaly Muzichenko:
Thank you!
 
Hello, what about OrdersTotal()?
I always knew that it contains the number of orders -1, i.e. OrdersTotal()-1 and everything was working, but I started writing a program and suddenly, one order is no longer counted, I asked for OrdersTotal() and it gave me the total number of orders = 3, instead of 3-1.
What happens?

The usual form of the loop in the help:

int total=OrdersTotal();
for(int pos=0;pos<total;pos++)
{
}

That is, the first order is equal to zero.

But no, in fact, the first order is 1, which means that we should start the search from 1 and not from zero?
Have the metaquotes done something wrong or am I stupid?

Документация по MQL5: Торговые функции / OrdersTotal
Документация по MQL5: Торговые функции / OrdersTotal
  • www.mql5.com
Не следует путать между собой действующие отложенные ордера и позиции, которые также отображаются на вкладке "Торговля" в панели "Инструменты". Ордер – это распоряжение на проведение торговой операции, а позиция является результатом одной или нескольких сделок.
 
Maksim Mihajlov:
Hello, what's up with OrdersTotal()?
I always knew that it contains the number of orders -1, so OrdersTotal()-1 and everything was working, but I started writing a program and suddenly one order is not taken into account and I asked for OrdersTotal() and it says total orders = 3, instead of 3-1.
What happens?

The usual form of the loop in the help:

int total=OrdersTotal();
for(int pos=0;pos<total;pos++)
{
}

That is, the first order is equal to zero.

But no, in fact, the first order is 1, which means that we should start the search from 1 and not from zero?
Have the metaquotes done something wrong, or am I stupid?

You've mixed up the RELATED ORDERS and POISONS. Read the reference. Be more specific in your question: what are you trying to count: REMOVED ORDERS or POSITIONS? And yes, nothing has changed - the first element index starts with '0'.


Added: example

Example: Calculate Positions and Pending Orders

How to start with MQL5
How to start with MQL5
  • 2020.03.12
  • 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:

You've mixed up the RELATED ORDERS and the POSITIONS. Read the reference. Form your question more precisely: what are you trying to count: RETIRED ORDERS or POSITIONS? And yes, nothing has changed - the first element index starts with '0'.


Added: example

Example: Calculate Positions and Pending Orders

I mean MQL4, not MQL5, there is no difference between pending and market orders!

 
Maksim Mihajlov:

I mean MQL4, not MQL5, there's no division into pending and market pending!

You are writing in MQl5 forum. You are writing in the main section. You post in the MQL5 forum - and you will get answers about MQL5.

Questions on the old terminal are addressed to the special section: MQL4 and MetaTrader 4. From now on, write there. I will transfer your questions to it.

 

I compared two variants, in the first one, I used OrdersTotal()-1 and started the search from zero - got the error
. In the second variant, I started with one and took the whole OrdersTotal() - no error this time

In the screenshots, you can see that OrdersTotal() shows the actual number of orders, not OrdersTotal()-1 ...

The question is
why OrdersTotal() shows the actual number of orders, rather than -1, should it be like this or it is something new?
Because in this case, we should start the search not from zero, but from one!

Files:
4.png  181 kb
2.png  186 kb
 
Maksim Mihajlov:

I compared two variants, in the first one, I used OrdersTotal()-1 and started the search from zero - got the error
. In the second variant, I started with one and took the whole OrdersTotal() - no error this time

In the screenshots, you can see that OrdersTotal() shows the actual number of orders, not OrdersTotal()-1 ...

The question is
why OrdersTotal() shows the actual number of orders, rather than -1, should it be like this or it is something new?
Because in this case, we should start the search not from zero, but from one!

I think I understood my error, sorry...
There is an offset of -1 in this condition:
if (OrderSelect(i-1,SELECT_BY_POS)==true){}
Sorry for being blunt, I took the string from another program and didn't pay attention to the offset!

 
Hello. I need your help in correcting the indicator. The essence of the indicator is as follows. Calculate the magnitude of price increase relative to the previous bar. For zero takes a star bar. That is, the opening price is equal to the closing price. When compiling no errors, but when testing an error on the line 80 20 characters. Thesignal line isalso incorrectly drawn. But I think this is the reason for incorrect calculation of the main buffer. Please help me to fix it.
//+------------------------------------------------------------------+
//|                                                         MSBB.mq4 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

#include <MovingAverages.mqh>

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1  clrGreen
#property indicator_color2  clrRed
#property  indicator_width1  1
input int            InpMSBBPeriod=3;        // Period
input ENUM_MA_METHOD InpMSBBMethod=MODE_SMA;  // Method
//--- indicator buffers
double         ExtMSBBBuffer[];
double         ExtTempBuffer[];
double         ExtPriceBuffer[];
double         ExtSignalBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- indicator buffers mapping
   IndicatorDigits(Digits-2);
//--- drawing settings
   IndicatorBuffers(4);
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(0,ExtMSBBBuffer);
   SetIndexBuffer(1,ExtSignalBuffer);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(2,ExtTempBuffer);
   SetIndexBuffer(2,ExtPriceBuffer);
   SetIndexDrawBegin(1,InpMSBBPeriod);
//--- name for DataWindow and indicator subwindow label
   IndicatorShortName("MSBB("+IntegerToString(InpMSBBPeriod)+")");
   SetIndexLabel(0,"MSBB");
   SetIndexLabel(1,"Signal");
//---
   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;//limit;
//------
   if(rates_total<=InpMSBBPeriod || InpMSBBPeriod<=2)
      return(0);
   /*//--- counting from 0 to rates_total
      ArraySetAsSeries(ExtMSBBBuffer,false);
      ArraySetAsSeries(ExtSignalBuffer,false);
      ArraySetAsSeries(open,false);
      ArraySetAsSeries(high,false);
      ArraySetAsSeries(low,false);
      ArraySetAsSeries(close,false);*/
//---
  // limit=rates_total-prev_calculated;
   //if(prev_calculated>0)
     // limit++;
//--- typical price and its moving average
   for(i=0; i<rates_total; i++)
     {
      ExtTempBuffer[i] = NormalizeDouble((close[i]-open[i])/Point(),2);
      ExtPriceBuffer[i] = NormalizeDouble((close[i+1]-open[i+1])/Point(),2);
      //ExtMSBBBuffer[i]=price_open+ExtTempBuffer[i];
      //Print("ExtPriceBuffer[i] = ", ExtPriceBuffer[i]);
      if(ExtTempBuffer[i]==0)
         ExtMSBBBuffer[i]=0.0;
      if(ExtPriceBuffer[i]>0 && ExtTempBuffer[i]>0)
        {
         double price_open = NormalizeDouble((open[i]-open[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-close[i+1])/Point(),2);
         if((price_open<0 && price_close>0)||(price_open>0 && price_close<0))
            ExtMSBBBuffer[i] = 0.0;
         if((price_open<0 && price_close<0)||(price_open>0 && price_close>0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      if(ExtPriceBuffer[i]>0 && ExtTempBuffer[i]<0)
        {
         double price_open = NormalizeDouble((open[i]-close[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-open[i+1])/Point(),2);
         if((price_open<0 && price_close>0)||(price_open>0 && price_close<0))
            ExtMSBBBuffer[i] = 0.0;
         if((price_open>0 && price_close>0)||(price_open<0 && price_close<0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      if(ExtPriceBuffer[i]<0 && ExtTempBuffer[i]<0)
        {
         double price_open = NormalizeDouble((open[i]-open[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-close[i+1])/Point(),2);
         if((price_open<0 && price_close>0)||(price_open>0 && price_close<0))
            ExtMSBBBuffer[i]=0.0;
         if((price_open<0 && price_close<0)||(price_open>0 && price_close>0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      if(ExtPriceBuffer[i]<0 && ExtTempBuffer[i]>0)
        {
         double price_open = NormalizeDouble((open[i]-close[i+1])/Point(),2);
         double price_close = NormalizeDouble((close[i]-open[i+1])/Point(),2);
         if((price_open>0 && price_close<0)||(price_open<0 && price_close>0))
            ExtMSBBBuffer[i]=0.0;
         if((price_open>0 && price_close>0)||(price_open<0 && price_close<0))
            ExtMSBBBuffer[i]=ExtTempBuffer[i]+price_open;
        }
      //--- signal line counted in the 2-nd buffer
      //ExtSignalBuffer[i]=iMAOnArray(ExtMSBBBuffer,0,InpMSBBPeriod,0,InpMSBBMethod,0);
      SimpleMAOnBuffer(rates_total,prev_calculated,1,InpMSBBPeriod+2,ExtMSBBBuffer,ExtSignalBuffer);
      Print ("ExtSignalBuffer = ", ExtSignalBuffer[i]);
      //--- done
     }
   /* if(ExtPriceBuffer[i]>0||ExtPriceBuffer[i]<0)
     {
      ExtMSBBBuffer[i] = ExtPriceBuffer[i]+ExtTempBuffer[i];
      Print("ExtMSBBBuffer[i] = ", ExtMSBBBuffer[i]);
     }
   if(ExtPriceBuffer[i]==0)
     {
      ExtMSBBBuffer[i] = 0.0;
      Print("ExtMSBBBuffer[i] = ", ExtMSBBBuffer[i]);
     }
   }*/
//---
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Линии индикаторов
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Линии индикаторов
  • www.mql5.com
Некоторые технические индикаторы имеют несколько отрисовываемых на графике буферов. Нумерация индикаторных буферов начинается с 0. При копировании значений индикатора функцией CopyBuffer() в массив типа double для некоторых индикаторов можно указывать не номер копируемого буфера, а идентификатор этого буфера.