[ARCHIVE]Any rookie question, so as not to clutter up the forum. Professionals, don't pass it by. Can't go anywhere without you - 5. - page 335

 
borilunad:
Then do some digging in your own place! You have a function for every word of your code, and you have to make do with variables. That's what makes the code heavy. You should use functions when you can't do without them! I commented everything in Kim's code that I don't need, and it all works very fast! Remember, I asked everyone how to make the program run faster under many conditions. Now testing runs for a year on all ticks in 5 minutes! I combed through all the conditions and functions and threw out everything unnecessary.

Of course I remember. I'll keep it up for a while. In fact, I need to change my habits. It's not the first programmer to say that my code is not easy to understand. Apparently it is...
 
borilunad:
So dig in your own place! You have a function for every word of your code, and you have to make do with variables. That's why your code is heavy. You should use functions when you can't do without them! I commented everything in Kim's code that I don't need, and it all works very fast! Remember, I asked everyone how to make the program run faster under many conditions. Now testing runs for a year on all ticks in 5 minutes! I combed through all the conditions and functions and threw out everything unnecessary.

Variables can only be dispensed with if we test the strategy in the tester.

For the real, every necessary value to execute the logic must be calculated at the right moment in time, because the values of these variables are very easy to lose, for example during a restart.

 

Good day to you all.

I already figured out how to write indices, but I have problems with the first robot. It seems to be logical, the compiler does not complain, the journal has no errors, but the Expert Advisor in the tester does not work - the chart opens, but there is no movement on this graph (the chart does not move).

The idea is as follows: The indicator produces a point (always at the opening and the opening price of the candle) from which to buy or sell, the task of the robot at the same time, after receiving a point to buy or sell, close the opposite order, open a new or modify an old order in the same direction (stops and TP are issued by another indicator)

I would be very grateful to you for hints where it is wrong.

The code itself (changed indices names according to their functionality, removed declaration of variables and error handling section):

   // Предварит.обработка

   if(High[0]!=Low[0]) return; //если бар открылся до поступления текущей котировки, выход из start

       vverh = iCustom(NULL,0,"Индикатор дающий точку на покупку",Glubina,Pogreshnost,0,0);   //значение индикатора на покупку
       vniz  = iCustom(NULL,0,"Индикатор дающий точку на продажу",Glubina,Pogreshnost,1,0);   //значение индикатора на продажу
       
   if(vverh==0 && vniz==0)
     {
      Alert("Сигнала нет. Эксперт ждёт сигнал.");
      return;
     }
   if(Bars < Glubina)                       // Недостаточно баров
     {
      Alert("Недостаточно баров в окне. Эксперт не работает.");
      return;                                   // Выход из start()
     }
   if(Work==false)                              // Критическая ошибка
     {
      Alert("Критическая ошибка. Эксперт не работает.");
      return;                                   // Выход из start()
     }

//--------------------------------------------------------------- 4 --
   // Учёт ордеров
   Symb=Symbol();                               // Название фин.инстр.
   Total=0;                                     // Количество ордеров
   for(i=1; i<=OrdersTotal(); i++)              // Цикл перебора ордеров
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // Если есть следующий
        {                                       // Анализ ордеров:
         if (OrderSymbol()!=Symb)continue;      // Не наш фин. инструм
         if (OrderMagicNumber()!=MagicNumber)   // Попался ордер открытый не советником
            continue;
            
         Total++;                               // Счётчик ордеров открытых советником
         if (Total>1)                           // Не более одного орд
           {
            Alert("Несколько ордеров одного советника. Эксперт не работает.");
            return;                             // Выход из start()
           }
         Ticket=OrderTicket();                  // Номер выбранн. орд.
         Tip   =OrderType();                    // Тип выбранного орд.
         Price =OrderOpenPrice();               // Цена выбранн. орд.
         SL    =OrderStopLoss();                // SL выбранного орд.
         TP    =OrderTakeProfit();              // TP выбранного орд.
         Lot   =OrderLots();                    // Количество лотов
        }
     }
//--------------------------------------------------------------- 5 --
// торговые критерии
if(vverh>0)
  {
   Opn_B=true;
   Cls_S=true;
   Opn_S=false;
   Cls_B=false;
  }
if(vverh>0)
  {
   Opn_S=true;
   Cls_B=true;
   Opn_B=false;
   Cls_S=false;
  }
  
//--------------------------------------------------------------- 6 --
   
   //расчет стопов
   i_stop=0;
   while (stopov_for_S<2)                                                        //ищем 2 последних точки стопа в индикаторе, выбираем изз них самую дальнюю от текущей цены
         {
          for_S = iCustom(NULL,0,"Индюк дающий точки стопов",Glubina,0,i_stop);
          if (for_S>0)
             {
              stopov_for_S++;
              if(Stop_for_S<for_S) Stop_for_S=for_S;
             }
          i_stop++;
         }
   i_stop=0;
   while (stopov_for_B<2)
         {
          for_B = iCustom(NULL,0,"Индюк дающий точки стопов",Glubina,1,i_stop);
          if (for_B>0)
             {
              stopov_for_B++;
              if(Stop_for_B<for_B) Stop_for_B=for_B;
             }
          i_stop++;
         }
SL_for_B = Stop_for_B-pogreshnostSL;
SL_for_S = Stop_for_S+pogreshnostSL;
TP_for_B=vverh+(vverh-Stop_for_B)*koeff_dvizheniya;
TP_for_S=vniz-(Stop_for_S-vniz)*koeff_dvizheniya;


   // Закрытие и модификация ордеров
   while(true)                                  // Цикл закрытия и модификации орд.
     {
      if (Tip==0 && Opn_B==true)                // Если открыт ордер БАЙ и индикатор дает сигнал на покупку
             {
              OrderModify(Ticket,SL_for_B,TP_for_B,0,CLR_NONE); //меняем стопы текущего ордера бай
              break;
             }
      if (Tip==0 && Opn_S==true)                // Если открыт ордер БАЙ и индикатор дает сигнал на продажу
             {
              RefreshRates();
              Ans=OrderClose(Ticket,Lot,Bid,50);        // закрываем БАЙ
                 if (Ans==true)                         // Получилось :)
                    {
                     Alert ("Закрыт ордер Buy ",Ticket);
                     break;                             // Выход из цикла закр
                    }
                 if (Fun_Error(GetLastError())==1)      // Обработка ошибок
                     continue;                          // Повторная попытка
             }
      
      if (Tip==1 && Opn_S==true)
             {
              OrderModify(Ticket,SL_for_S,TP_for_S,0,CLR_NONE);
              break;
             }
      if (Tip==1 && Opn_B==true)
             {
              RefreshRates();
              Ans=OrderClose(Ticket,Lot,Ask,50);
                 if (Ans==true)                         // Получилось :)
                    {
                     Alert ("Закрыт ордер Sell ",Ticket);
                     break;                             // Выход из цикла закр
                    }
                 if (Fun_Error(GetLastError())==1)      // Обработка ошибок
                     continue;                          // Повторная попытка
             }
     }
//--------------------------------------------------------------- 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)                                  // Цикл закрытия орд.
     {
      Ticket=0;
      if (Opn_B==true)                          // Открытых орд. нет +
        {                                       // критерий откр. Buy
         RefreshRates();                        // Обновление данных
         Alert("Попытка открыть Buy. Ожидание ответа..");
         Ticket=OrderSend(Symb,OP_BUY,Lts,Ask,50,SL_for_B,TP_for_B,"My order #",MagicNumber,0,CLR_NONE);//Открытие Buy
         if (Ticket > 0)                        // Получилось :)
           {
            Alert ("Открыт ордер Buy ",Ticket);
            return;                            // Выход из start()
           }
         if (Fun_Error(GetLastError())==1)      // Обработка ошибок
            continue;                           // Повторная попытка
         return;                                // Выход из start()
        }
        
      if (Opn_S==true)                          // Открытых орд. нет +
        {                                       // критерий откр. Buy
         RefreshRates();                        // Обновление данных
         Alert("Попытка открыть Sell. Ожидание ответа..");
         Ticket=OrderSend(Symb,OP_SELL,Lts,Bid,50,SL_for_S,TP_for_S,"My order #",MagicNumber,0,CLR_NONE);//Открытие Sell
         if (Ticket > 0)                        // Получилось :)
           {
            Alert ("Открыт ордер Buy ",Ticket);
            return;                            // Выход из start()
           }
         if (Fun_Error(GetLastError())==1)      // Обработка ошибок
            continue;                           // Повторная попытка
         return;                                // Выход из start()
        }
     }
//--------------------------------------------------------------- 9 --
   return;                                      // Выход из start()
  }

 
If (торговые условия сигнал №1)
  {
  }//   Какой код нужен, чтобы тело оператора №1 в случае соответствия, передало управление к оператору  «торговых       условий №2»    

If (торговые условия сигнал №2)
  {
  }// Какой код нужен, чтобы тело оператора №2 в случае соответствия, передало управление к оператору «торговых       условий №3 и №4»    

If (торговые условия сигнал №3)
  {                                          
   Opn_B=true;                            
   }
   else
If (торговые условия сигнал №4)
  {                                          
   Opn_S=true;                            
   }
     else
         return(0);

The essence of the problem is as follows: it is not clear what to put in curly brackets in the body of operators #1,2 in fact there is checked compliance of trading conditions and no more actions.

(There are four trading signals, number 1 triggers, we pass control to processing signal number 2, number 2 triggers, we pass it to processing signals number 3 and 4 and perform trading operations there).

  else
         return(0);

Is it worth adding it to the end? Logically, if signals #3,4 do not trigger, then I need the Expert Advisor to start again.

 
artmedia70:

Variables can only be used when testing the strategy in the tester.

For the real world, every value needed to execute the logic must be calculated at the right time, because the values of these variables are very easy to lose, for example during a restart.

But do the variables written in the extern get lost? It has never happened! But all conditions are in front of my eyes and at hand in start(), and functions, which are outside start(), have checks and final non-changeable actions! I may be wrong by and large, but so far I'm comfortable this way, and I haven't received a single error or rakeback on Real yet! I always read your posts carefully, Artem, and other experienced programmers like alsu, Meat and others, as well as guest moderators! But not everything is still within my capabilities, so I can't apply what is not yet clear to me to the smallest detail. thanks for everything!
 
barma:

Good day to you all.

I already figured out how to write indices, but I have problems with the first robot. It seems to be logical, the compiler does not complain, the journal has no errors, but the Expert Advisor in the tester does not work - the chart opens, but there is no movement on this graph (the chart does not move).

The idea is as follows: The indicator produces a point (always at the opening and the opening price of the candle) from which to buy or sell, the task of the robot at the same time, after receiving a point to buy or sell, close the opposite order, open a new or modify an old order in the same direction (stops and TP are issued by another indicator)

I would be very grateful to you for hints where it is wrong.

The code itself (changed indices names according to their functionality, removed declaration of variables and error handling section):

If you have replaced the names of the indicators only in the EA, and not also in the indicator codes themselves, which are displayed in the corresponding windows on the charts, then the EA will not receive anything from them, and the error is not given, because everything is presented in the EA, but it does not receive signals from the indicators. Check if the names of the indicators are spelled the same way!
 
borilunad:
If you have changed the names of the indicators only in the EA, and not in the codes of indicators themselves, which are displayed in the corresponding windows on the charts, then the EA will not receive anything from them and will not give an error, because everything is presented in the EA, but it does not receive signals from indicators. Check if the names of the indicators are spelled the same way!

Thanks for the tip, I have checked everything once again, there are no mistakes in the writing. I have only changed the names of indicators in the text of the first message on the forum, in order to make their task clear, in the text of the Expert Advisor the names of indices are written exactly as they are named in the folder "indicators". For example: "3.0_figuri_2.3_rasshirenie".

In addition, I have selected another EA (from the tutorial) and entered the names of non-existing indicators in the iCustom function. What happened was the following - the EA really stopped trading (which is, by the way, understandable), but when I start the tester, the chart was moving from the set start date to the set end date, I should remind you that my problem is that the chart is not moving.

Maybe someone else has faced this problem?

 
barma:

Thanks for the tip, I have checked everything once again, there are no mistakes in the writing. I have only changed the names of indicators in the text of the first message on the forum, in order to make their task clear, in the text of the Expert Advisor the names of indices are written exactly as they are named in the folder "indicators". For example: "3.0_figuri_2.3_rasshirenie".

In addition, I have selected another EA (from the tutorial) and entered the names of non-existing indicators in the iCustom function. What happened was the following - the EA really stopped trading (which is, by the way, understandable), but when I start the tester, the chart was moving from the set start date to the set end date, I should remind you that the problem is that the chart is not moving.

Maybe someone else had such a problem.

Check the name of the indicator, not in the folder, but in its code: "short name", because by it the Expert Advisor recognizes it, if it is still installed on the appropriate chart and the TF!
 
For the indicator to draw something in the tester, it must be installed on the chart, the EA itself will not draw lines.
 
barma:

Thanks for the tip, I have checked everything once again, there are no mistakes in the writing. I have only changed the names of indicators in the text of the first message on the forum, in order to make their task clear, in the text of the Expert Advisor the names of indices are written exactly as they are named in the folder "indicators". For example: "3.0_figuri_2.3_rasshirenie".

In addition, I have selected another EA (from the tutorial) and entered the names of non-existing indicators in the iCustom function. What happened was the following - the EA really stopped trading (which is, by the way, understandable), but when I start the tester, the chart was moving from the set start date to the set end date, I should remind that the problem is that the chart is not moving.

Maybe someone else had such a problem?

Weekend at the offices, so the graph does not move.