Mira cómo descargar robots gratis
¡Búscanos en Twitter!
Pon "Me gusta" y sigue las noticias
¿Es interesante este script?
Deje un enlace a él, ¡qué los demás también lo valoren!
¿Le ha gustado el script?
Evalúe su trabajo en el terminal MetaTrader 5
Librerías

CDir (MT5) - clase para obtener el índice del catálogo - librería para MetaTrader 5

Visualizaciones:
874
Ranking:
(20)
Publicado:
2017.03.27 11:11
\MQL5\Include\WIN_API\
Dir_API.mqh (16.64 KB) ver
\MQL5\Scripts\
¿Necesita un robot o indicador basado en este código? Solicítelo en la bolsa freelance Pasar a la bolsa

A veces, surge la necesidad de salir fuera del «entorno protegido» (sandbox) y leer el índice, comprobar la existencia de un archivo o una carpeta en el sistema de archivos. Además, puede que sea necesario averiguar los atributos del archivo o directorio, tamaño del archivo, hora de su creación, del último acceso o escritura. El código de abajo representa un ejemplo de la posible solución de estas tareas:

El prólogo estándar y la descripción de las variables, así como el enlace al código fuente de la clase de inclusión #include <WIN_API\Dir_API.mqh> es una instrucción explícita al compilador de que tiene que buscar este archivo en el directorio \MQL5\Include\WIN_API. Si desea, puede cambiar este enlace en función de sus preferencias respecto a la organización del trabajo con archivos de inclusión, usando el manual de referencia.

//+------------------------------------------------------------------+
//|                                            ExampleDirClass.mq4/5 |
//|                                        Copyright © 2017, Avatara |
//|                            https://www.mql5.com/en/users/avatara |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2017, Avatara"            2017/02/12
#property link      "https://www.mql5.com/en/users/avatara"
#property description "-- Example Dir Class --------------"
#property strict
#include <WIN_API\Dir_API.mqh> 
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   File_Def File;            // work structure
   CDir Dir; int total,i;     
   string path = TerminalInfoString(TERMINAL_COMMONDATA_PATH)+
               "\\..\\..\\Terminal";
//---    
  

Como podemos observar, la variable string path incluye la ruta hacia la carpeta que se ubica a dos niveles por encima de la ubicación estándar de la carpeta del terminal iniciado, y en caso de no usar la opción /portable, obtendremos la ruta hacia la carpeta que contiene los datos personalizados de todos los terminales de cliente de este usuario.

Un lector reflexivo dirá que hacemos unos movimientos extra, bastará con subir a un nivel y nos encontraremos en la carpeta necesaria. ¿Y si queremos navegar a otra carpeta, por ejemplo a Crashes o Tester? Para nuestro ejemplo es más instructivo.

Volvamos al código del ejemplo.

/---    
   total = Dir.Create(path);       // init dir
   Print (path," Total=",total-3); //Common,Help && Community not calc
    for (i = 0;i<total;i++)
    {
     string nameFile = Dir.GetNameFile(i);
     if(nameFile == "Common"||nameFile=="Help"||nameFile=="Community")
                                                              continue;
     File = Dir.GetStruct(i);
     Print (StringFormat ("%37s \t%8X\t  %5s\t",nameFile,
     File.FileAttributes,File.isDir?"-SubDir-":""),
     File.isDir?"            ":IntegerToString(File.FileLength,12),
     File.CreationTime,"     ",File.LastWriteTime,"     ",
     File.LastAccessTime);
    }
    Dir.Clear(); 
//---    

Teniendo creada la instancia de la clase, recibimos el número de elementos (archivos subcarpetas) en la variable total. Organizando el ciclo, imprimimos la lista de carpetas de los terminales (saltando los directorios compartidos). Vamos a ilustrar el acceso a los datos de la instancia con el acceso a la copia de la estructura de trabajo de datos de la clase File.

  path=TerminalInfoString(TERMINAL_PATH)+
              "\\..";
    Dir.Create(path,"\\M*");   // use filter "M*"       
    Print ("Alternative access:");
    total = Dir.Size(); 
    Print (Dir.Path," Total=",total);
    for (i = 0;i<total;i++)
    {
    Print  (StringFormat("%57s \t%8X \t %s \t",Dir.GetNameFile(i), 
                         Dir.GetStruct(i).FileAttributes,
                         Dir.isDir(i)?"--- SubDir ---": 
                         IntegerToString(Dir.GetFileLength(i),14)),
    "\t   Last modify: ",Dir.GetLastWriteTime(i));
    }
//---    
    Dir.Clear();  

En el ejemplo de la impresión de una parte del índice del directorio (se usa la selección de los elementos que contienen la M al principio) se demuestran otros métodos del trabajo con los elementos de la clase.

En la siguiente parte del código, comprobamos la existencia de un archivo especificado y buscamos su longitud.

//---  Use to check the file
    path="C:";
    Print("------------ Use to check the file ---------------------");
    stringfilter="\\pagefile.sys";
    Dir.Create(path,filter);
    total=Dir.Size();
    PrintFormat("Find %d entry.",total);
    if(total>0)
      for(i =0;i<total;i++)Print("File search \"",path,filter,
        "\" is return:",Dir.isDir(i)?"--- SubDir ---  "+
        Dir.GetNameFile(i):Dir.GetNameFile(i)+
        IntegerToString(Dir.GetFileLength(i),14)+" byte. \t",
        StringFormat("Atributes=%X",Dir.GetAtributes(i)));
    else  Print("File ",path,filter," is absent.");
//---
    Dir.Clear();              

Finalizamos el script de prueba con el ejemplo del uso de la referencia a la instancia de la clase de almacenamiento del elemento del índice del directorio:

  //--- use pointer to access data

   path="C:\\Temp";

    //---------------------> pointer declarate     CDir_API *e;        Print("------ Pointer use example. --------");     total =Dir.Create(path);     PrintFormat("%s       Find %d entry.",path,total);     if(total>0)       for(i =0;i<total;i++)       {       e=Dir.GetPointers(i);       Print(StringFormat("%77s \t%8X\t  %5s\t ",e.Name_File,           e.FileDef.FileAttributes,e.FileDef.isDir?"-SubDir-":""),           e.FileDef.isDir?"         ":           IntegerToString(e.FileDef.FileLength,12),"   ",           e.FileDef.CreationTime,"     ",           e.FileDef.LastWriteTime,"     ",           e.FileDef.LastAccessTime);       }       else  Print("File ",path,filter," is absent."); //---     Dir.Clear();     Print("------------- The end. -----------------------"); } //+------------------------------------------------------------------+

No me cabe la menor duda de que la mayoría de los lectores utilizará en su trabajo precisamente este método del acceso a los datos de la clase.

Para descifrar los atributos, puede necesitar la información adicional:

32 A file or directory that is an archive file or directory. Applications typically use this attribute to mark files for backup or removal.
FILE_ATTRIBUTE_COMPRESSED 2048 (0x800) A file or directory that is compressed. For a file, all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_DEVICE 64 (0x40) This value is reserved for system use.
FILE_ATTRIBUTE_DIRECTORY 16 (0x10) The handle that identifies a directory.
FILE_ATTRIBUTE_ENCRYPTED 16384 (0x4000) A file or directory that is encrypted. For a file, all data streams in the file are encrypted. For a directory, encryption is the default for newly created files and subdirectories.
FILE_ATTRIBUTE_HIDDEN 2 (0x2) The file or directory is hidden. It is not included in an ordinary directory listing.
FILE_ATTRIBUTE_INTEGRITY_STREAM 32768 (0x8000)

The directory or user data stream is configured with integrity (only supported on ReFS volumes). It is not included in an ordinary directory listing. The integrity setting persists with the file if it's renamed. If a file is copied the destination file will have integrity set if either the source file or destination directory have integrity set.

Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This flag is not supported until Windows Server 2012.

FILE_ATTRIBUTE_NORMAL 128 (0x80) A file that does not have other attributes set. This attribute is valid only when used alone.
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 8192 (0x2000) The file or directory is not to be indexed by the content indexing service.
FILE_ATTRIBUTE_NO_SCRUB_DATA 131072 (0x20000)

The user data stream not to be read by the background data integrity scanner (AKA scrubber). When set on a directory it only provides inheritance. This flag is only supported on Storage Spaces and ReFS volumes. It is not included in an ordinary directory listing.

Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This flag is not supported until Windows 8 and Windows Server 2012.

FILE_ATTRIBUTE_OFFLINE 4096 (0x1000) The data of a file is not available immediately. This attribute indicates that the file data is physically moved to offline storage. This attribute is used by Remote Storage, which is the hierarchical storage management software. Applications should not arbitrarily change this attribute.
FILE_ATTRIBUTE_READONLY 1 (0x1) A file that is read-only. Applications can read the file, but cannot write to it or delete it. This attribute is not honored on directories. For more information, see You cannot view or change the Read-only or the System attributes of folders in Windows Server 2003, in Windows XP, in Windows Vista or in Windows 7.
FILE_ATTRIBUTE_REPARSE_POINT 1024 (0x400) A file or directory that has an associated reparse point, or a file that is a symbolic link.
FILE_ATTRIBUTE_SPARSE_FILE 512 (0x200) A file that is a sparse file.
FILE_ATTRIBUTE_SYSTEM 4 (0x4) A file or directory that the operating system uses a part of, or uses exclusively.
FILE_ATTRIBUTE_TEMPORARY 256 (0x100) A file that is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because typically, an application deletes a temporary file after the handle is closed. In that scenario, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.
FILE_ATTRIBUTE_VIRTUAL 65536 (0x10000) This value is reserved for system use.

Espero que este ejemplo, como la propia clase, les sea de utilidad, y yo no les haya agotado mucho con mis explicaciones... ;)

¡Disfrútenlo!

Traducción del ruso realizada por MetaQuotes Ltd
Artículo original: https://www.mql5.com/ru/code/17623

HistoryPositionInfo HistoryPositionInfo

Devuelve el beneficio de la posición en puntos a base del historial de trading.

Dsl - macd Dsl - macd

Indicador MACD en interpretación de la línea de señal descontinua (DSL).

XRSXCandleKeltnerPluse XRSXCandleKeltnerPluse

Indicador XRSXCandleKeltner con la posibilidad de la indicación de la ruptura.

XCCXCandleKeltnerPluse XCCXCandleKeltnerPluse

Indicador XCCXCandleKeltner con la posibilidad de la indicación de la ruptura.