[WARNING CLOSED!] Any newbie question, so as not to clutter up the forum. Professionals, don't go by. Can't go anywhere without you. - page 832

 
Vinin:

What's going to change next time?
The same thing. A position is closed - a pending order is set, etc. There is a function that returns the last value (e.g. OrderCloseTime()). With every tick, I get the time value of the last closed position (say, position #1). When closing the next position (position #2) with a new tick I get the time to close this (#2) position. The OrderCloseTime() value has changed relative to the previous one. And so on. I don't care how or how much the variable has changed. What matters to me is the very fact that the variable has changed. It's like a logical operation: If the OrderCloseTime() of the last closed position is greater than the OrderCloseTime() of the penultimate one, then we should do BLA-BLA-BLA. Also - if the OrderClosePrice() of the last closed position is not equal to the OrderClosePrice() of the penultimate one, then make a BLA-BLA-BLA. Or maybe it is not possible to make such a comparison?
 
Here is the question. Suppose, for example, our EA shows a buy signal when the indicator (for example, I took CCI) crosses some level (the red line) from bottom to top, and a sell signal when it, respectively, goes down. How should we make the order open only once during the formation of the bar A? Suppose the indicator crosses the level (the red line) downwards and upwards several times during the formation of bar A. As I have already mentioned, we should make it so that an order is opened only once.

What we need is for the sell signal to be received on bar D (situation 2 on the chart) to not close the order opened on bar A , and not to be affected in any way.

I.e., the orders are not controlled by the Expert Advisor after they are opened.


Thank you in advance.

 

Please help me attach a piece of Sequent Demarque code to the EA https://www.mql5.com/ru/code/7372

does not work like this:

num=0:

for(i=bars; i>=0; i--)
{
if ((iClose(NULL,PERIOD_M5,i+1)<iClose(NULL,PERIOD_M5,i+4) && num!=0 )) {
num++;


if ((iClose(NULL,PERIOD_M5,i+1)<iClose(NULL,PERIOD_M5,i+4))
buy.......

if (num==9)
close........

 
Vinin:


1. Count the number of orders of the first type

2. Count the number of type 2 orders

3. Compare the results


Dear Vinin. Thank you very much!
 
Forrim:
Here is the question. Let us assume that the buy signal in the EA will be displayed when the indicator (for example, I took CCI) crosses some level (red line) from bottom to top and the sell signal, respectively, when it is from top to bottom. How should we make the order open only once during the formation of the bar A? Suppose the indicator crosses the level (the red line) downwards and upwards several times during the formation of bar A. As I have already mentioned, we should make it so that an order is opened only once.

This requires that at a sell signal to be received on bar D (situation 2 on the chart) the order opened on bar A should not be closed and should not be affected in any way.

That is, the orders are not controlled by the EA after they are opened.


Many thanks in advance.

Actually, the CCI jumps so wildly that we'd better check it after the bar has closed and a new one has been opened.

If we want to check if the opening time of a candle is different (if it is, the order opens) or is the same (=> no order opens), then at each crossing we should store the opening time in the global variable.

 
Forrim:
Here is the question. Suppose, for example, our EA shows a buy signal when the indicator (for example, I took CCI) crosses some level (the red line) from bottom to top, and a sell signal when it, respectively, goes down. How should we make the order open only once during the formation of the bar A? Suppose the indicator crosses the level (the red line) downwards and upwards several times during the formation of bar A. As I have already mentioned, we should make it so that the order is opened only once.

What we need is for the sell signal to be received on bar D (situation 2 on the chart) to not close the order opened on bar A , and not to be affected in any way.

I.e., the orders are not controlled by the Expert Advisor after they are opened.


Thank you in advance.

If a position of this type is already open, do not open any more.
 
//--------------------------------------------------------------- 1 --
                                   // Численные значения для М15
extern double StopLoss   =20;      // SL для открываемого ордера
extern double TakeProfit =20;      // ТР для открываемого ордера
extern double Step_Sar=0.02;       // Шаг Sar
extern double Maximum_Sar=0.2;     // Максимум Sar
extern double Lot=0.01;            // Жестко заданное колич. лотов
bool Work=true;                    // Эксперт будет работать.
//--------------------------------------------------------------- 2 --
int start()
  { 
   int   
   Total,                           // Количество ордеров в окне 

   Ticket;                          // Номер ордера
   
   double
   Sar_1 ,                          // Значен. Sar текущее
   Sar_0 ,                          // Значение Sar предыдущей свечки      
   Price,                           // Цена ордера
   SL,                              // SL ордера 
   TP;                              // TP ордера
   
   bool
   Ans  =false,                     // Ответ сервера после закрытия
   Cls_B=false,                     // Критерий для закрытия  Buy
   Cls_S=false,                     // Критерий для закрытия  Sell
   Opn_B=false,                     // Критерий для открытия  Buy
   Opn_S=false;                     // Критерий для открытия  Sell
   
//--------------------------------------------------------------- 3 --   
   // Учёт ордеров   

   Total=0;                                     // Количество ордеров
   for(int i=1; i<=OrdersTotal(); i++)          // Цикл перебора ордер
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // Если есть следующий
        {                                       // Анализ ордеров:
         if (OrderSymbol()!=Symbol())continue;      // Не наш фин. инструм
         if (OrderType()>1)                     // Попался отложенный
           {
            Alert("Обнаружен отложенный ордер. Эксперт не работает.");
            return;                             // Выход из start()
           }
         Total++;                               // Счётчик рыночн. орд
         if (Total>1)                           // Не более одного орд
           {
            Alert("Несколько рыночных ордеров. Эксперт не работает.");
            return;                             // Выход из start()
           }

   
     
       
        
    
         
         Price =OrderOpenPrice();               // Цена выбранн. орд.
         SL    =OrderStopLoss();                // SL выбранного орд.
         TP    =OrderTakeProfit();              // TP выбранного орд.
         Lot   =OrderLots();                    // Количество лотов
         }
         }
   
//--------------------------------------------------------------- 6 --
   // Торговые критерии
   Sar_1=iSAR(NULL, 0, 0.02, 0.2, 1);           // Sar_1
   Sar_0=iSAR(NULL, 0, 0.02, 0.2, 0);           // Sar_0
 
   if (Sar_0 > Price && Sar_1 < Price)          // если Sar меняет положение
     {
      Opn_B=true;                               // Критерий откр. Buy             
     }  
   if (Sar_0 < Price && Sar_1 > Price)          // если Sar меняет положение
     {                                          
      Opn_S=true;                               // Критерий откр. Sell                                   
     }   
//--------------------------------------------------------------- 7 --
  
     {
      if (Opn_B==true)         
        {                                       // критерий откр. Buy
         RefreshRates();                        // Обновление данных
         SL=(20+Ask-Bid)*Bid;                 // Вычисление SL откр.
         TP=20*Bid;                           // Вычисление TP откр.
         Alert("Попытка открыть Buy. Ожидание ответа..");
         Ticket=OrderSend(Symbol(),OP_BUY,Lot,Ask,0,SL,TP);//Открытие Buy                         
        }
        if (Fun_Error(GetLastError())==1)      // Обработка ошибок
                                   
         return;                                // Выход из start()
        
        
      if (Opn_S==true)                          // критерий откр. Sell
      
        {                                       // критерий откр. Sell
         RefreshRates();                        // Обновление данных
         SL=(20+Ask-Bid)*Ask;                 // Вычисление SL откр.
         TP=20*Ask;                           // Вычисление TP откр.
         Alert("Попытка открыть Sell. Ожидание ответа..");
         Ticket=OrderSend(Symbol(),OP_SELL,Lot,Bid,0,SL,TP);//Открытие Sel
         
         return;                                // Выход из start()
        }
        
      if (Fun_Error(GetLastError())==1)      // Обработка ошибок
                      
         return;                                // Выход из start()
        
     }
//--------------------------------------------------------------- 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("Старая версия терминала.");
         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 --

Elementary EA, should open a position when Parabolic SAR indicator changes relative to price chart, works on M15, SL and TP are always constant for opened position.

The EA compares indicator positions of the current and previous candlesticks.

There are no errors or bugs during compilation, in the test in the tab "results" "chart" "report" is empty, in the log is this: "picture".

I am coding for the second day, i have never coded before, i read my mql books and searched the internet for my problem. I am at a deadlock, please help if you can.


 

T.H.C. try this




Files:
0000001_1.mq4  3 kb
 
Techno:

T.H.C. Try this.




Thank you so much, I didn't expect such a quick response and such a change in the code.

Please advise on programming books other than basic mql

 
T.H.C.:

Thank you very much, I did not expect such speed and changes in the code.

Please advise more books on programming, besides basic mql.

I've only read the base one, you need more practice to get a good grasp of the subject.
Reason: