Questions from Beginners MQL5 MT5 MetaTrader 5 - page 832

 
void OnTick()
  {
 TimeCurrent(dt); 
//--- Достаточно ли количество баров для работы
   if(Bars(_Symbol,_Period)<10) // общее количество баров на графике меньше 10?
     {
      Alert("На графике меньше 10 баров, советник не будет работать!!");
      return;
     }
//--- сначала нужно записать в массивы значения буферов индиктора Fractal
//--- заполнение данными буфера

   ArraySetAsSeries(Signal,true);
   ArraySetAsSeries(Main,true);

   
   if(CopyBuffer(Stochastic_handle,0,0,100,Main)<=0) return;
   if(CopyBuffer(Stochastic_handle,1,0,100,Signal)<=0) return;

   double Main_1=Main[1];
   Main_1=NormalizeDouble(Main_1,5);
   Print("Main_1=",DoubleToString(Main_1,5));
    
   double Main_2=Main[2];
   Main_2=NormalizeDouble(Main_2,5);
   
   double Main_3=Main[3];
   Main_3=NormalizeDouble(Main_3,5);
   
   double Signal_1=Signal[1];
   Signal_1=NormalizeDouble(Signal_1,5);
   Print("Signal_1=",DoubleToString(Signal_1,5));
   
   double Signal_2=Signal[2];
   Signal_2=NormalizeDouble(Signal_2,5);
   
   double Signal_3=Signal[3];
   Signal_3=NormalizeDouble(Signal_3,5);
   
   
// Для сохранения значения времени бара мы используем static-переменную Old_Time.
// При каждом выполнении функции OnTick мы будем сравнивать время текущего бара с сохраненным временем.
// Если они не равны, это означает, что начал строится новый бар.

   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;

// копируем время текущего бара в элемент New_Time[0]
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) // ok, успешно скопировано
     {
      if(Old_Time!=New_Time[0]) // если старое время не равно
        {
         IsNewBar=true;   // новый бар
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("Новый бар",New_Time[0],"старый бар",Old_Time);
         Old_Time=New_Time[0];   // сохраняем время бара
        }
     }
   else
     {
      Alert("Ошибка копирования времени, номер ошибки =",GetLastError());
      ResetLastError();
      return;
     }
     
     
// открытие покупок

     if(Main_1>Signal_1&&Main_2<Signal_2&&Main_3<Signal_3&&Main_2<20)
     {
      if(IsNewBar!=false)
        {
           
              {
               open_by_market();

              }
        }
     }
  

  // закрытие покупок 
 
   if (Signal_3>80&&Signal_2>80&&Signal_1<80)
   {
   if(PositionsTotal()>0)
        {
         for(int i=0;i<PositionsTotal();i++)
           {
            ulong orders_ticket=PositionGetTicket(i);
            if(((PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY) ))
              
              
              {  trade.PositionClose(orders_ticket); }        
            
         }
     }           
   }
 
}
   

Good day. Please clarify how to implement two tasks (using buy signals as an example).

given: entry point - stochastic line crossing below 20

trade close - crossing of 80 level downward through the slow stochastic line

i.e. do not open several positions on the same level like on the picture attached

2. to close at the second, not at the first crossing of level 80 from top to bottom with a slow stochastic line

Совершение сделок - Торговые операции - MetaTrader 5
Совершение сделок - Торговые операции - MetaTrader 5
  • www.metatrader5.com
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
Files:
121.png  27 kb
 
gastinets:

Good day. Please clarify how to implement two tasks (using buy signals as an example).

given: entry point - stochastic line crossing below 20

trade close - crossing of 80 level downward through the slow stochastic line

i.e. do not open several positions on the same level like on the picture attached

2) The second order would be closed at the second, not the first, crossing of level 80 downwards through the slow stochastic line

First formulate it clearly:

  • condition of position opening
  • close condition

 
Please advise how to access position information in the OnTick function of the constructed Expert Advisor. At least whether it is open or not. Where can I get a pointer to the position? Or it needs to be done in some other way?
 
VHS:
Please advise how to access position information in the OnTick function of a constructed Expert Advisor. At least, if it is open or not. Where can I get a pointer to the position? Or it needs to be done in some other way?

The Expert Advisor is designed by whom?

Please show me the code.
 
Comments not related to this topic have been moved to "Questions from MQL4 MT4 MetaTrader 4 beginners".
 
Vladimir Karputov:

The expert is designed by whom?

Show the code, please.
The Expert Advisor is designed by Wizard using a custom signal class and a custom trading class. The code of the Expert Advisor itself is standard. ExtExpert.OnTick() is called in OnTick, the rest of the code is built using the standard library. Actually this question is a follow-up to the previous one, to which no one has responded. I want the Expert Advisor designed by Wizard to use the custom signals class only for opening positions and close them only when trading and ignoring signals from the signal class. I figured out how to ignore signals. But how to get information in onTick about whether there is an open position to enable ignoring, I do not understand.
 
VHS:
***And I've only ever closed by trading ***

It's not clear.

 

VHS:
***а закрывал уже только по трейдингу ***

Vladimir Karputov:

It is not clear.

"D" and "L" next to each other on the keyboard. My mistake.

 
Artyom Trishkin:

"D" and "L" next to each other on the keyboard. Wrong.

Yes, Artyom, thank you very much. Apparently auto-replacement (or crooked hands). And the custom class and closure are not trayDing, but trayLing.
In the CExpert class, the Processing method goes into Direction first and checks for a signal from the signal class. And then (only if there is a SelectPosition) it checks Trailing. As a result, if there is an open position, it will sometimes close in the absence of signals from the Trailing Class, getting a signal from the signals class.
The previous variant - to take information about the presence of an open position from the Trailing Stop class and pass it to Ignore via OnTick - didn't work. I have learned how to memorize in OnInit the trailing object and to transfer from it to OnTick. But it works only while the position is open. But after it is closed, processing doesn't start trailing and Ignore remains ignored. So there is only one final touch: after closing the position, define this moment in OnTick and return Ignore value "0". But how to effectively get information about (presence/absence of) a position in OnTick I don't understand.
 
VHS:
Yes, Artem, thank you very much. Apparently auto-change (or crooked hands). And the custom class and close is not trayDing, it's trayLing.
In the CExpert class, the Processing method goes into Direction first and checks for a signal from the signal class. And then (only if there is a SelectPosition) it checks Trailing. As a result, if there is an open position, it will sometimes close in the absence of signals from the Trailing Class, getting a signal from the signals class.
The previous variant - to take information about the presence of an open position from the Trailing Stop class and pass it to Ignore via OnTick - didn't work. I have learned how to memorize in OnInit the trailing object and to transfer from it to OnTick. But it works only while the position is open. But after it is closed, processing doesn't start trailing and Ignore remains ignored. So there is only one final touch: after closing the position, define this moment in OnTick and return Ignore value "0". But how to effectively get information about (presence/absence of) a position in OnTick I don't understand.

I think you can make it much easier - in your EA set the CLOSE threshold to 100, and give 0.5 weight to the signal - thus a signal with a weight of 0.5 will NEVER go past the 100 threshold