Questions from Beginners MQL4 MT4 MetaTrader 4 - page 114

 
Rewerpool:
Good afternoon ! How can I create a trigger ? For example I need this condition if(iClose(NULL,HTF,4)<BlueLine) if it is executed DayDown = 1 ! Q: How can DayDown be left as 1 and not polled until the next day ?
int ДеньОпроса=0;
void OnTick()
{
  if(ДеньОпроса != Day())  // Если новый день - нужно опросить
  {
     if(iClose(NULL,HTF,4)<BlueLine) DayDown = 1;  // Опрос
     ДеньОпроса = Day();   // Запомнить день
  }
 
Thank you! I'll try to screw it on)
 
Hello, please write code on the condition that if you delete 1 object from the chart, then the rest (a choice) will be deleted

I have other objects attached to 1 object, and when you delete this object, the rest just hang on the chart
 
STARIJ:

I've got it like this:

if(DayNext!= Day()) // If a new day, you have to poll

{

// Polling

if(iClose(NULL,1440,2)<BlueLine)

if(iOpen(NULL,1440,1)<BlueLine && iClose(NULL,HTF,1)>BlueLine)

PROBOI1 = 1;Print("Closed above BlueLine = ",iClose(NULL,HTF,1));

if(iClose(NULL,1440,2)>RedLine)

if(iOpen(NULL,1440,1)>RedLine && iClose(NULL,HTF,1)<RedLine)

PROBOI1 = -1;Print("Closed below RedLine = ",iClose(NULL,HTF,1));

DayNext = Day(); // Remember the day

}

Correct if something is wrong! Further, if I want to track what's happening now on a lower TF do I need to write Day outside the Survey? Right -STARIJ:

if(iClose(NULL,60,1)>RedLine&&iClose(NULL,1440,2)>RedLine) ) Sell = 1

 
Sorry for doing this, but please reply:
https://www.mql5.com/ru/forum/226620#comment_6481536
 
Vladimir Karputov:

Set magic number +1 for condition 1, magic number +2 for condition 2 and so on. That way you can then see if this position has been opened with condition 1 or with condition 2...

Afternoon. I have only succeeded for one position BAY. The magik set for sell does not work for some reason. Everything is absolutely identical, except for the magik itself of course. What have I done wrong?

int total=OrdersTotal();

      for(int i=OrdersTotal()-1;i>=0;i--)

      {

        if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

         {

         if(TimeCurrent()>OrderOpenTime()+100 && OrderTicket() && OrderType()==OP_BUY && (MathAbs(WPR1)<5))

         rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow); 

        

         if(TimeCurrent()>OrderOpenTime()+100 && OrderTicket() && OrderType()==OP_BUY && OrderMagicNumber==111 && MathAbs(WPR1)<20)

         rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow);

      

         if(TimeCurrent()>OrderOpenTime()+100 && OrderTicket() && OrderType()==OP_SELL && OrderMagicNumber==222 && MathAbs(WPR1)>97.55)

         rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow); 

           

         if(TimeCurrent()>OrderOpenTime()+100 && OrderTicket() && OrderType()==OP_SELL && MathAbs(WPR1)>96)

         rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow);               

         }

       continue;  

      }  
 
novichok2018:

What have I done wrong?

I apologize for not finding the beginning of the correspondence, but I would like to immediately advise you to avoid complex conditions and calculations in them - this makes the code unreadable and therefore complicates the search for logical errors, I would write your code like this:

int total=OrdersTotal();

  for(int i=OrdersTotal()-1;i>=0;i--)

      {

        if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

         {

            if(TimeCurrent()>OrderOpenTime()+100)&& OrderTicket())

            {   

         if(OrderType()==OP_BUY && (MathAbs(WPR1)<5))

            rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow); 

         if(OrderType()==OP_BUY && OrderMagicNumber==111 && MathAbs(WPR1)<20)

            rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow);

         if(OrderType()==OP_SELL && OrderMagicNumber==222 && MathAbs(WPR1)>97.55)

            rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow); 

         if(OrderType()==OP_SELL && MathAbs(WPR1)>96)

            rez =  OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),int(MarketInfo(OrderSymbol(),MODE_DIGITS))),slippage,Yellow);

            }

         }

       continue;  

      }

If you understand what I mean, you can modify the code I gave you a little more, I mean to put it in a separate conditionif(OrderType()==OP_BUY....

Then it will be much easier to find logical errors, imho

 
Igor Makanu:

I apologize for not finding the beginning of the correspondence, but I would like to immediately advise to avoid complex conditions and calculations in them - this makes the code unreadable and as a consequence complicates the search for logical errors, I would write your code like this:

If you understand what I mean, you can modify the code I gave you a little more, I mean to put it in a separate conditionif(OrderType()==OP_BUY....

Then it will be much easier to find logical errors, imho

Understood, thanks, but as far as I understand there is no difference for understanding of the code by the platform, while for me, breaking one condition into several shorter ones seems to be more complicated in searching for errors because the number of occurrences of statements inside each other increases. But maybe you're right and I'll come over to your side soon. Regarding code logic - I haven't found any difference between mine and yours and still don't see the error.

 
novichok2018:

Regarding code logic - I found no difference between mine and yours and I still don't see the error.

Exactly so - the logic of the code is the same, but if you split the conditions, it is faster to find where the logical error is, and in your case, if you take it out:

if(TimeCurrent()>OrderOpenTime()+100)&& OrderTicket())

into a separate condition, we get code optimization - the condition will be checked once instead of 4 times like in your example.

Check the output in the Expert Advisor's journal using the

Print()

for logging to see which code fragment is executed and with what parameters

 

Guys,

How do I read the Morning Flat indicator in the Expert Advisor code?

I'm trying it this way and it doesn't work.

min=iCustom(Symbol(),0,"Morning Flat",StartHour,EndHour,TargetLevel,1,0);

The indicator itself

//+------------------------------------------------------------------+
//| MorningFlat.mq4 |
//| Scriptong |
//| |
//+------------------------------------------------------------------+
#property copyright "Scriptong"
#property link ""

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Turquoise
#property indicator_color2 Red
#property indicator_color3 Gold
#property indicator_color4 Silver

extern int StartHour=0;
extern int EndHour=8;
extern double TargetLevel=161.8;
extern color UpColor = Turquoise;
extern color DnColor = Red;
extern color TargetUpColor = Gold;
extern color TargetDnColor = Silver;

//---- buffers
double Up[];
double Down[];
double TargetUp[];
double TargetDn[];
bool Activate=False;
datetime LastDay;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
   if(Period()>PERIOD_H1)
     {
      Comment("Индикатор работает на таймфреймах меньше H4!");
      return(0);
     }
   if(StartHour<0 || EndHour<0 || StartHour>23 || EndHour>23 || StartHour>=EndHour)
     {
      Comment("Значения StartHour и EndHour должны лежать в диапазоне от 0 до 24 и StartHour < EndHour.");
      return(0);
     }

   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,Up);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(1,Down);
   SetIndexStyle(2,DRAW_LINE);
   SetIndexBuffer(2,TargetUp);
   SetIndexStyle(3,DRAW_LINE);
   SetIndexBuffer(3,TargetDn);
   SetIndexEmptyValue(0, 0.0);
   SetIndexEmptyValue(1, 0.0);
   SetIndexEmptyValue(2, 0.0);
   SetIndexEmptyValue(3, 0.0);

   Activate=True;
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
  {
//----
// Удаление объектов-ценовых меток
   for(int i=ObjectsTotal()-1; i>=0; i--)
     {
      string Name=ObjectName(i);
      if(StringSubstr(Name,0,3)=="Lab")
         ObjectDelete(Name);
     }
   Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Ценовая метка со значением уровня |
//+------------------------------------------------------------------+
void DrawLabel(datetime TimeL,double Price,bool Upper,color Col,int Code)
  {
   if(Upper)
      string Name="Lab"+DoubleToStr(TimeL,0)+"U";
   else
      Name="Lab"+DoubleToStr(TimeL,0)+"D";

   if(ObjectCreate(Name,OBJ_ARROW,0,TimeL,Price))
     {
      ObjectSet(Name,OBJPROP_ARROWCODE,Code);
      ObjectSet(Name,OBJPROP_COLOR,Col);
     }
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
  {
//----
   if(!Activate) return(0);

   LastDay=0;
   int counted_bars=IndicatorCounted();
   if(counted_bars>0) counted_bars--;
   int limit=Bars-counted_bars;
   for(int i=limit; i>=0; i--)
      if(TimeHour(Time[i])>=EndHour)
        {
         datetime BeginDay=iTime(Symbol(),PERIOD_D1,iBarShift(Symbol(),PERIOD_D1,Time[i])); // Расчет времени начала суток
         datetime NextDay=BeginDay+86400; // Расчет времени начала следующих суток
         if(LastDay>= BeginDay) continue; // Если в этот день уже рисовали уровни, то продолжаем основной цикл
         int StartBar=iBarShift(Symbol(),0,BeginDay+StartHour*3600); // Бар, соответсвующий началу суток плюс смещение в часах
         int FinishBar=iBarShift(Symbol(),0,BeginDay+(EndHour-1)*3600); // Бар, соответствующий последнему бару "утреннего флэта"
         double LowV=Low[iLowest(Symbol(),0,MODE_LOW,StartBar-FinishBar+1,FinishBar)]; // Нижняя граница
         double HighV=High[iHighest(Symbol(),0,MODE_HIGH,StartBar-FinishBar+1,FinishBar)]; // Верхняя граница
         double TargetU = (HighV-LowV)*(TargetLevel-100)/100+HighV;
         double TargetD = LowV-(HighV-LowV)*(TargetLevel-100)/100;
         // Канал "утреннего флэта"
         for(int j=StartBar; j>=FinishBar; j--)
           {
            Up[j]=HighV;
            Down[j]=LowV;
            //Есть такой индикатор
            // -----------------------
            // Ожидаемые цели при пробое флэта 
            for(j=FinishBar; Time[j]<NextDay && j>=0; j--)
              {
               TargetUp[j] = TargetU;
               TargetDn[j] = TargetD;
              }
            // ------------------- 

            DrawLabel(Time[iBarShift(Symbol(), 0, BeginDay)], HighV, True, UpColor, 5); // Рисуем верхнюю ценовую метку канала
            DrawLabel(Time[iBarShift(Symbol(), 0, BeginDay)], LowV, False, DnColor, 5); // Рисуем нижнюю ценовую метку канала
            DrawLabel(Time[FinishBar],TargetU,True,TargetUpColor,5); // Рисуем верхнюю ценовую метку цели
            DrawLabel(Time[FinishBar],TargetD,False,TargetDnColor,5); // Рисуем нижнюю ценовую метку цели
            LastDay=BeginDay; // Отмечаем, что в этот день уровни уже были нарисованы
           }
        }
   WindowRedraw();
//----
   return(0);
  }
//+------------------------------------------------------------------+