Questions from Beginners MQL5 MT5 MetaTrader 5 - page 953

 
fxsaber:

Where would I use it?

This whole idea is that let's say I have directories with files for processing at "..\MQL5\\Files\00\dir_01" address. Using your wonderful code, I get the path to these folders in an array and want to access these files, knowing exactly what files should be processed, and I have to write the path to them, for example "MQL5\\Files\\\00\dir_01\\A\test.csv" and the code returns "MQL5\Files\00\\dir_01\A\", and I am asking if I can modify it to return the optimal path that will be applicable in further code.

 
Aleksey Vyazmikin:

Where would I use it?

This whole idea is that let's say I have directories with files for processing at "..\MQL5\\Files\00\dir_01" address. Using your wonderful code, I get the path to these folders in an array and want to access these files, knowing exactly what files I need to process, and I need to set path to these files, for example "MQL5\\Files\\\00\dir_01\\A\test.csv" and the code returns "MQL5\Files\00\\dir_01\A\", and I am asking whether it can be modified in order to return the optimal path that will be applicable in further code.

You just don't understand what a double slash is - it's one character which is denoted by two in the syntax: first slash command, second slash what.

\n, \r, \t, \" and \\\ are characters that are set by this rule. I.e. there is always one slash in the path.

 
fxsaber:

You just don't understand what a double slash is - it's one character, which in syntax is denoted by two: the first slash command, the second slash what.

\n, \r, \t, \" and \\\ are characters that are set by this rule. I.e. there's always one slash in the path.

I don't exclude that I'm missing something, but I need two slashes to generate file path, not one.

 
Aleksey Vyazmikin:

I don't rule out that I'm misunderstanding something, but I need two slashes to generate the file path, not one.

You don't need two slashes.

void OnStart()
{
  uchar Array[1] = {'\\'};
  
  Print(CharArrayToString(Array));
}
Try to print one, two, or three slashes into the log. Maybe you will understand then.
 
fxsaber:

You don't need two slashes.

Try to print one, two, or three slashes into the log. Maybe then you will understand.

Yes, I understand that the slash is a command, but I need to write the path, and I use double slash for that.

Here's the path.

int zz=FileOpen(" 00\\dir_01\\A\\ZZ_Analiz_Open.bin",FILE_BIN|FILE_READ);

I got a string in the array Folders[0]:

00\dir_01\A\

I want to access a file with the same name but in different directories by changing the index of the array.

int zz=FileOpen(Folders[0]+"ZZ_Analiz_Open.bin",FILE_BIN|FILE_READ);

but this command will get an error, won't it?

 
And in the main file, one of the methods is created объект класса included file and one of the methods is called.

That's a waste.

 

Hello!

I'm trying to switch from MQL4 to MQL5 and I cannot find the last closed position.
In MQL5, when we send an order, it is an order, and when it is opened it becomes a position, and logically it should be placed in position history and the deleted pending orders should be placed in order history, but all I see is the history of orders from deals, so I do not know where to find a closed position.

I tried this way:

ulong GetLastCloseTicket()
{
    datetime to=TimeCurrent();
    datetime from=to-3*PeriodSeconds(PERIOD_D1);
    HistorySelect(from,to);    
    int Htotal=HistoryOrdersTotal();
    ulong lastOrders[2];
    ulong ticket;
    ArrayInitialize(lastOrders, 0);
 
    for (uint j = 0; j < Htotal; j++)
    {           
        if(ticket= HistoryOrderGetTicket(j)) {            
            if (HistoryOrderGetInteger(ticket,ORDER_TYPE)== ORDER_TYPE_BUY || HistoryOrderGetInteger(ticket,ORDER_TYPE)== ORDER_TYPE_SELL) {
                Print("ticket = " +ticket+";");
                Print("ORDER_TYPE = " +ORDER_TYPE+";");                
                // хранить самый последний (недавно закрытый) ордер в lastOrders[1]
                // а предпоследний в lastOrders[0]
                if (ticket > lastOrders[0]) {
                    if (ticket > lastOrders[1]) {
                        lastOrders[0] = lastOrders[1];
                        lastOrders[1] = ticket;                   
                    } else {
                        lastOrders[0] = ticket;
                    }
                }
            }
        }
    }
    Print("lastOrders[1] = " +lastOrders[1]+";");
    return (lastOrders[1]);   
} 

But it displays numbers of both opened and closed positions. ORDER_TYPE always shows 4, which is also not clear.

I tried to change ORDER to DEAL, but it does not work either.
Please, help me, what is wrong?

 
vladzeit:

Vladimir, thank you.I am already familiar withRefreshRates function fromCSymbolInfo class.I've seen it in your works and read it in a primer.

The call of this function inOnTick and output of price values inComment are also clear to me from the example. The procedure inOnInit to check the current symbol is also clear to me.

While waiting for the example with the new bar, I will try to put some practice with your example, I haven't used it in practice. I will try it.


So, this example works only at the moment when a new bar is born.

This example uses static variablesPrevBars,prev_ask andprev_bid. The essence of static variables is.

Local variables declared with the static keyword retain their values forthe lifetime of the function. With each next call of the function, these local variables contain the values they had in the previous call.

So our three static variables(PrevBars,prev_ask andprev_bid) are local variables declared inside OnTick function and they store their values, which they had when they entered OnTick function previously.

PrevBars stores the time of the previous bar. This time is compared totime_0, the time of the current bar. As long asPrevBars is equal totime_0, we are at the current bar and exit the OnTick function. The same with the variables that store the prices of the previous bar: we first display the previous and current prices and then write the current prices into the variablesprev_ask andprev_bid.

//+------------------------------------------------------------------+
//|                                      Display previous prices.mq5 |
//|                              Copyright © 2018, Vladimir Karputov |
//|                                           http://wmua.ru/slesar/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2018, Vladimir Karputov"
#property link      "http://wmua.ru/slesar/"
#property version   "1.000"
//---
#include <Trade\SymbolInfo.mqh>  
CSymbolInfo    m_symbol;                     // symbol info object
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
      return(INIT_FAILED);
   RefreshRates();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   static datetime PrevBars=0;
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==PrevBars)
      return;
   PrevBars=time_0;
   if(!RefreshRates())
     {
      PrevBars=0;
      return;
     }
//---
   static double prev_ask=0.0;
   static double prev_bid=0.0;
   Comment("       Previous | Current","\n",
           "Ask: ",DoubleToString(prev_ask,m_symbol.Digits())," | ",DoubleToString(m_symbol.Ask(),m_symbol.Digits()),"\n",
           "Bid:  ",DoubleToString(prev_bid,m_symbol.Digits())," | ",DoubleToString(m_symbol.Bid(),m_symbol.Digits()));
   prev_ask=m_symbol.Ask();
   prev_bid=m_symbol.Bid();
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates(void)
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print("RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
      return(false);
//---
   return(true);
  }
//+------------------------------------------------------------------+
 

Forum on Trading, Automated Trading Systems and Strategy Tests

FAQ from Beginners MQL5 MT5 MetaTrader 5

Aleksey Vyazmikin, 2018.12.05 00:39

I know it's a slash command, but I need to write the path.

Here's the path let's say

int zz=FileOpen(" 00\\dir_01\\A\\ZZ_Analiz_Open.bin",FILE_BIN|FILE_READ);

I got a string in Folders[0] array:

00\dir_01\A\

I want to access a file with the same name but in different directories by changing the index of the array.

int zz=FileOpen(Folders[0]+"ZZ_Analiz_Open.bin",FILE_BIN|FILE_READ);

but this command will get an error, won't it?


There will be no error. You still haven't figured out what a double slash is.

 
Aleksey Vyazmikin:

Yes, I understand that the slash is a command, but I need to write the path, and I use double slash for that.

Here's the path for example

I got a string in the array Folders[0]:

I want to access a file with the same name but in different directories by changing the array index.

but this command will get an error, won't it?

Alexey, take an example from the documentation

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- неправильный способ открытия файла
   string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
   string filename=terminal_data_path+"\\MQL5\\Files\\"+"fractals.csv";
   int filehandle=FileOpen(filename,FILE_WRITE|FILE_CSV);
   if(filehandle<0)
     {
      Print("Неудачная попытка открыть файл по абсолютному пути");
      Print("Код ошибки ",GetLastError());
     }
//--- правильный способ работы в "файловой песочнице"
   ResetLastError();
   filehandle=FileOpen("fractals.csv",FILE_WRITE|FILE_CSV);
   if(filehandle!=INVALID_HANDLE)
     {
      FileWrite(filehandle,TimeCurrent(),Symbol(), EnumToString(_Period));
      FileClose(filehandle);
      Print("FileOpen OK");
     }
   else Print("Операция FileOpen неудачна, ошибка ",GetLastError());
//--- еще один пример с созданием вложенной директории в MQL5\Files\
   string subfolder="Research";
   filehandle=FileOpen(subfolder+"\\fractals.txt",FILE_WRITE|FILE_CSV);
      if(filehandle!=INVALID_HANDLE)
     {
      FileWrite(filehandle,TimeCurrent(),Symbol(), EnumToString(_Period));
      FileClose(filehandle);
      Print("Файл должен быть создан в папке "+terminal_data_path+"\\"+subfolder);
     }
   else Print("Операция FileOpen неудачна, ошибка ",GetLastError());
  }

and print the two string variables highlighted in the example code. Find the differences and understand that the double slash is only written in the program code, but only one is left at compile time and one is used in the file path.

Документация по MQL5: Файловые операции / FileOpen
Документация по MQL5: Файловые операции / FileOpen
  • www.mql5.com
[in]  Имя открываемого файла, может содержать подпапки. Если файл открывается для записи, то указанные подпапки будут созданы в случае их отсутствия. [in]  значение, используемое в качестве разделителя в txt или csv-файле. Если для csv-файла разделитель не указан, то по умолчанию используется символ табуляции. Если для txt-файла разделитель не...
Reason: