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

 
DanilaMactep #:

Good afternoon everyone. I have 20 tools open and need to load the same template on all of them. Is it possible to automate this with a script? If yes, can you please share the code how to do it?

Template as default will be remembered. And all new windows will open by default template.

 
Tretyakov Rostyslav #:
Just post the code.

There's five pages of code in there. You'll all be throwing stones at me, I'm an amateur... the forum says it's more than 64,000 characters.

Files:
 
Sergey Dymov #:

There's five pages of code in there. You'll all be throwing stones at me, I'm an amateur... forum swears it's more than 64000 characters.

You should specify a character in'CopyXXXX' function:

   int  copy_open=CopyOpen(Symbol(),PERIOD_M15,0,1,OpenPrice);
   if(copy_open<0)
      Print("Неудачная попытка копирования OpenPrice");
 


Доброго времени суток!
Помогите разобраться я новичок в програмировании, посмотрел ролик "Как написать индикатор" писал код с ведущим ,от кампилировал без ошибок, вывожу на терминал индикатор не отрисовывается, ошибок нет в окне он есть в списке запущиных индекаторовв тоже. Что я делаю не так?




//+------------------------------------------------------------------+
//|                                                     MaOsC Уч.mq5 |
//|                                             Copyright 2022,Игорь |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022,Игорь"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window                                              //Выводить индикатор в отдельное окно
#property indicator_buffers 4
#property indicator_plots   1                                                    //Количество графических серий в индикаторе
#property indicator_label1  "MAOS"
#property indicator_type1 DRAW_COLOR_HISTOGRAM                                   // Графическое построение цветная гистограмма
#property indicator_color1 clrLightBlue,clrBlue,clrYellow,clrGold,clrDarkOrange
#property indicator_style1 STYLE_SOLID                                           //стиль линий для отрисовки
#property indicator_width1 2                                                     //толшина линий

input uint                 MaFastPeriod    = 7;
input uint                 MaSlowPeriod    = 33;
input ENUM_MA_METHOD       MaMethod        = MODE_SMA;                        //метод МА
input ENUM_APPLIED_PRICE   MaAppliaedPrice = PRICE_CLOSE;

double  MAOSBuffer[];       //буфер если связан с ценой то тип double
double  ColorsBuffer[];
double  FastBuffer[];
double  SlowBuffer[];


int   FastPeriod,                                                                 // глобальные переменные
      SlowPeriod,
      fma_h, sma_h;                                                               // описатель (хэндл) индекатора,для того что-бы можно было обращаться к нему в дальнейшем

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
{
   FastPeriod = int(MaFastPeriod < 1 ? 1 : MaFastPeriod);  //описание действия (если MaFastPeriod меньше 1 то указываем 1 а если оно больше либо = 1 то указываем MaFastPeriod)
   SlowPeriod = int(MaSlowPeriod == MaFastPeriod ? FastPeriod + 1 : MaSlowPeriod < 1 ? 1 : MaSlowPeriod); // описание действия(если MaSlowPeriod = FastPeriod то в таком случае +1,а иначе если MaSlowPeriod меньше 1 то указываем 1 а если оно больше либо = 1 то указываем MaSlowPeriod)
   
   SetIndexBuffer(0, MAOSBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, ColorsBuffer, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, FastBuffer, INDICATOR_CALCULATIONS);
   SetIndexBuffer(3, SlowBuffer, INDICATOR_CALCULATIONS);   
   
   ArraySetAsSeries(MAOSBuffer, true);
   ArraySetAsSeries(ColorsBuffer, true);
   ArraySetAsSeries(FastBuffer, true);
   ArraySetAsSeries(SlowBuffer, true);

   ResetLastError();
   
   fma_h = iMA(NULL,PERIOD_CURRENT, FastPeriod, 0, MaMethod, MaAppliaedPrice);
   if (fma_h == INVALID_HANDLE)
   {
      Print("Не удалось инициализировать индикатор Moving Average");
      return INIT_FAILED;
   }
   
   fma_h = iMA(NULL,PERIOD_CURRENT, SlowPeriod, 0, MaMethod, MaAppliaedPrice);
   if (sma_h == INVALID_HANDLE)
   {
      Print("Не удалось инициализировать индикатор Moving Average");
      return INIT_FAILED;
   } 
   
   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[])
{
   if (rates_total < 4) return(0); //индикатор. проверку и расчёт количества прощитываемых баров(если rates_total меньше 4 баров то ни какого вычесления и отрисовки не делаем )
   
   int limit = rates_total - prev_calculated;
   if (limit > 1)
   {
      limit = rates_total -2;
      ArrayInitialize(MAOSBuffer, 0);
      ArrayInitialize(ColorsBuffer, 4);
      ArrayInitialize(FastBuffer, 0);
      ArrayInitialize(SlowBuffer, 0);
   }
   
   int count =(limit > 1 ? rates_total : 1),
   copied = 0;
   
   copied = CopyBuffer(fma_h, 0, 0, count, FastBuffer);
   
   if  (copied != count)
       return(0);
       
   copied = CopyBuffer(sma_h, 0, 0, count, SlowBuffer);
   
   if  (copied != count)
       return(0);


   for(int i=limit; i>=0; i--)
   {
       MAOSBuffer[i]   = FastBuffer[i] - SlowBuffer[i];
       ColorsBuffer[i] = (MAOSBuffer[i] > 0 ? (MAOSBuffer[i] > MAOSBuffer[i=1] ? 0 : 1) : MAOSBuffer[i] < 0 ? (MAOSBuffer[i] < MAOSBuffer[i+1] ? 2: 3) : 4);
   }

   return(rates_total);
}
//+------------------------------------------------------------------+
Files:
MaOsC_sv.mq5  11 kb
MaOsC_dr.ex5  11 kb
 
MatveySt #:


1) Both must be sma_h

   fma_h = iMA(NULL,PERIOD_CURRENT, FastPeriod, 0, MaMethod, MaAppliaedPrice);
   if (fma_h == INVALID_HANDLE)
   {
      Print("Не удалось инициализировать индикатор Moving Average");
      return INIT_FAILED;
   }
   
   fma_h = iMA(NULL,PERIOD_CURRENT, SlowPeriod, 0, MaMethod, MaAppliaedPrice);
   if (sma_h == INVALID_HANDLE)
   {
      Print("Не удалось инициализировать индикатор Moving Average");
      return INIT_FAILED;
   } 

2) put "+"

   for(int i=limit; i>=0; i--)
   {
       MAOSBuffer[i]   = FastBuffer[i] - SlowBuffer[i];
       ColorsBuffer[i] = (MAOSBuffer[i] > 0 ? (MAOSBuffer[i] > MAOSBuffer[i=1] ? 0 : 1) : MAOSBuffer[i] < 0 ? (MAOSBuffer[i] < MAOSBuffer[i+1] ? 2: 3) : 4);
   }
 
Tretyakov Rostyslav #:

1) Both must be sma_h

2) put "+"

Thank you!!! It's all working!
 

Help get the chat number out. It's resetting. I don't get it.

#include <Telegram.mqh>
long Ch_id;
//+------------------------------------------------------------------+
//|   CMyBot                                                         |
//+------------------------------------------------------------------+
class CMyBot: public CCustomBot
  {
public:
   void ProcessMessages(void)
     {
      for(int i=0; i<m_chats.Total(); i++)
        {
         CCustomChat *chat=m_chats.GetNodeAtIndex(i);
         //--- if the message is not processed
         if(!chat.m_new_one.done)
           {
            chat.m_new_one.done=true;
            string text=chat.m_new_one.message_text;
            Ch_id=chat.m_id;   // И здесь не хочет присваивать.
            //--- start
            if(text=="/start")
               SendMessage(chat.m_id,"Hello, world! I am bot. \xF680");
               Alert("chat.m_id ",chat.m_id);
               Ch_id=chat.m_id;  // что здесь не так?

            //--- help
            if(text=="/help")
               SendMessage(chat.m_id,"My commands list: \n/start-start chatting with me \n/help-get help");
           }        
        }
     }
  };

//---
input string InpToken="5068873298:AAGihZr2vJsD5Zs1ca4i0r2JimAFuIbbmI0";//Token
//---
CMyBot bot;
int getme_result;
//+------------------------------------------------------------------+
//|   OnInit                                                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- set token
   bot.Token(InpToken);
//--- check token
   getme_result=bot.GetMe();
//--- run timer
   EventSetTimer(3);
   OnTimer();
//--- done
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|   OnDeinit                                                       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Comment("");
  }
//+------------------------------------------------------------------+
//|   OnTimer                                                        |
//+------------------------------------------------------------------+
void OnTimer()
  {
//--- show error message end exit
   if(getme_result!=0)
     {
      Comment("Error: ",GetErrorDescription(getme_result));
      return;
     }
//--- show bot name
   Comment("Bot name: ",bot.Name());
//--- reading messages
   bot.GetUpdates();
//--- processing messages
   bot.ProcessMessages();
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam)
{
   if(id==CHARTEVENT_KEYDOWN &&
         lparam=='Q')
   {

      Alert("445672666"); // Номер чата вручную забил, работает.
       
      bot.SendMessage(445672666,"ee\nAt:100\nDDDD");
  //    bot.SendMessage(Ch_id,"ee\nAt:100\nDDDD"); не хочет работать, Ch_id=0.
      Alert(Ch_id);
      
     
   }
}
 

Alexey Viktorov

Thank you, that's helpful.

 
Good morning. Need some help. In the tester, the order profit is not correctly displayed on the chart. Everything was fine before. But today I have a feeling that it understates very much.
 
Сергей Груздев #:
Good morning. I need some help. In the tester, the order profit is not correctly displayed on the chart. Everything was fine before. But today it feels like it understates very much.

It's this way for you.

Reason: