Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 861

 

Hi, could you tell me why it's not working? No errors, but orders do not open in the tester. I'm trying to write an EA for breakout of high and low of a daily candlestick as a training tool.


extern int      TimeCandle   = 1440;      //таймфрейм свечи, которую пробиваем 
extern int      HourStart=10; // час начала торговли
extern double   Lots=0.1;     // лот торговли   
extern int      StopLoss=100; // стоплосс
extern int      TakeProfit=100; // тайкпрофит
extern int      znak=5;     // количество знаков котировки
extern int      magik=54321;     // магик 

double minprice; // минимальная цена
double maxprice;// максимальная цена


void OnTick()
  {
  double SL, TP;
  int ticket;
 
   minprice = iLow(Symbol(),TimeCandle,1);
   maxprice = iHigh(Symbol(),TimeCandle,1);   
   
   if (TimeHour(TimeCurrent()==HourStart))
   { 
    if (BuyLimitCount()==0 && BuyCount()==0) //если нет ордера то пытаться открыть
    { 
    SL = NormalizeDouble(maxprice - StopLoss*Point,znak);
    TP = NormalizeDouble(maxprice + TakeProfit*Point,znak);
    ticket = OrderSend(Symbol(), OP_BUYLIMIT,Lots,maxprice, 10, SL,TP,"", magik,0,Blue);
    
    if (ticket <0)
    Print ("Не удалось открыть ордер на покупку");
    }
    
    
     if (SellLimitCount()==0 && SellCount()==0) //если нет ордера то пытаться открыть
    { 
    SL = NormalizeDouble(minprice + StopLoss*Point,znak);
    TP = NormalizeDouble(minprice - TakeProfit*Point,znak);
    ticket = OrderSend(Symbol(), OP_SELLLIMIT,Lots,minprice,10, SL,TP,"", magik,0,Red);
        
    if (ticket <0)
    Print ("Не удалось открыть ордер на продажу");
    }
    
    }
    Comment ("Минимальная цена:" + DoubleToStr(minprice,znak) + "\n" + "Максимальная цена:"+ DoubleToStr(maxprice, znak)); 
  }
   
  // проверяем есть ли байлимит ордера с конца
  int BuyLimitCount()
  {
  int count = 0;
  for (int i=OrdersTotal()-1;i>=0;i--)
  {
    if (OrderSelect(i, SELECT_BY_POS,MODE_TRADES) == true && 
        OrderMagicNumber()== magik &&                        
        OrderType() == OP_BUYLIMIT )                        
        {
        count ++;
        }
    }
    return(count);  
    
  }
   // проверяем есть ли селллимит ордера с конца
  int SellLimitCount()
  {
  int count = 0;
  for (int i=OrdersTotal()-1;i>=0;i--)
  {
    if (OrderSelect(i, SELECT_BY_POS,MODE_TRADES) == true && 
        OrderMagicNumber()== magik &&                        
        OrderType() == OP_SELLLIMIT )                        
        {
        count ++;
        }
    }
    return(count);      
  }
  
   // проверяем есть ли бай ордера с конца
  int BuyCount()
  {
  int count = 0;
  for (int i=OrdersTotal()-1;i>=0;i--)
  {
    if (OrderSelect(i, SELECT_BY_POS,MODE_TRADES) == true && 
        OrderMagicNumber()== magik &&                        
        OrderType() == OP_BUY )                        
        {
        count ++;
        }
    }
    return(count);      
  }
  
  // проверяем есть ли селл ордера с конца
  int SellCount()
  {
  int count = 0;
  for (int i=OrdersTotal()-1;i>=0;i--)
  {
    if (OrderSelect(i, SELECT_BY_POS,MODE_TRADES) == true &&         
        OrderMagicNumber()== magik &&                        
        OrderType() == OP_SELL )                        
        {
        count ++;
        }
    }
    return(count);      
  }
Как самому создать советника или индикатор - Алгоритмический трейдинг, торговые роботы - MetaTrader 5
Как самому создать советника или индикатор - Алгоритмический трейдинг, торговые роботы - MetaTrader 5
  • www.metatrader5.com
Для разработки торговых систем в платформу встроен собственный язык программирования MetaQuotes Language 5 (MQL5), среда разработки MetaEditor и инструменты тестирования стратегий. Любую информацию о разработке торговых стратегий на языке MQL5 можно найти на официальном сайте MQL5.community. На этом же сайте в разделе Code Base могут быть...
 
nelenaby:

Hi, could you tell me why it's not working? No errors, but orders do not open in the tester. I am trying to write an EA for breakout of high and low of a daily candlestick as a training tool.


It does not open, i.e. it does not try or it tries but fails? What do they say in the log?

 
nelenaby:

Hi, could you tell me why it's not working? No errors, but orders do not open in the tester. I am trying to write an EA for breakdown of high and low of a daily candlestick as a training tool.


Analyze this expression of yours

if (TimeHour(TimeCurrent()==HourStart))
        {
          ........
        }

I do not understand the meaning of this expression and maybe I'm wrong. But you should at least replace "(TimeCurrent()==HourStart)" with "(TimeCurrent() - HourStart)".

 

Next, if I understand you correctly - you are trying to place a BuyLimit order if there is no BuyLimitOrder AND BuyPosition. Note the exact "AND". That is, the presence of any of them separately suits you, thus, at a desired position of the current price you will get an infinite number of ByLimits, one on each tick, until at least one of them triggers and the first position opens. Also, you do not care where the price is now. As soon as the strange condition on time is fulfilled (just above post), I think there's an error, but never mind. Anyway, if you disregard that, the EA will start placing wrong orders on the first tick, until the price reaches yesterday's high, because you are using yesterday's high as the price for placing the order. The Buy Limit is set below the current price, which means that the current price should be above yesterday's high but until then the order will fail.

So, the only situation that suits you is when the price moved above yesterday's high, there is no bye-limit, and there are no open trades. This is a rare combination. Besides, it will not affect the breakout, but will bounce after the breakout (because there is a bylimit), and it will throw you lots of errors, starting from the first tick above yesterday's maximum (that is another error). The condition is already fulfilled, the Expert Advisor throws the order, but there is also a spread, the minimum allowed distance from the market, etc.

 
Sergey Voytsekhovsky:

I'm having trouble understanding the meaning of this expression, maybe I'm wrong, but at the very least replace "(TimeCurrent()==HourStart)" with "(TimeCurrent() - HourStart)".

That's right, there is an error here. You need if (TimeHour(TimeCurrent())==HourStart)

Now the order opens sometimes, but it generates more errors (OrderSend error 130).

The error here is not correct about limit orders.

 
nelenaby:

That's right, there's an error here. It needs if (TimeHour(TimeCurrent())==HourStart)

Now it opens transactions sometimes, but it throws more errors (OrderSend error 130).

It is not right about limit orders.

Here is a script to work with time.

It is old but it works correctly.

Files:
 

Hello.

Please help me to understand how to work with files.

When the program is running, I save the received data to a file and read the CSV.

The file increases, the speed drops. I tried to update (overwrite) some of the elements in the lines. No way!

You cannot delete a selected line! I cannot add a new element to an old line!

This is very strange! You may easily delete a file or a graphic object, etc. But when it comes to working with a created file, it is an absolute deadlock!

On forums there is only one recommendation: "Read the file into memory, change or delete the line and save the new file under the old name".

This does not seem to me to be the right solution. I must have missed something. Please help me figure it out.

 
im-zvv:

That doesn't seem like the right decision to me. I'm probably missing something. Please help me figure it out.

You should be urgently hired by Microsoft to finally fix this"wrong solution" for file handling.


File handling is not like editing a file in a file editor, it's more like making a word out of dice with individual letters.
If you need to insert a new letter, all the cubes following it need to be moved to the right.
If you want to remove an old letter, all the dice following it must be moved to the left.
Therefore, if the file is not large and the work does not require access to the file, it is indeed easier to write the data to a new file, delete the old one, and rename the new file to the name of the old one.

If I'm not mistaken, the only thing missing in MQL when working with files is the ability to trim the file length to the required size.


 
Alekseu Fedotov:

Here's a script for working with time.

It's old, but it works correctly.

I used to use Kim's function too, then I found time to write my own:

//_______________________________________________________________________
class CWorkTime
  {
private:
   int               mday,mstarthour,mstophour,mstartmin,mstopmin;
   datetime          mstarttime,mstoptime;
   bool              UseThisSession;
   void inittime()
     {
      mday=Day();
      MqlDateTime dtstart,dtstop;
      TimeToStruct(TimeCurrent(),dtstart);
      dtstop=dtstart;
      dtstart.hour= mstarthour;
      dtstart.min = mstartmin;
      dtstop.hour = mstophour;
      dtstop.min = mstopmin;
      mstarttime = StructToTime(dtstart);
      mstoptime=StructToTime(dtstop);
     }
public:
   void              CWorkTime(void){};
   void              ~CWorkTime(void){};
   void              CWorkTime(int hstart,int mstart,int hstop,int mstop)
     {
      mstarthour=hstart;
      mstartmin = mstart;
      mstophour=hstop;
      mstopmin=mstop;
      UseThisSession=(mstarthour<0 || mstophour<0 || mstarthour>23 || mstophour>23) ? false : true;
      UseThisSession=(mstartmin<0 || mstopmin<0 || mstartmin>59 || mstopmin>59) ? false : true;
      if(UseThisSession) inittime(); else Print("Время работы советника не используется");
     };

   bool              Disable()
     {
      bool result=false;
      if(UseThisSession)
        {
         if(mday!=Day()) inittime();
         datetime t=TimeCurrent();
         result=t>=mstarttime && t<=mstoptime ? false : true;
        }
      return(result);
     };
  }
*Work;


.....

int OnInit()
{
   Work=new CWorkTime(StartHour,StartMinute,StopHour,StopMinute);
}

.....


void OnTick()
  {

if(Work.Disable())
{
 Comment("Не торговое время!!! Сопровождение открытых ордеров");
 }
else
{......
disable runtime - you have to enter invalid data when initialising the constructor, e.g. 25 hours or 70 minutes
 
Sergey Dzyublik:

You urgently need to be hired by Microsoft so that they finally fix this"wrong solution" for file handling.


Working with files is not like editing a file in a file editor, it's more like making a word out of dice with individual letters.
If you need to insert a new letter, all the cubes following it need to be moved to the right.
If you want to remove an old letter, all the dice following it must be moved to the left.
Therefore, if the file is not large and the work does not require access to the file, it is indeed easier to write the data to a new file, delete the old one, and rename the new file to the name of the old one.

If I'm not mistaken, the only thing missing in MQL when working with files is the ability to trim the file length to the required size.


Thank you. Good clarification. Unfortunately my file is very big and therefore I will have to work with "cubes".
Reason: