Questions from a "dummy" - page 200

 

So, there is a function to determine the opening time of a bar (including if the bar is in the future)

//+---------------------------------------------------------------------------+
//| Получение точного времени открытия                                        |
//|Input:                                                                     |
//|1) Время, которое необходимо округлить до ближайшего времени открытия бара |
//|2) Переменная для вывода результата                                        |
//|3) Период ТФ                                                               |
//|4) Отклонение влево-вправо                                                 |
//|Возврат: количество элементов(1), 0 если не скопировано, (-1) если ошибка  |
//+---------------------------------------------------------------------------+
int GetSingleBarOpenTime(datetime Time,datetime &Output,ENUM_TIMEFRAMES nPeriod,int Shift=0) export
  {
   datetime OpenTime[1];
   int Count=0;
// если бар существует то используем стандартную процедуру поиска времени открытия
   if(Time<=TimeCurrent() && Shift==0)
     {
      Count=CopyTime(Symbol(),nPeriod,Time,1,OpenTime);
      if(Count==0)
        {
         Print("GetCorrectOpenTime CopyTime elements=0");
         return(0);
        }
      else if(Count<0)
        {
         Print("GetCorrectOpenTime error "+(string)GetLastError());
         return(Count);
        }
      else
        {
         Output=OpenTime[0];
         return(Count);
        }
     }
//если бар находится в будущем то используем следующую процедуру
   else
     {
      MqlDateTime sTime;
      // NumOfUnits - количество стандартных единиц
      int NumOfUnits=0; 
      int ToRnd;
      TimeToStruct(Time,sTime);
      //Единица измерения(1-минута, 2 - час, 3 - день, 4 - неделя(но используются дни), 5 - месяц)
      short Unit=0;
      //в зависимости от ТФ инициализируются параметры
      switch(nPeriod)
        {
         case PERIOD_M1:   {Unit=1;NumOfUnits=1;break;}
         case PERIOD_M2:   {Unit=1;NumOfUnits=2;break;}
         case PERIOD_M3:   {Unit=1;NumOfUnits=3;break;}
         case PERIOD_M4:   {Unit=1;NumOfUnits=4;break;}
         case PERIOD_M5:   {Unit=1;NumOfUnits=5;break;}
         case PERIOD_M6:   {Unit=1;NumOfUnits=6;break;}
         case PERIOD_M10:  {Unit=1;NumOfUnits=10;break;}
         case PERIOD_M12:  {Unit=1;NumOfUnits=12;break;}
         case PERIOD_M15:  {Unit=1;NumOfUnits=15;break;}
         case PERIOD_M20:  {Unit=1;NumOfUnits=20;break;}
         case PERIOD_M30:  {Unit=1;NumOfUnits=30;break;}
         case PERIOD_H1:   {Unit=2;NumOfUnits=1;break;}
         case PERIOD_H2:   {Unit=2;NumOfUnits=2;break;}
         case PERIOD_H3:   {Unit=2;NumOfUnits=3;break;}
         case PERIOD_H4:   {Unit=2;NumOfUnits=4;break;}
         case PERIOD_H6:   {Unit=2;NumOfUnits=6;break;}
         case PERIOD_H8:   {Unit=2;NumOfUnits=8;break;}
         case PERIOD_H12:  {Unit=2;NumOfUnits=12;break;}
         case PERIOD_D1:   {Unit=3;NumOfUnits=1;break;}
         case PERIOD_W1:   {Unit=4;NumOfUnits=7;break;}
         case PERIOD_MN1:  {Unit=5;NumOfUnits=1;break;}
         default:         {Print("Period is unknown"); break;}
        }
      // Если ТФ - минуты, то
      if(Unit==1)
        {
         sTime.sec=0;
         //Остаток от деления
         ToRnd=(int)fmod(sTime.min,NumOfUnits);
         Time=StructToTime(sTime);
         // Округление до ближайшего времени открытия(пример: если сейчас 14:25, и тф 2min, то ближайщее время открытия бара - 14:24)
         Time-=(ToRnd*60);
         Time+=(NumOfUnits*Shift*60);

        }
      else if(Unit==2)
        {
         sTime.sec=0;
         sTime.min=0;
         ToRnd=(int)fmod(sTime.hour,NumOfUnits);
         Time=StructToTime(sTime);
         Time-=(ToRnd*60*60);
         Time+=(NumOfUnits*Shift*60*60);
        }
      else if(Unit==3)
        {
         sTime.hour=0;
         sTime.min=0;
         sTime.sec=0;
         ToRnd=(int)fmod(sTime.day,NumOfUnits);
         Time=StructToTime(sTime);
         int hds;
         hds=sTime.day_of_week;
         if (hds==0) hds=7;
         hds=floor((hds+Shift)/7)*2;
         int ti=Shift+hds;
         while (hds>7)
         {
            hds=(floor(hds/7))*2;
            ti+=hds;
         }
         Print(ti);
         Time-=(ToRnd*60*60*24);
         Time+=(NumOfUnits*Shift*60*60*24);
        }
      else if(Unit==4)
        {
         sTime.hour=0;
         sTime.min=0;
         sTime.sec=0;
         ToRnd=(int)fmod(sTime.day,NumOfUnits);
         Time=StructToTime(sTime);
         Time-=(ToRnd*60*60*24);
         Time+=(NumOfUnits*Shift*60*60*24);
        }
      else if(Unit==5)
        {
         sTime.sec=0;
         sTime.min=0;
         sTime.hour=0;
         sTime.day=1;
         sTime.mon=sTime.mon-(int)fmod(sTime.mon,NumOfUnits)+(NumOfUnits*Shift);
         while(sTime.mon<1)
           {
            sTime.year--;
            sTime.mon=12+sTime.mon;
           }
         while(sTime.mon>12)
           {
            sTime.year++;
            sTime.mon=sTime.mon-12;
           }
         if(sTime.sec<0)
            Print("GetSingleBarOpenTime seconds error");
         if(sTime.min<0)
            Print("GetSingleBarOpenTime minutes error");
         if(sTime.hour<0)
            Print("GetSingleBarOpenTime hours error");
         if(sTime.day<1)
            Print("GetSingleBarOpenTime days error");
         if(sTime.mon<0)
            Print("GetSingleBarOpenTime months error");
         if(sTime.year<1970)
            Print("Year < 1970");
         Time=StructToTime(sTime);
        }
      Output=Time;
      return(1);
     }
  }

The problem with Shift is that it now shifts not by the number of bars but by the number of days (it doesn't matter on D1 or D1; the main thing is to understand D1). So I think I got it in my head that I can check the number of daysTotal by shift (number of weekdays) and the current day of the week, but which formula to use - I can not determine.

Note: in Unit=3 try to do it (so far unsuccessful)

Help please.

 
victorva: the trade request gives error 10016 ("wrong stops"). What are they wrong in?

1. Insert the code correctly (Ctrl+Alt+M).

void OnTick()
  {
   MqlTick last_tick={0};                       // предопределенная структура для получения текущих данных рынка
   SymbolInfoTick("EURUSD",last_tick);          // инструмент: указывать обязательно
   double Bid = last_tick.bid;                         // Текущая цена Bid
   MqlTradeRequest request={0};                 
   MqlTradeResult result={0};                 
   request.action=TRADE_ACTION_DEAL;           
   request.magic=555;                          
   request.symbol="EURUSD";
   request.volume=1.0;                  
   request.deviation=0;                 
   request.type=ORDER_TYPE_BUY;                        
   request.sl=Bid-300*_Point;                         // Уровень Stop Loss ордера
   request.tp=Bid+1000*_Point;                    // Уровень Take Profit ордера
   OrderSend(request,result);
   Comment("retcode = ",result.retcode);
  }
2. Let's start with the fact that your request doesn't contain the mandatory field request.price (the absence of such a field is only acceptable for Market Execution mode). So it turns out that as long as request.price==0.
MQL5.community - Памятка пользователя
MQL5.community - Памятка пользователя
  • 2010.02.23
  • MetaQuotes Software Corp.
  • www.mql5.com
Вы недавно зарегистрировались и у вас возникли вопросы: Как вставить картинку в сообщение на форуме, как красиво оформить исходный код MQL5, где находятся ваши Личные сообщения? В этой статье мы подготовили для вас несколько практических советов, которые помогут быстрее освоиться на сайте MQL5.community и позволят в полной мере воспользоваться доступными функциональными возможностями.
 
victorva:

the trade query gives error 10016 ("wrong stops"). What are they wrong?


request.sl=Bid-300*_Point; // Stop Loss level of the order
request.tp=Bid+1000*_Point; // Level of Take Profit order

In that they are not normalized. (use the SRC button to insert the code).

  request.sl=NormalizeDouble(Bid-300*_Point,_Digits);   // Уровень Stop Loss ордера
  request.tp=NormalizeDouble(Bid+1000*_Point,_Digits);  // Уровень Take Profit ордера
 

Checking the functionality of the automatic link insertion

1. Вставляйте код правильно (Ctrl+Alt+M).

 
Yedelkin:

1. Insert the code correctly (Ctrl+Alt+M).

2. Let's start with the fact that your request doesn't specify the mandatory field request.price (the absence of such a field is only allowed for Market Execution mode). So it turns out that as long as request.price==0.

Thank you. Put the price in, it worked.

 

Please help me, I can't figure one thing out.

|9|8|7|6|5|4|3|2|1|0| <-- time series Rates

CopyRates(Symbol(),Period(),Time,2,Result);

For example I've specified time of candlestick #3. In this case, I get back the Rates of candlesticks #3 and #4. But how to get the rates of candlesticks #3 and #2, having an open time of candlestick #3. The negative number is not digested.

I had the idea of finding an index of sorts, but to do it I need to copy all elements from the current one, but, gosh, if I have M1 and a bar 10 years old, then the array is too big.

Thanks in advance

 

Good day!

Could you please explain in which units the traffic is measured in the "Services" tab of MetaTrader 5 Strategy Tester (MetaTester 5 Agents Managers build 712)? Is it measured in kiloBytes|megaBytes or kiloBytes|megaBytes?

Thank you.

 

Guys, can you tell me if there is an indicator or object in the base that allows you to display other currencies' charts on the main chart?

p.s. I wrote my own for mt4, but maybe there is a ready-made one here...

 
storm:

Guys, can you tell me if there is an indicator or object in the base that allows you to display other currencies' charts on the main chart?

p.s. I wrote my own for mt4, but maybe there is a ready-made one here...

I found it, they already wrote it, z**** , I don't need to write it myself at least. https://www.mql5.com/ru/code/1055
MultiCurrency
MultiCurrency
  • votes: 9
  • 2012.09.14
  • Nikolay Kositsin
  • www.mql5.com
Индикатор MultiCurrency позволяет анализировать одновременно до восьми графиков валют.
 
storm:
Found it, it's already written, z**** , you don't have to write it yourself. https://www.mql5.com/ru/code/1055
Inversion in it was intended by the author, but was not implemented, I had to tweak it, but credit to the author!
Reason: