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

 
DYM:

I'm having trouble with this, I understand the price1 anchor point, but I can't figure out how to make the condition. My variant doesn't work.

This section

           double a=ObjectGetDouble(id,name,OBJPROP_PRICE1);
           double b=ObjectGetDouble(id,name,OBJPROP_PRICE2);
             if(b!=a) 
           {
            ObjectSetDouble(id,name,OBJPROP_PRICE2,a);
           }

should be put in OnTimer()

 

does anyone know if individual compiler warnings can be disabled ?

or else

"declaration of 'XXxx' hides global variable"

bother me...



 
Maxim Kuznetsov:

does anyone know if individual compiler warnings can be disabled ?

or else

"declaration of 'XXxx' hides global variable"

are annoying...

Can't

 
MakarFX:

This section

should be put in OnTimer()

Thank you very much for your help. I think I understood how this condition works. Unfortunately, I have very little information on handling the OnTimer() function, but I found one tip and the condition works. But will it not waste all memory if the function works in milliseconds?

This is what I got:

extern ENUM_LINE_STYLE  line_st   =  STYLE_SOLID;         // 9. Стиль линий
extern int              line_wd   =  2;                   // 10. Толщина линий

// Координаты
extern int x_coor = 7;    // Сдвиг по оси X
extern int y_coor = 10;    // Сдвиг по оси Y

string nameline;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
      EventSetMillisecondTimer(500);
   
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
    //RefreshRates();
       double a=ObjectGetDouble(ChartID(),nameline,OBJPROP_PRICE1);
       double b=ObjectGetDouble(ChartID(),nameline,OBJPROP_PRICE2);
       if(b!=a) 
         {
            ObjectSetDouble(ChartID(),nameline,OBJPROP_PRICE2,a);
            Print("Работает - функция");
         }         
         else
            {
              Print("Не работает - функция");
            }
  }
//+------------------------------------------------------------------+
//| ChartEvent function                                              |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
  {
  
   datetime dt1     = 0;
   double   price1  = 0;
   datetime dt2     = 0;
   double   price2  = 0;
   int      window   = 0;
   int      x        = 0;
   int      y        = 0;

//+------------------------------------------------------------------+ 
      //--- Клик по 1 линии
   if(id==CHARTEVENT_OBJECT_CLICK)
     {
      string clickObject=sparam;
      if(clickObject==line[0])
        {
        nameline="line_"+IntegerToString(MathRand()+100,0,' ');

         y=200;
         ChartXYToTimePrice(0,25,y,window,dt1,price1);
         ChartXYToTimePrice(0,147,y,window,dt2,price2);

         TrendCreate(0,nameline,0,dt1,price1,dt2,price2,color1,line_st,line_wd,false,true,false,false,false,0);
         
        }

     }
}

void OnDeinit(const int reason)
  {
   Comment("");
   EventKillTimer();

  }
 
DYM:

Thank you very much for your help. I think I understand how this condition works. Unfortunately, there is very little information on how to work with the OnTimer() function, but I found one hint and the condition works. But will this function not overload memory if it is triggered in milliseconds?

Here's what I got:

It won't... and it's better to do this.

   if(b!=a) 
     {
      if(ObjectSetDouble(ChartID(),nameline,OBJPROP_PRICE2,a))
        {
         Print("Работает - функция");
        }
      else
        {
         Print("Ошибка-",GetLastError());
        }
     }
 
MakarFX:

will not score... and it's better to do so.

Thank you very much!

 
MakarFX:

will not score... and it's better to do so

And it's better to do it this way:

   if(b!=a) 
     {
      if(!ObjectSetDouble(ChartID(),nameline,OBJPROP_PRICE2,a))
         Print("Ошибка-",GetLastError());
     }
 
Vitaly Muzichenko:

Or better still:

Thank you.
 

Hi all. i found an article and decided to re-do it in my own way. but since i have my hands in the wrong place, i would like your advice on what i did wrong.

Here's the article I'm referring to -http://mql.su/2017/11/lesson11-first-indicator/

I wanted to make my own indicator based on rsi readings.

I'm not very experienced in this field but it seems I'm doing something wrong )))))))))

I do not need to do it for me, just tell me where and what to add and replace!

#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_chart_window
//#property indicator_separate_window  // Индик. рисуется в основном окне
//////////////////////////////////////////
#property indicator_buffers 2   // Сообщаем о том, что у нас будет два буфера
#property indicator_color1 Lime // Цвет стрелки для покупок
#property indicator_color2 Red  // Цвет стрелки для продаж


double Buy[];                   // Буфер для покупок
double Sell[];                  // Буфер для продаж

#define  BUY 0
#define  SELL 1

input int per = 14;
input int verx = 70;
input int niz = 30;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
     // Установим связь наших массивов с буферами индикатора
   SetIndexBuffer (0, Buy);
   SetIndexBuffer (1, Sell);  
   
    // Устанавливаем нулевые значения для индикатора, при которых не будет сигнальных стрелок
   SetIndexEmptyValue (0, 0);
   SetIndexEmptyValue (1, 0);
   
     //Определяем стиль отображения индикаторных линий - стрелка
   SetIndexStyle (0, DRAW_ARROW);
   SetIndexStyle (1, DRAW_ARROW); 
   
     // Установим значки "стрелки" для буферов
   SetIndexArrow(0, 233);  // Стрелка "вверх" для покупок
   SetIndexArrow(1, 234);  // Стрелка "вниз" для продаж
   
   //Определяем разрядность значений индикаторных линий - приравниваем разрядности фин. инструмента
   IndicatorDigits (Digits);
   //Строка с кратким названием индикатора выводится в сплывающей подсказке при наведении указателя мыши на стрелку
   IndicatorShortName ("Мой первый индикатор");
   //Устанавливаем текст описания стрелок индикатора для отображения информации в всплывающей подсказке.
   SetIndexLabel(0, "Покупаем");
   SetIndexLabel(1, "Продаём");
//---
   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 counted_bars = IndicatorCounted();
   int limit, signal;
   
   //Пересчитаем последний посчитанный бар
   if (counted_bars>0) 
       counted_bars-- ;
       
   //Определяем число баров, которые следует пересчитать
   limit=Bars-counted_bars;
   
   // Чтобы индикатор "не перерисовывался" расчет ведем с последнего закрытого бара(он имеет индекс равный 1)
   // нулевой бар является текущим, т.е. он изменяется с каждым новым тиком до тех пор пока не будет закрыт
   
   for(int i = 2; i < limit; i++)  
   {
         //Проверяем сигнал на вход для текущего бара
         signal = Signal(i-1);
         
         if (signal == BUY)
         {
            Buy[i-1] = low[i-1];
         }
         else   
         if (signal == SELL)
         {
            Sell[i-1] = high[i-1];
         }
   }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
 int Signal(int i)
{
  // Снимем показания индикатора
   double Current   = iRSI(NULL, 0, per, PRICE_CLOSE, i);
   double Previous    = iRSI(NULL, 0, per, PRICE_CLOSE, i+1);
   
    double SCurrent   = iRSI(NULL, 0, per, PRICE_CLOSE, i);
     // Для предыдущего бара
   double SPrevious    = iRSI(NULL, 0, per, PRICE_CLOSE, i+1);
      // А теперь проверим всловия для наличия сигналов
   
   // есть сигнал на покупку?
   if(per >= verx && Close[1]<Open[1])
   
   return(BUY);
   
   if(per <= verx && Close[1]>Open[1])
    return(SELL);
   
   // Сигнала нет   
   return(-1);
   }
Урок №11: Пишем индикатор
Урок №11: Пишем индикатор
  • 2017.11.08
  • admin
  • mql.su
На этом уроке мы напишем простой индикатор, который в дальнейшем будем использовать при разработке советника. А использовать для получения сигнала мы будем уже существующие — Moving Average и MACD. Алгоритм следующий: Определять направление сделки (покупка или продажа) мы будем по индикатору Moving Average с периодом 100 на дневном...
Files:
 
jarikn:

Hi all. i found an article and decided to re-do it for my own use. but since i have my hands in the wrong place, i would like your advice on what i did wrong.

Here's the article I'm referring to -http://mql.su/2017/11/lesson11-first-indicator/

I wanted to make my own indicator based on rsi readings.

I'm not very experienced in this field but it seems I'm doing something wrong )))))))))

You don't have to do it for me, just tell me where and what to add and replace!

   if(per >= verx && Close[1]<Open[1])
   
   return(BUY);
   
   if(per <= verx && Close[1]> Open[1])
    return(SELL);

You are comparing the wrong rsi instead of "per".

Reason: