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

 

Please help me to write the code

Conditions for the indicator:

If the high (2) is greater than the previous high (1) and the low (2) is greater than the previous low (1), wait for the opposite situation (highs 3 and 4) and (low 3 and 4). At the maximum between the highs (2 and 3), set the mark of the maximum as a blue dot.

If the maximum (4) is lower than the previous maximum (3) and the minimum (4) is lower than the previous minimum (3), wait for the opposite situation (highs 5 and 6) and (lows 5 and 6). At the low between the highs (4 and 5), the low is set as the red dot.

Sorry, the picture doesn't fit.

The code itself:


 for(int i=Start;i>0 && !IsStopped();i--)

   {

    int a1=0,b1=0,a2=0,b2=0, Stop1a=0, Stop1b=0;

//-----------------------------------    

    if(high[i-1]<high[i] && low[i-1]<low[i] && Stop1a==0)  // условие для установки максимума и открытый доступ

     {

      Stop1a=1;                                            // закрываем доступ (чтобы небыло ненужных повторений)

      for(i;i>0;i--)                                       // цикл для счетчика

        {

         a1++;                                             // счетчик для функции iHighest

         if(high[i-1]>high[i] && low[i-1]>low[i])          // противоложное условие предыдущему

          {

           Stop1a=0;                                       // открываем доступ

           b1=iHighest(NULL,0,MODE_HIGH,a1,i);             // получаем индекс максимального значения

           Max1[b1]=high[b1];                              // заполняем индикаторный массив для максимумов

           break;                                          // прерываем цикл

          }

        }

     } 



    if(high[i-1]>high[i] && low[i-1]>low[i] && Stop1b==0)  // условие для установки минимума и открытый доступ

     {

      Stop1b=1;                                            // закрываем доступ (чтобы небыло ненужных повторений)

      for(i;i>0;i--)                                       //  цикл для счетчика

        {

         a2++;                                             // счетчик для функции iLowest

         if(high[i-1]<high[i] && low[i-1]<low[i])          // противоложное условие предыдущему

          {

           Stop1b=0;                                       // открываем доступ

           b2=iLowest(NULL,0,MODE_LOW,a2,i);               // получаем индекс минимального значения

           Min1[b2]=low[b2];                               // заполняем индикаторный массив для минимумов

           break;                                          // прерываем цикл

          }

        }

     } 
 
Dear specialists! Code:

int Handle = FileOpen("2022.02.01 12-00",FILE_ANSI|FILE_WRITE|FILE_COMMON,'-'); //open for writing
FileWrite(Handle, "1", "643", "USDCAD","[11-1.30-0.70]");//write dataset
FileSeek(Handle,0,SEEK_SET);//replaced the pointer to the beginning of the file (I think this is unnecessary, but still)
FileClose(Handle);//closed the file
Handle = FileOpen("2022.02.01 12-00",FILE_ANSI|FILE_SHARE_READ|FILE_COMMON,'-');//open for reading
Print(FileTell(Handle)," ",FileReadNumber(Handle)," ",FileReadNumber(Handle));
FileClose(Handle); //closed the file

The log entry must contain the current pointer position, a space, the first value read from the file (1), a space, the second value read from the file (643). Instead, the following is logged:

6 643.0 1.0

That is, for some reason I can't figure out, the file pointer is not at the beginning of the file, but six bytes away from it, at the second separator ("-"), while the next reading is from right to left. The attempts to move the pointer to the beginning of the file using the FileSeek function were unsuccessful.
My intellect is not enough to understand the reason for this. Please explain what the hell is going on.
 
Sergey Gubar #:

Please help me to write the code

Conditions for the indicator:

If the high (2) is greater than the previous high (1) and the low (2) is greater than the previous low (1), wait for the opposite situation (highs 3 and 4) and (low 3 and 4). At the maximum between the highs (2 and 3), set the mark of the maximum as a blue dot.

If the maximum (4) is lower than the previous maximum (3) and the minimum (4) is lower than the previous minimum (3), wait for the opposite situation (highs 5 and 6) and (lows 5 and 6). At the low between the highs (4 and 5), the low is set as the red dot.

Sorry, the picture doesn't fit.

The code itself:


Don't look ahead

[i+1]
 

Please help me!

I'm not getting what I'm expecting at all. Need to read the log file

#define  GENERIC_READ            0x80000000
#define  GENERIC_WRITE           0x40000000

#define  WIN32_FILE_SHARE_READ   1
#define  WIN32_FILE_SHARE_WRITE  2

#define  CREATE_NEW              1
#define  CREATE_ALWAYS           2
#define  OPEN_ALWAYS             4
#define  OPEN_EXISTING           3
#define  TRUNCATE_EXISTING       5

#define  SEEK_FILE_BEGIN         0
#define  SEEK_FILE_CURRENT       1
#define  SEEK_FILE_END           2

#define  INVALID_HANDLE_VALUE    -1
#define  UNICODE
#define  FILE_ATTRIBUTE_NORMAL 0x80

#import "kernel32.dll"
int CreateFileW(string Filename,uint AccessMode,int ShareMode,int PassAsZero,int CreationMode,int FlagsAndAttributes,int AlsoPassAsZero);
int ReadFile(int FileHandle,ushort & Buffer[],int BufferLength,int & BytesRead[],int PassAsZero);
int SetFilePointer(int FileHandle,int Distance,int PassAsZero,int FromPosition);
int GetFileSize(int FileHandle,int PassAsZero);
int CloseHandle(int FileHandle);
#import

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnStart()
{
  string sDate = TimeToString(TimeCurrent()-86400, TIME_DATE);
  string FileName = TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL4\\Logs\\"+sDate+".log";
  int FileHandle = CreateFileW(FileName, GENERIC_READ, WIN32_FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
   SetFilePointer(FileHandle, 0, 0, SEEK_FILE_BEGIN);
   int szFileA = GetFileSize(FileHandle, 0);
   ushort ReadBufferA[];
    ArrayResize(ReadBufferA, szFileA);
    int BytesReadA[1] = {0};
    ReadFile(FileHandle, ReadBufferA, szFileA, BytesReadA, 0);

  string Res=ShortArrayToString(ReadBufferA, 0, BytesReadA[0]);

  string msg="FileHandle: "+FileHandle+"    \n"
             "FileSize: "+szFileA+"    \n"
             +"Res: "+Res;
  Print(msg); // 2022.02.03 04:56:43.670	test GBPJPY,M30: FileHandle: -1    FileSize: -1    Res: 

 CloseHandle(FileHandle);
}
//+------------------------------------------------------------------+
 

Good afternoon, all. I have an indicator that draws Fibonacci levels. I need the EA to place another EA with certain settings on this chart when the price reaches the 61.8 level on this Fibo grid and press the button to open an order.

Below is a screenshot of the indicator and the EA with its buttons. We do not have the source code of the Expert Advisor with the buttons. An EA for tracking the 61.8 level on the Fibo grid will not work in the tester; it will work on the demo account and then, if everything goes well, this combination can be installed on the real account.

indicator that draws Fibo levels the advisor with the buttons must be pressed on the left open


Is it really possible to do? If so, how to implement it in words, and then in code? Please explain in detail and clearly.

 
DanilaMactep #:

Good afternoon, all. I have an indicator that draws Fibonacci levels. I need the EA to place another EA with certain settings on this chart when the price reaches the 61.8 level on this Fibo grid and press the button to open an order.

Below is a screenshot of the indicator and the EA with its buttons. We do not have the source code of the Expert Advisor with the buttons. An EA for tracking the 61.8 level on the Fibo grid will not work in the tester; it will work on the demo account and then, if everything goes well, this combination can be installed on the real account.


Is it really possible to do? If so, how to implement in words, and then in code? Please explain how you can more detail and clearly.

Do you have memory for 24 hours?

 
Andrey Sokolov #:

Do you have a 24-hour memory?

No. I haven't found out how to implement what I need - maybe I'll get it with the second iteration;-)
 
DanilaMactep #:
No. I haven't found out how to implement what I need - maybe I will with the second iteration;-)

Maxim Kuznetsov told you how. Have you read it?

 

Good day please help to solve the problem with wrong closing of orders

When a positive profit is earned, the Expert Advisor closes the first and the last order in the order grid

Everything is fine on a demo account but on a real account only the second-to-last order is closed. I faced such a problem when I had to close the whole grid of orders and the problem was in the requotes, then the flag was set and the problem is solved. Here I have done the same but the problem is not solved.

Flag:

int flag_close3=0;
//-------------------------------------------------------------------+  Команда на закрытие мин макс и предпоследнего ордеров в сетке профит = 0
   if(CalculiteProfitMinMaxPenultimateOrders() >= 0 && Drawdown >= DrawdownClosingMinMaxOrdersZero && FindPenultimateProfit() > 0)
     {
       flag_close3=1;
     }
//-------------------------------------------------------------------+  Флаг на закрытие  ордеров
   if(flag_close3==1)
      ClosseMinMaxPenultimateOrdersZero();
//+----------------------------------------------------------------------------+
//| Закрытие минимального максимального и предпоследнего ордеров профит = 0    |
//+----------------------------------------------------------------------------+
void  ClosseMinMaxPenultimateOrdersZero()
  {
   int slipp = (int) MarketInfo(_Symbol,MODE_SPREAD)*2;
   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(CalculiteProfitMinMaxPenultimateOrders() >= 0  && Drawdown >= DrawdownClosingMinMaxOrdersZero && FindPenultimateProfit() > 0)
                 {
                  if(OrderClose(GetTicketPenultimateOrder(), FindPenultimateLots(), Bid, slipp) && OrderClose(GetTicketMinOrder(), GetMinLotOrder(), Bid, slipp) &&
                     OrderClose(GetTicketMaxOrder(), FindLastLots(), Bid, slipp))
                    {
                     SendNotification("Закрылся минимальный максимальный и предпоследний ордера на покупку: " + Symbol() + ", Баланс: " + DoubleToString(NormalizeDouble(AccountBalance(), 2))
                                      + ", Свободно денежных средств: " + DoubleToString(NormalizeDouble(AccountFreeMargin(), 2)));
                     Print("Максимальный и минимальный ордера на покупку успешно закрыты!");
                    }
                  else
                    {
                     Print("Не удалось закрыть максимальный и минимальный ордера на покупку!",GetLastError());
                    }
                 }
              }

            if(OrderType() == OP_SELL)
              {
               if(CalculiteProfitMinMaxPenultimateOrders() >= 0 && Drawdown >= DrawdownClosingMinMaxOrdersZero && FindPenultimateProfit() > 0)
                 {
                  if(OrderClose(GetTicketPenultimateOrder(), FindPenultimateLots(), Ask, slipp) && OrderClose(GetTicketMinOrder(), GetMinLotOrder(), Ask, slipp) &&
                     OrderClose(GetTicketMaxOrder(), FindLastLots(), Ask, slipp))
                    {
                     SendNotification("Закрылся минимальный максимальный и предпоследний ордера на продажу: " + Symbol() + ", Баланс: " + DoubleToString(NormalizeDouble(AccountBalance(), 2))
                                      + ", Свободно денежных средств: " + DoubleToString(NormalizeDouble(AccountFreeMargin(), 2)));
                     Print("Максимальный и минимальный ордера на продажу успешно закрыты!");
                    }
                  else
                    {
                     Print("Не удалось закрыть максимальный и минимальный ордера на продажу!",GetLastError());
                    }
                 }
              }
           }
        }
     }
  }

Thanks!!!!

 
EVGENII SHELIPOV on a demo account but on a real account only the second-to-last order is closed. I faced such a problem when I had to close the whole grid of orders and the problem was in the requotes, then the flag was set and the problem is solved. Here I have done the same but the problem is not solved.

Flag:

Thanks!!!!

Where does your flag reset?