Questions from Beginners MQL4 MT4 MetaTrader 4 - page 155

 
Vitaly Gorbunov:
I am going to the country house now and will be there on Monday. If you're interested, add me as a friend and we'll chat without clogging up the forum.
Okay.
 
nidves:

I am learning to work with arrays through this code. After all, the task is not complicated in principle.

The "Open" quotes are already stored in the array above. Therefore, I should just pull out the quote of the date I need from the array.

iTime(symbolMT,periodMT,numberBar);

Try to get the dates like this

Or write an indicator and it will be easier to take

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[])
  {

both date and price and they are all already in the arrays time[],open[],high[],low[],close[],

 
Vladimir Karputov:

Who told you that? The simplest test with#property indicator_chart_window is\MQL5\Indicators\Examples\Custom Moving Average.mq5 indicator

Write an example based on this indicator and show what does not work.

Here is the indicator

I am unable to bind the indicator (i-DRP...) to my Expert Advisor (DR Test) through iCustom:

what i am doing wrong tell me please

thanks

 
jakhongir.mamadiev:

Here is the floor. indicator

I am not able to connect the indicator (i-DRP...) with my Expert Advisor (DR Test) through iCustom:

what i am doing wrong tell me please

thanks

Please advise why it does not work

 

Hello

please help me tie the floor. indicator (i-DRPojection) with the EA properly.

I can not

floor. indicator :

 #property copyright "Ким Игорь В. aka KimIV"
#property link        "http://www.kimiv.ru"
//----
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 clrAqua    // Blue
#property indicator_color2 clrOrange //Salmon
#property strict
//------- Внешние параметры ------------------------------------------
extern int   NumberOfDay = 10 ;   // Количество дней
//------- Буферы индикатора ------------------------------------------
double MaxDay[];
double MinDay[];
//+---------------------------------------------------------------------------------+
void init(){ //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//+---------------------------------------------------------------------------------+
   SetIndexBuffer ( 0 , MaxDay); SetIndexStyle ( 0 , DRAW_LINE , STYLE_SOLID , 1 );
   SetIndexBuffer ( 1 , MinDay); SetIndexStyle ( 1 , DRAW_LINE , STYLE_SOLID , 1 );
   //Comment("");
   }
//+---------------------------------------------------------------------------------+
int start(){ //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//+---------------------------------------------------------------------------------+
   double po= 0 , ph= 0 , pl= 0 , pc= 0 , x= 0 ;
   int     currDay= 0 , i= 0 , j= 0 ;
     if ( Period ()> 240 ) 
     {
       Comment ( "Индикатор i-DRProjections не поддерживает ТФ более Н4 !" ); return 0 ;
     }
     while (i<=NumberOfDay) 
     {
         if (currDay!= TimeDay ( Time [j])) 
        {
         po= iOpen ( NULL , 1440 , i+ 1 );
         ph= iHigh ( NULL , 1440 , i+ 1 );
         pl= iLow   ( NULL , 1440 , i+ 1 );
         pc= iClose ( NULL , 1440 , i+ 1 );
         if (pc<po) x=(ph + pl + pc + pl)/ 2 ;
         if (pc>po) x=(ph + pl + pc + ph)/ 2 ;
         if (pc==po) x=(ph + pl + pc + pc)/ 2 ;
         i++;
        }
      currDay= TimeDay ( Time [j]);
      MaxDay[j]=x - pl;
      MinDay[j]=x - ph;
      j++;
     }
   return 0 ;   
}
//+----------------------------------------------------------------------------------+
void deinit(){ //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//+----------------------------------------------------------------------------------+
   ObjectDelete ( "LineHi" );
   ObjectDelete ( "LineLo" );
   Comment ( "" );
}

advisor (my attempt to fail):

 //--------------------------------------------------------------- 1 --
                                   // Численные значения для М15
extern double StopLoss   = 200 ;     // SL для открываемого ордера
extern int     NumberOfDay= 100 ;     // Значение DR: Кол-во дней
extern double Lots       = 0.1 ;     // Жестко заданное колич. лотов
extern double Prots      = 0.07 ;     // Процент свободных средств


bool Work= true ;                     // Эксперт будет работать.
string Symb;                       // Название финанс. инструмента
//--------------------------------------------------------------- 2 --
int start()
  {
   int
   Total,                           // Количество ордеров в окне 
   Tip=- 1 ,                           // Тип выбран. ордера (B=0,S=1)
   Ticket;                           // Номер ордера
   double
   UpLine,                           // Значен. DR. 
   DnLine,                           // Значен. DR.
   Lot,                             // Колич. лотов в выбран.ордере
   Lts,                             // Колич. лотов в открыв.ордере
   Min_Lot,                         // Минимальное количество лотов
   Step,                             // Шаг изменения размера лота
   Free,                             // Текущие свободные средства
   One_Lot,                         // Стоимость одного лота
   Price,                           // Цена выбранного ордера
   SL,                               // SL выбранного ордера 
   TP;                               // TP выбранного ордера
   bool
   Work,
   Ans  = false ,                     // Ответ сервера после закрытия
   Cls_B= false ,                     // Критерий для закрытия  Buy
   Cls_S= false ,                     // Критерий для закрытия  Sell
   Opn_B= false ,                     // Критерий для открытия  Buy
   Opn_S= false ;                     // Критерий для открытия  Sell
//--------------------------------------------------------------- 3 --
   // Предварит.обработка
   /*if(Bars < Period_MA_2)                       // Недостаточно баров
     {
      Alert("Недостаточно баров в окне. Эксперт не работает.");
      return;                                   // Выход из start()
     }
   if(Work==false)                              // Критическая ошибка
     {
      Alert("Критическая ошибка. Эксперт не работает.");
      return;                                   // Выход из start()
     }*/
//--------------------------------------------------------------- 4 --
   // Учёт ордеров
   Symb= Symbol ();                               // Название фин.инстр.
   Total= 0 ;                                     // Количество ордеров
   for ( int i= 1 ; i<= OrdersTotal (); i++)           // Цикл перебора ордер
     {
       if ( OrderSelect (i- 1 , SELECT_BY_POS )== true ) // Если есть следующий
        {                                       // Анализ ордеров:
         if ( OrderSymbol ()!=Symb) continue ;       // Не наш фин. инструм
         if ( OrderType ()> 1 )                     // Попался отложенный
           {
             Alert ( "Обнаружен отложенный ордер. Эксперт не работает." );
             return ;                             // Выход из start()
           }
         Total++;                               // Счётчик рыночн. орд
         if (Total> 1 )                           // Не более одного орд
           {
             Alert ( "Несколько рыночных ордеров. Эксперт не работает." );
             return ;                             // Выход из start()
           }
         Ticket= OrderTicket ();                   // Номер выбранн. орд.
         Tip   = OrderType ();                     // Тип выбранного орд.
         Price = OrderOpenPrice ();               // Цена выбранн. орд.
         SL    = OrderStopLoss ();                 // SL выбранного орд.
         TP    = OrderTakeProfit ();               // TP выбранного орд.
         Lot   = OrderLots ();                     // Количество лотов
        }
     }
//--------------------------------------------------------------- 5 --
   // Торговые критерии
   UpLine = iCustom ( NULL , 0 , "i-DRProjections_vr1pv1z_0_1" ,NumberOfDay, 0 , 0 );
   DnLine = iCustom ( NULL , 0 , "i-DRProjections_vr1pv1z_0_1" ,NumberOfDay, 1 , 0 );


   if (DnLine >= Ask )                           // 
     {                                           // 
      Opn_B= true ;
     }
   if (UpLine <= Bid )                           // 
     {
      Cls_B= true ;                               // 
     }
   if (UpLine <= Bid )                           // 
     {                                           // 
      Opn_S= true ;                 
     }                                           // 
   if (DnLine >= Ask )   
     { 
      Cls_S= true ;                 
     }
//--------------------------------------------------------------- 6 --
   // Закрытие ордеров
   while ( true )                                   // Цикл закрытия орд.
     {
       if (Tip== 0 && Cls_B== true )                 // Открыт ордер Buy..
        {                                       //и есть критерий закр
         Alert ( "Попытка закрыть Buy " ,Ticket, ". Ожидание ответа.." );
         RefreshRates ();                         // Обновление данных
         Ans= OrderClose (Ticket,Lot, Bid , 2 );       // Закрытие Buy
         if (Ans== true )                         // Получилось :)
           {
             Alert ( "Закрыт ордер Buy " ,Ticket);
             break ;                               // Выход из цикла закр
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }

       if (Tip== 1 && Cls_S== true )                 // Открыт ордер Sell..
        {                                       // и есть критерий закр
         Alert ( "Попытка закрыть Sell " ,Ticket, ". Ожидание ответа.." );
         RefreshRates ();                         // Обновление данных
         Ans= OrderClose (Ticket,Lot, Ask , 2 );       // Закрытие Sell
         if (Ans== true )                         // Получилось :)
           {
             Alert ( "Закрыт ордер Sell " ,Ticket);
             break ;                               // Выход из цикла закр
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       break ;                                     // Выход из while
     }
//--------------------------------------------------------------- 7 --
   // Стоимость ордеров
   RefreshRates ();                               // Обновление данных
   Min_Lot= MarketInfo (Symb, MODE_MINLOT );         // Миним. колич. лотов 
   Free   = AccountFreeMargin ();                 // Свободн средства
   One_Lot= MarketInfo (Symb, MODE_MARGINREQUIRED ); // Стоимость 1 лота
   Step   = MarketInfo (Symb, MODE_LOTSTEP );       // Шаг изменен размера

   if (Lots > 0 )                                 // Если заданы лоты,то 
      Lts =Lots;                                 // с ними и работаем 
   else                                          // % свободных средств
      Lts= MathFloor (Free*Prots/One_Lot/Step)*Step; // Для открытия

   if (Lts < Min_Lot) Lts=Min_Lot;               // Не меньше минимальн
   if (Lts*One_Lot > Free)                       // Лот дороже свободн.
     {
       Alert ( " Не хватает денег на " , Lts, " лотов" );
       return ;                                   // Выход из start()
     }
//--------------------------------------------------------------- 8 --
   // Открытие ордеров
   while ( true )                                   // Цикл закрытия орд.
     {
       if (Total== 0 && Opn_B== true )               // Открытых орд. нет +
        {                                       // критерий откр. Buy
         RefreshRates ();                         // Обновление данных
         SL= Bid - New_Stop(StopLoss)* Point ;     // Вычисление SL откр.
         Alert ( "Попытка открыть Buy. Ожидание ответа.." );
         Ticket= OrderSend (Symb, OP_BUY ,Lts, Ask , 2 ,SL,Cls_B); //Открытие Buy
         if (Ticket > 0 )                         // Получилось :)
           {
             Alert ( "Открыт ордер Buy " ,Ticket);
             return ;                             // Выход из start()
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       if (Total== 0 && Opn_S== true )               // Открытых орд. нет +
        {                                       // критерий откр. Sell
         RefreshRates ();                         // Обновление данных
         SL= Ask + New_Stop(StopLoss)* Point ;     // Вычисление SL откр.
         Alert ( "Попытка открыть Sell. Ожидание ответа.." );
         Ticket= OrderSend (Symb, OP_SELL ,Lts, Bid , 2 ,SL,Cls_S); //Открытие Sel
         if (Ticket > 0 )                         // Получилось :)
           {
             Alert ( "Открыт ордер Sell " ,Ticket);
             return ;                             // Выход из start()
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       break ;                                     // Выход из while
     }
//--------------------------------------------------------------- 9 --
   return ;                                       // Выход из start()
  }
//-------------------------------------------------------------- 10 --
int Fun_Error( int Error)                         // Ф-ия обработ ошибок
  {
   switch (Error)
     {                                           // Преодолимые ошибки            
       case    4 : Alert ( "Торговый сервер занят. Пробуем ещё раз.." );
         Sleep ( 3000 );                           // Простое решение
         return ( 1 );                             // Выход из функции
       case 135 : Alert ( "Цена изменилась. Пробуем ещё раз.." );
         RefreshRates ();                         // Обновим данные
         return ( 1 );                             // Выход из функции
       case 136 : Alert ( "Нет цен. Ждём новый тик.." );
         while ( RefreshRates ()== false )           // До нового тика
             Sleep ( 1 );                           // Задержка в цикле
         return ( 1 );                             // Выход из функции
       case 137 : Alert ( "Брокер занят. Пробуем ещё раз.." );
         Sleep ( 3000 );                           // Простое решение
         return ( 1 );                             // Выход из функции
       case 146 : Alert ( "Подсистема торговли занята. Пробуем ещё.." );
         Sleep ( 500 );                             // Простое решение
         return ( 1 );                             // Выход из функции
         // Критические ошибки
       case    2 : Alert ( "Общая ошибка." );
         return ( 0 );                             // Выход из функции
       case    5 : Alert ( "Старая версия терминала." );
         bool Work= false ;                             // Больше не работать
         return ( 0 );                             // Выход из функции
       case 64 : Alert ( "Счет заблокирован." );
         Work= false ;                             // Больше не работать
         return ( 0 );                             // Выход из функции
       case 133 : Alert ( "Торговля запрещена." );
         return ( 0 );                             // Выход из функции
       case 134 : Alert ( "Недостаточно денег для совершения операции." );
         return ( 0 );                             // Выход из функции
       default : Alert ( "Возникла ошибка " ,Error); // Другие варианты   
         return ( 0 );                             // Выход из функции
     }
  }
//-------------------------------------------------------------- 11 --
int New_Stop( int Parametr)                       // Проверка стоп-прик.
  {
   int Min_Dist= MarketInfo (Symb, MODE_STOPLEVEL ); // Миним. дистанция
   if (Parametr<Min_Dist)                       // Если меньше допуст.
     {
      Parametr=Min_Dist;                         // Установим допуст.
       Alert ( "Увеличена дистанция стоп-приказа." );
     }
   return (Parametr);                             // Возврат значения
  }
//-------------------------------------------------------------- 12 --
 
Hi all. I have tested so many EAs in the tester, but I haven't encountered anything like this. I am testing an EA (in the tester) and the code does not contain no loss or trailing stop. However, when an order is opened and price moves in the required direction, it triggers a trailing stop (about 20 points) and starts trailing stop (with error 1). What is this nonsense, why and how to get rid of it?
 
Youri Lazurenko:
Hi all. I have tested so many EAs in the tester, but I haven't encountered anything like this. I am testing an EA (in the tester) and the code does not contain no loss or trailing stop. However, when an order is opened and price moves in the required direction, it triggers a trailing stop (about 20 points) and starts trailing stop (with error 1). What is this nonsense, why and how to get rid of it?

Contact the Expert Advisor or go to the club of telepaths. They will definitely help you.

 
Konstantin Nikitin:

Expert's code, or the telepath club. They'll definitely help.

Thank you. Oddly enough, your answer helped. It (answer) encouraged me to revise the code again and find the error (I probably would have missed it otherwise). Sometimes the desire to do as well as possible leads to the opposite result.

P.S. Yes, you're right, you can't answer my question without code. But since you have exhausted the question, I don't think it (the code) has any sense. Thanks again.

 

Hi all, could you tell me how to write the code correctly (types of variables)? Basically it works as it is, but in case of errors.

   int День_Года=TimeDayOfYear(Time[0]);
   int Рабочий_День_Года;
   double Количество_недель_дробь=День_Года/7;

The task is to calculate the number of the WORKING day of the year.

 

Greetings all !

Decided to run the old EA for the sake of experimentation, but at the time of compilation gives a bunch of errors (compile). I've been in a different build for a while now. Any suggestion on what the issue is and how to fix it.https://www.mql5.com/ru/code/9386

p.s. Maybe someone has a terminal of the old build... it would be more vague...
Нейросетевой советник
Нейросетевой советник
  • www.mql5.com
В корневом каталоге диска С: создайте папку с названием "ANN", в которой будут храниться настроенные нейросети. Для того, чтобы библиотека подключилась, также необходимо в терминале Меню "Сервис" > Вкладка "Советники" включить режим: "Разрешить импорт DLL" Оптимизацию необходимо проводить при включенном генетическом алгоритме. У советника...
Reason: