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

 
MakarFX:

Try this, it should work.

Nope. It keeps beeping an alert. Here's the whole code and the indulgences. Maybe I'm doing something wrong

//+------------------------------------------------------------------+
//|                                                          777.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#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_buffers 2
#property indicator_plots   2
//--- plot Покупаем
#property indicator_label1  "Продаём"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- plot Продаём
#property indicator_label2  "Покупаем"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrBlue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1
//--- input parameters
double      Buy[];            // Буфер для покупок
double      Sell[];           // Буфер для продаж


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, 234);  //Стрелка "вниз" для продаж
   SetIndexArrow(1, 233);  //Стрелка "вверх" для покупок
   //Устанавливаем текст описания стрелок индикатора для отображения информации в всплывающей подсказке.
   SetIndexLabel(0, "Продаём");
   SetIndexLabel(1, "Покупаем");
   //Определяем разрядность значений индикаторных линий - приравниваем разрядности фин. инструмента
   IndicatorDigits (Digits);
   //Строка с кратким названием индикатора выводится в сплывающей подсказке при наведении указателя мыши на стрелку
   IndicatorShortName ("Мой первый индикатор");
   
//---
   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 limit=rates_total-prev_calculated-2;
   if(limit<1) return(0);
   for(int i=limit;i>=0;i--)
     {
     
      // Снимем показания индикатора
     double in1b = iCustom(NULL,0,"in1",1,i+1); // индикатор 1 стрелка вверх
     double in1s = iCustom(NULL,0,"in1",0,i+1); // индикатор 1 стрелка вниз
      
     
     
     double in2b = iCustom(NULL,0,"in2",0,i+1); // индикатор 2 стрелка вверх
     double in2s = iCustom(NULL,0,"in2",1,i+1); // индикатор 2 стрелка вниз
    
    Comment("in1v = "+DoubleToString(in1b)+"\n" +"in1n = "+DoubleToString(in1s)+"\n"
    +"in2v = "+DoubleToString(in2b)+"\n" +"in2n = "+DoubleToString(in2s));
     
    if(in1b < 2147483647 && in2b < 2147483647) // индикатор стрелка вверх
        {
         Sell[i]=low[i];
       /*  if(show_alert!=time[i])
           {
            Alert(Symbol()+"BUY М "); show_alert=time[i];
           }*/
        }
   
      if(in1s < 2147483647 && in2s < 2147483647) // индикатор стрелка вниз
        {
         Buy[i]=high[i];
        /* if(show_alert!=time[i])
           {
            Alert(Symbol()+"SELL М "); show_alert=time[i];
           }*/
        }
     }
     
   
     
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
Files:
in1.ex4  13 kb
in2.ex4  28 kb
 
jarikn:
Guys, help me make an alert for an indicator. I want to test a combination of different indicators, but I need an alert function. I want the alert to be shown only once when arrow appears. If you are not hard please help me write this function, I can not do it, alerts pop up a whole minute or all the time, even mt4 hangs.


Add a variable

if not a signal the variable becomes false

if (signal and variable== false) {

alert;

variable=true;

}

 
Andrey Sokolov:


Add a variable

the variable becomes false if a new candle appears

if (signal and variable== false) {

alert;

variable=true;

}

will be no more than 1 per candle

ok. thank you.

 
jarikn:

Okay. Thank you.

I changed it there.

 
Another question. Why is this indicator a heavy load on the CPU? I open 10 currency pairs and mt4 gets really bogged down. As a forex trading robot, you should use the mt4 indicators as an indicators.
 
Can you please tell me how to make an object selectable programmatically? I couldn't find anything like that in the Help
 

Hi all, I have an indicator that shows the angle of the trend in degrees (not normalised though). Everything is great on the chart. It can be on the angle curve itself (blue) or on its mean curve (green) - Fig. 1. When calling the indicator in the Expert Advisor through double Custom = iCustom(Symbol(), window, "Angle", 0, 1), the program produces some huge numbers - Figure 2. The dialog window - chart period, "Angle" - indicator name, 0 - zero buffer where the blue line is calculated (I can put 1 - green MA buffer, but the result will be similar), 1 - shift. What could be the problem?

Figure 1

Figure 2

 
Tango_X:
Could you please tell me how to make an object selectable? I couldn't find anything like that in the Help

OBJPROP_SELECTED

Object selection

mql5

mql4

Документация по MQL5: Константы, перечисления и структуры / Константы объектов / Свойства объектов
Документация по MQL5: Константы, перечисления и структуры / Константы объектов / Свойства объектов
  • www.mql5.com
Свойства объектов - Константы объектов - Константы, перечисления и структуры - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
I have written an EA and everything seems to be working. But the thing is that orders should be closed at crossing of slips. To be more precise, only the first order is closed, and it doesn't matter which way it went, then the log generates error OrderClose error 4051. What is the problem?
   //-----------------------------------------------------------
     if (CountSell() == 0 && mama1<mama2 && cci>verh && cci1>verh && cci<cci1)
      {
      tiket = OrderSend(Symbol(), OP_SELL,Lots,Bid,Slippage,0,0,"",Magic,0, Red);
      if (tiket>0)
         {
         SL=NormalizeDouble(Bid+StopLoss*Point,Digits);
         TP=NormalizeDouble(Bid-TakeProfit*Point,Digits);
         if (OrderSelect(tiket, SELECT_BY_TICKET))
            if (!OrderModify(tiket,OrderOpenPrice(),SL,TP,0))
               Print("Ошибка модификации ордера на продажу");
         } else Print("Ошибка открытия ордера на продажу");
      }
    if (CountBuy() == 0 && mama1>mama2 && cci<nuz && cci1<nuz && cci>cci1)
      {
      tiket = OrderSend(Symbol(), OP_BUY,Lots,Ask,Slippage,0,0,"",Magic,0,Blue);
      if (tiket>0)
         {
         SL=NormalizeDouble(Ask-StopLoss*Point,Digits);
         TP=NormalizeDouble(Ask+TakeProfit*Point,Digits);
         if (OrderSelect(tiket, SELECT_BY_TICKET))
           if (!OrderModify(tiket,OrderOpenPrice(),SL,TP,0))
           Print("Ошибка модификации ордера на покупку");
         } else Print("Ошибка открытия ордера на покупку");
      }  
      
      if(mama1>mama2 && CountSell()>0)
      {
         for(int i = OrdersTotal() -1;i>=0; i--)
         {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
            {
            if(OrderMagicNumber()==Magic && OrderType()==OP_SELL)
            OrderClose(OrderType(),OrderLots(),Ask,Slippage,Black);
            }
         }
         
      }
       if(mama1<mama2 && CountBuy()>0)
      {
         for(int i = OrdersTotal() -1;i>=0; i--)
         {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
            {
            if(OrderMagicNumber()==Magic && OrderType()==OP_BUY)
            OrderClose(OrderType(),OrderLots(),Bid,Slippage,Black);
            }
         }
         
      }
 
Tango_X:
Can you please tell me how to programmatically make an object selected? I haven't found anything like that in the Help

If you use the standard object creation function, the default setting is selection = true. For example, for the trend line, the 4th line from the bottom:

bool TrendCreate(const long            chart_ID = 0,      // ID графика
                 const string          name = "TrendLine", // имя линии
                 const int             sub_window = 0,    // номер подокна
                 datetime              time1 = 0,         // время первой точки
                 double                price1 = 0,        // цена первой точки
                 datetime              time2 = 0,         // время второй точки
                 double                price2 = 0,        // цена второй точки
                 const color           clr = clrRed,      // цвет линии
                 const ENUM_LINE_STYLE style = STYLE_SOLID, // стиль линии
                 const int             width = 4,         // толщина линии
                 const bool            back = false,      // на заднем плане
                 const bool            selection = true, // выделить для перемещений
                 const bool            ray_right = false, // продолжение линии вправо
                 const bool            hidden = true,     // скрыт в списке объектов
                 const long            z_order = 0)       // приоритет на нажатие мышью
Reason: