Questions from Beginners MQL4 MT4 MetaTrader 4 - page 214

 
Aleksandr Martynov:

UPS, I think I've found it:

According to the documentation:

If a custom indicator is called using theiCustom() function, this indicator runs in the thread of the calling program. The library (imported) functions also work in the thread of the calling program.

Generally speaking, for MQL4 it doesn't matter where you place calculations, because resources will be allocated for the single thread of the program and indicators used by it.

In this case, it is advisable, if possible, to transfer the code of the indicator to the Expert Advisor and optimize the number of calculated values by the array depth and the number of "buffers", though it doesn't concern the recursive algorithms - it's still easier to read them in the indicator, because the program has automatically indexed buffers for the price data only ...

The issue is in the convenience of reading and editing the code, and so mt4 is single-threaded in one window. It is easier for me to take the calculation part of an indicator into an Expert Advisor. But it is not always good. The code turns out long, while inludes or iQuest is the same. If you want to speed up, then mt5. mt4 is not fast enough, judging by forum participants.

 
Valeriy Yastremskiy:

The question is how easy it is to read and edit the code, and as it is, mt4 is single-threaded in one window. I find it easier to get the calculation part of an indicator into an EA. But it is not always good. The code turns out long, while inludes or iQuest is the same. If you want to speed up, go to mt5. mt4 is slower, judging by forum comments.

If you want to speed up, then it's mt5, but mt4 loses out, judging by forum comments. So simple formulas like averaging, zigzag, and not any kind. 5 is good, of course, but not everyone is providing it yet and you have to learn it

 
Aleksandr Martynov:

managing the calculation buffers in the EA will be more expensive than the indicator... So simple formulas like averaging, zigzag and not all of them. 5 is good, of course, but not everyone has access to it.

But to do it you need to take away the code of indicator logic, which is not always easy.

 
How safe is it to give the EA and terminal logs to a developer at his request? Can he do anything to my account or computer?

 
Alexander Kovalev:
How safe is it to give the EA and terminal logs to the developer at his request? Can he do anything to my account or computer?

Yes, and also take all the gold jewellery out of the house from the casket

 

My friends, please advise me where I am going wrong (please don't kill me, I've been working in MQL4 for 3 days).


I am trying to open an SELL order from the market at a price indented Delta points (60) from the previously placed value (which I take when opening a previous order).

However, the script opens a new order at the same time as the previous order, at the current price, without waiting for the appropriate condition (a 60 point price drop). I know I have made it somewhere, but I still don't understand where it is.

I would be very grateful!


A strange discovery

 

Help me out!!!

I can't figure out where my problem is. The EA requires EMA volumes. I used iMAonArray.

But the calculation is not similar to the real one.

Here is the code:

***

Files:
 
Aleksandr Martynov:
Good question, I have a car and something rattles in it, which bolt to tighten? Do you have any idea how much advice is possible and in the end they are all useless because you have to tighten the nut...
There's only a code in the studio and no other way.

Look at the reason why it doesn't open for gold ?

***

Документация по MQL5: Дата и время / TimeCurrent
Документация по MQL5: Дата и время / TimeCurrent
  • www.mql5.com
Возвращает последнее известное время сервера, время прихода последней котировки по одному из выбранных в "Обзоре рынка" символов. В обработчике OnTick() данная функция вернет время пришедшего обрабатываемого тика. В других случаях (например, вызов в обработчиках OnInit(), OnDeinit(), OnTimer() и так далее) это –...
 
Наджибулло Хабибов:

Look at the reason why it doesn't open on gold ?

***

Insert the codecorrectly: use the Code button or alternatively: attach the file using the Attach file
MQL5.community - Памятка пользователя
MQL5.community - Памятка пользователя
  • www.mql5.com
Теперь вы можете не только читать статьи и скачивать программы на языке MQL5, но и участвовать в обсуждении интересующих вас тем на Форуме, оставлять комментарии к статьям и опубликованным кодам. Кроме того, вы можете не только выкладывать собственные разработки в Code Base, но и публиковать Статьи, за которые мы предлагаем вознаграждение...
 
Наджибулло Хабибов:

Look at the reason why it doesn't open on gold ?

***

//--- Inputs
extern double Lots       = 0.1;      // лот
extern double KLot       = 1;        // умножение лота
extern double MaxLot     = 5;        // максимальный лот
extern double Profit     = 0;        // Профит в валюте
extern int StopLoss      = 0;        // Стоп Лось
extern int TakeProfit    = 0;        // ТейкПрофит
extern int BULevel       = 0;        // уровень БУ
extern int BUPoint       = 30;       // пункты БУ
extern int TrailingStop  = 0;        // трал
extern int StartHour     = 0;        // час начала торговли
extern int StartMin      = 30;       // минута начала торговли
extern int EndHour       = 23;       // час окончания торговли
extern int EndMin        = 30;       // минута окончания торговли
extern int Reverse       = 0;        // 1-реверс
extern int CloseSig      = 0;        // 1-закрытие по сигналу
extern int Slip          = 30;       // реквот
extern int Shift         = 1;        // на каком баре сигнал индикатора
extern int Magic         = 123;      // магик

extern string IndName    = "Aroow";
extern int SignalPeriod  = 9;

datetime t=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   Comment("");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   Comment("");
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool TimeSession(int aStartHour,int aStartMinute,int aStopHour,int aStopMinute,datetime aTimeCur)
  {
//--- время начала сессии
   int StartTime=3600*aStartHour+60*aStartMinute;
//--- время окончания сессии
   int StopTime=3600*aStopHour+60*aStopMinute;
//--- текущее время в секундах от начала дня
   aTimeCur=aTimeCur%86400;
   if(StopTime<StartTime)
     {
      //--- переход через полночь
      if(aTimeCur>=StartTime || aTimeCur<StopTime)
        {
         return(true);
        }
     }
   else
     {
      //--- внутри одного дня
      if(aTimeCur>=StartTime && aTimeCur<StopTime)
        {
         return(true);
        }
     }
   return(false);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void PutOrder(int type,double price)
  {
   int r=0;
   color clr=Green;
   double sl=0,tp=0;

   if(type==1 || type==3 || type==5)
     {
      clr=Red;
      if(StopLoss>0)
         sl=NormalizeDouble(price+StopLoss*_Point,_Digits);
      if(TakeProfit>0)
         tp=NormalizeDouble(price-TakeProfit*_Point,_Digits);
     }

   if(type==0 || type==2 || type==4)
     {
      clr=Blue;
      if(StopLoss>0)
         sl=NormalizeDouble(price-StopLoss*_Point,_Digits);
      if(TakeProfit>0)
         tp=NormalizeDouble(price+TakeProfit*_Point,_Digits);
     }

   r=OrderSend(NULL,type,Lot(),NormalizeDouble(price,_Digits),Slip,sl,tp,"",Magic,0,clr);
   return;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int CountTrades()
  {
   int count=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()<2)
               count++;
           }
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double Lot()
  {
   double lot=Lots;
   
   if(CountTrades()>0)
     {
      lot=NormalizeDouble(lot*MathPow(KLot,CountTrades()),2);
     }
   if(lot>MaxLot)
      lot=Lots;
   return(lot);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Trailing()
  {
   bool mod;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY)
              {
               if(Bid-OrderOpenPrice()>TrailingStop*_Point)
                 {
                  if(OrderStopLoss()<Bid-TrailingStop*_Point)
                    {
                     mod=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TrailingStop*_Point,OrderTakeProfit(),0,Yellow);
                     return;
                    }
                 }
              }

            if(OrderType()==OP_SELL)
              {
               if((OrderOpenPrice()-Ask)>TrailingStop*_Point)
                 {
                  if((OrderStopLoss()>(Ask+TrailingStop*_Point)) || (OrderStopLoss()==0))
                    {
                     mod=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+TrailingStop*_Point,OrderTakeProfit(),0,Yellow);
                     return;
                    }
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void BU()
  {
   bool m;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==OP_BUY)
              {
               if(OrderOpenPrice()<=(Bid-(BULevel+BUPoint)*_Point) && OrderOpenPrice()>OrderStopLoss())
                 {
                  m=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+BUPoint*_Point,OrderTakeProfit(),0,Yellow);
                  return;
                 }
              }

            if(OrderType()==OP_SELL)
              {
               if(OrderOpenPrice()>=(Ask+(BULevel+BUPoint)*_Point) && (OrderOpenPrice()<OrderStopLoss() || OrderStopLoss()==0))
                 {
                  m=OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-BUPoint*_Point,OrderTakeProfit(),0,Yellow);
                  return;
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseAll(int ot=-1)
  {
   bool cl;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==0 && (ot==0 || ot==-1))
              {
               RefreshRates();
               cl=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,_Digits),Slip,White);
              }
            if(OrderType()==1 && (ot==1 || ot==-1))
              {
               RefreshRates();
               cl=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,_Digits),Slip,White);
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double AllProfit(int ot=-1)
  {
   double pr=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic)
           {
            if(OrderType()==0 && (ot==0 || ot==-1))
              {
               pr+=OrderProfit()+OrderCommission()+OrderSwap();
              }

            if(OrderType()==1 && (ot==1 || ot==-1))
              {
               pr+=OrderProfit()+OrderCommission()+OrderSwap();
              }
           }
        }
     }
   return(pr);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   double blu = iCustom(NULL,0,IndName,SignalPeriod,4,Shift);
   double red = iCustom(NULL,0,IndName,SignalPeriod,5,Shift);
   double blu2 = iCustom(NULL,0,IndName,SignalPeriod,4,Shift+1);
   double red2 = iCustom(NULL,0,IndName,SignalPeriod,5,Shift+1);

   bool buy = blu<1000 && red2<1000;
   bool sell = red<1000 && blu2<1000;

   if(Reverse>0)
     {
      buy = red<1000 && blu2<1000;
      sell = blu<1000 && red2<1000;
     }

   if(BULevel>0)
      BU();
   if(TrailingStop>0)
      Trailing();
   if(AllProfit()>Profit && Profit>0)
      CloseAll();

   if(TimeSession(StartHour,StartMin,EndHour,EndMin,TimeCurrent()) && t!=Time[0])
     {
      if(buy)
        {
         PutOrder(0,Ask);
        }
      if(sell)
        {
         PutOrder(1,Bid);
        }
      t=Time[0];
     }

   if(CountTrades()>0 && CloseSig>0)
     {
      if(sell)
        {
         CloseAll(0);
        }
      if(buy)
        {
         CloseAll(1);
        }
     }

   Comment("\n blu: ",blu,
           "\n red: ",red,
           "\n All Profit: ",AllProfit());
  }
//+------------------------------------------------------------------+
Reason: