FileReadNumber

A função lê do arquivo CSV uma string a partir da posição atual até um separador (ou até o fim de uma seqüência de texto) e converte a string de leitura para um valor do tipo double.

double  FileReadNumber(
   int  file_handle    // Manipular arquivo
   );

Parâmetros

file_handle

[in]  Descritor de arquivo retornado pelo FileOpen().

Valor do Retorno

Valor de tipo double.

Exemplo (o arquivo obtido durante a execução de um exemplo para a função FileWriteString é usado aqui)

//+------------------------------------------------------------------+
//|                                          Demo_FileReadNumber.mq5 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                              https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots   1
//---- Plotar Etiqueta1
#property indicator_label1  "Sobre-compra & Sobre-venda"
#property indicator_type1   DRAW_COLOR_BARS
#property indicator_color1  clrRedclrBlue
#property indicator_style1  STYLE_SOLID
#property indicator_width1  2
//--- paramêtros para leitura de dados
input string InpFileName="RSI.csv";   // nome do arquivo
input string InpDirectoryName="Data"// nome do diretório
//--- buffers do indicador
double   open_buff[];
double   high_buff[];
double   low_buff[];
double   close_buff[];
double   color_buff[];
//--- variáveis sobre-comprado
int      ovb_ind=0;
int      ovb_size=0;
datetime ovb_time[];
//--- variáveis sobre-vendido
int      ovs_ind=0;
int      ovs_size=0;
datetime ovs_time[];
//+------------------------------------------------------------------+
//| Função de inicialização do indicador customizado                 |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- variáveis de tamanhos de array por padrão
   int ovb_def_size=100;
   int ovs_def_size=100;
//--- alocar memória para arrays
   ArrayResize(ovb_time,ovb_def_size);
   ArrayResize(ovs_time,ovs_def_size);
//--- abre o arquivo
   ResetLastError();
   int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV|FILE_ANSI);
   if(file_handle!=INVALID_HANDLE)
     {
      PrintFormat("%s arquivo está disponível para leitura",InpFileName);
      PrintFormat("Caminho do arquivo: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
      double value;
      //--- ler dados de um arquivo
      while(!FileIsEnding(file_handle))
        {
         //--- ler o primeiro valor na string
         value=FileReadNumber(file_handle);
         //--- ler diferentes arrays de acordo com o resultado da função
         if(value>=70)
            ReadData(file_handle,ovb_time,ovb_size,ovb_def_size);
         else
            ReadData(file_handle,ovs_time,ovs_size,ovs_def_size);
        }
      //--- fechar o arquivo
      FileClose(file_handle);
      PrintFormat("Os dados são escritos, %s arquivo esta fechado",InpFileName);
     }
   else
     {
      PrintFormat("Falha para abrir %s arquivo, Código de erro = %d",InpFileName,GetLastError());
      return(INIT_FAILED);
     }
//--- ligando as arrays
   SetIndexBuffer(0,open_buff,INDICATOR_DATA);
   SetIndexBuffer(1,high_buff,INDICATOR_DATA);
   SetIndexBuffer(2,low_buff,INDICATOR_DATA);
   SetIndexBuffer(3,close_buff,INDICATOR_DATA);
   SetIndexBuffer(4,color_buff,INDICATOR_COLOR_INDEX);
//---- definir os valores dos indicadores que não serão visíveis no gráfico
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Ler dados do arquivo da string                                   |
//+------------------------------------------------------------------+
void ReadData(const int file_handle,datetime &arr[],int &size,int &def_size)
  {
   bool flag=false;
//--- é alcançada a leitura até o final da string ou do arquivo
   while(!FileIsLineEnding(file_handle) && !FileIsEnding(file_handle))
     {
      //--- deslocar o transporte após a leitura do número
      if(flag)
         FileReadNumber(file_handle);
      //--- armazenar a data atual
      arr[size]=FileReadDatetime(file_handle);
      size++;
      //--- aumentar tamanho da array, se necessário
      if(size==def_size)
        {
         def_size+=100;
         ArrayResize(arr,def_size);
        }
      //--- passar despercebido a primeira iteração
      flag=true;
     }
  }
//+------------------------------------------------------------------+
//| Função de iteração do indicador customizado                      |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   ArraySetAsSeries(time,false);
   ArraySetAsSeries(open,false);
   ArraySetAsSeries(high,false);
   ArraySetAsSeries(low,false);
   ArraySetAsSeries(close,false);
//---o loop para as barras que ainda não foram manipuladas
   for(int i=prev_calculated;i<rates_total;i++)
     {
      //--- 0 por padrão
      open_buff[i]=0;
      high_buff[i]=0;
      low_buff[i]=0;
      close_buff[i]=0;
      color_buff[i]=0;
      //--- verificar se qualquer data continua presente
      if(ovb_ind<ovb_size)
         for(int j=ovb_ind;j<ovb_size;j++)
           {
            //--- se as datas coincidem, a barra está na zona de sobre-compra
            if(time[i]==ovb_time[j])
              {
               open_buff[i]=open[i];
               high_buff[i]=high[i];
               low_buff[i]=low[i];
               close_buff[i]=close[i];
               //--- 0 - cor vermelha
               color_buff[i]=0;
               //--- aumentar o contador
               ovb_ind=j+1;
               break;
              }
           }
      //--- verificar se todos os dados continuam a existir
      if(ovs_ind<ovs_size)
         for(int j=ovs_ind;j<ovs_size;j++)
           {
            //--- se as datas coincidem, a barra está na zona de sobre-venda
            if(time[i]==ovs_time[j])
              {
               open_buff[i]=open[i];
               high_buff[i]=high[i];
               low_buff[i]=low[i];
               close_buff[i]=close[i];
               //--- 1 - cor azul
               color_buff[i]=1;
               //--- aumentar o contador
               ovs_ind=j+1;
               break;
              }
           }
     }
//--- valor retorno de prev_calculated para a próxima chamada
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Manipulador de eventos ChartEvent                                |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
                  const long &lparam,
                  const double &dparam,
                  const string &sparam
                  )
  {
//---alterar a largura indicador de acordo com a escala
   if(ChartGetInteger(0,CHART_SCALE)>3)
      PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
   else
      PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
  }

Também Veja

FileWriteString