Assista a como baixar robôs de negociação gratuitos
Encontre-nos em Facebook!
Participe de nossa página de fãs
Script interessante?
Coloque um link para ele, e permita que outras pessoas também o avaliem
Você gostou do script?
Avalie seu funcionamento no terminal MetaTrader 5
Bibliotecas

CDir (MT5) - classe para obter a tabela de conteúdo do diretório - biblioteca para MetaTrader 5

Visualizações:
1043
Avaliação:
(20)
Publicado:
2017.03.28 12:47
\MQL5\Include\WIN_API\ \MQL5\Scripts\
Precisa de um robô ou indicador baseado nesse código? Solicite-o no Freelance Ir para Freelance

Às vezes é necessário ir além da "área restrita" e ler a tabela de conteúdo, verificar se há um arquivo ou diretório no sistema de arquivos. Além disso, pode ser preciso encontrar atributos do arquivo ou diretório, tamanho, tempo de criação, último acesso ou entrada. Um exemplo de uma possível solução para estes problemas é representado por este código:

Um prólogo padrão e uma descrição das variáveis, bem como um link para o código-fonte da classe incluída #include <WIN_API\Dir_API.mqh> são uma indicação clara para o compilador procurar esse arquivo no diretório \MQL5\Include\WIN_API. Você é livre para mudar este link, dependendo de suas preferências na organização do trabalho com arquivos incluídos em conformidade com a documentação.

//+------------------------------------------------------------------+
//|                                            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 ver, a variável de cadeia path contém o caminho para a pasta localizada dois níveis acima do diretório padrão do terminal executando, e nós obtemos (se a opção não é usada /portable) o caminho para o diretório que contém os dados personalizados de todos os terminais de cliente do usuário.

O leitor atento dirá que fazemos movimentos extra, uma vez que basta subir bastante um nível para estar no diretório correto. Sim, mas, se o que se pretende é navegar para outro diretório, por exemplo: Crashes ou Tester? Para nosso exemplo, é instrutivo.

Voltamos para o código do exemplo.

/---    
   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(); 
//---    

Criando uma instância da classe, obtemos na variável total o número de itens (arquivos ou subdiretórios). Após organizar o ciclo, imprimimos uma lista de diretórios dos terminais (ignorando os diretórios gerais). Ilustramos o acesso aos dados da instância usando o acesso à cópia de uma classe funcional de dados de classe 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();  

No exemplo de impressão de parte do conteúdo do diretório (é usada a seleção de itens que começam com a letra M) são demonstrados outras técnicas para trabalhar com os itens da classe.

E na continuação, parte do código onde nós verificamos a disponibilidade de um arquivo específico e sabemos seu comprimento.

//---  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();              

Completamos o script de teste usando o exemplo de utilização do link para a instância da classe de armazenamento do elemento de conteúdo do diretório:

  //--- 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. -----------------------"); } //+------------------------------------------------------------------+

Eu não tenho nenhuma dúvida de que a maioria dos leitores tiraram proveito desta forma de acesso aos dados de classe no seu trabalho.

Para descriptografar atributos, podem ser exigidas informações adicionais:

FILE_ATTRIBUTE_ARCHIVE 32 (0x20) 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 exemplo e a própria classe sejam úteis para você, eu, por minha vez, não estou muito cansado com minhas explicações ...;)

Divirtam-se!

Traduzido do russo pela MetaQuotes Ltd.
Publicação original: https://www.mql5.com/ru/code/17623

HistoryPositionInfo HistoryPositionInfo

Retorna o lucro da posição em pontos com base no histórico de negociação.

Dsl - macd Dsl - macd

Indicador MACD na versão da linha de sinal intermitente (DSL).

XRSXCandleKeltnerPluse XRSXCandleKeltnerPluse

Indicador XRSXCandleKeltner com possibilidade de detecção do rompimento

XCCXCandleKeltnerPluse XCCXCandleKeltnerPluse

Indicador XCCXCandleKeltner com possibilidade de detecção do rompimento