FileFindFirst
この関数は指定されたフィルタに基づいてディレクトリ内のファイルまたはサブディレクトリの検索を開始します。
long FileFindFirst(
const string file_filter,
string& returned_filename,
int common_flag=0
);
|
パラメータ
file_filter
[in] 検索フィルタ。ファイル検索に使用される、\Files ディレクトリに相対したサブディレクトリ(またはネストされたサブディレクトリのシーケンス)が指定されます。
returned_filename
[out] 戻されたパラメータ。成功の場合には、最初に見つかったファイルまたはサブディレクトリの名称が配置されます。拡張子を含んだファイル名のみが返されます。ディレクトリ及びサブディレクトリは検索フィルタに含まれている場合でも結果に含まれません。
common_flag
[in] ファイルの場所を決めるフラグ。common_flag = FILE_COMMON の場合、ファイルは全てのクライアント端末の共有フォルダ \Terminal\Common\Files 内に存在します。その他の場合、ファイルはローカルフォルダに存在します。
戻り値
注意事項
例:
//— スクリプト起動時に入力パラメータウィンドウを表示する
#property script_show_inputs
//— フィルタ
input string InpFilter=”Dir1\\*”;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string file_name;
string int_dir=””;
int i=1,pos=0,last_pos=-1;
//— 最後のバックスラッシュを探す
while(!IsStopped())
{
pos=StringFind(InpFilter,”\\”,pos+1);
if(pos>=0)
last_pos=pos;
else
break;
}
//— フィルタにフォルダ名が含まれる
if(last_pos>=0)
int_dir=StringSubstr(InpFilter,0,last_pos+1);
//— ローカルフォルダのルートで検索ハンドルを取得する
long search_handle=FileFindFirst(InpFilter,file_name);
//— FileFindFirst() の実行が成功したかをチェックする
if(search_handle!=INVALID_HANDLE)
{
//— 渡された文字列がファイル名かディレクトリ名かをループでチェックする
do
{
ResetLastError();
//— ファイルの場合、関数が true を返し、ディレクトリの場合 ERR_FILE_IS_DIRECTORY エラーを返す
FileIsExist(int_dir+file_name);
PrintFormat(“%d : %s name = %s”,i,GetLastError()==ERR_FILE_IS_DIRECTORY ?”Directory” : “File”,file_name);
i++;
}
while(FileFindNext(search_handle,file_name));
//— 検索ハンドルを閉じる
FileFindClose(search_handle);
}
else
Print(“Files not found!”);
}
|
参照
FileFindNext、FileFindClose
FileFindNext
この関数は FileFindFirst() 関数で始めた検索を続けます。
bool FileFindNext(
long search_handle,
string& returned_filename
);
|
パラメータ
search_handle
[in] FileFindFirst() で取得される検索ハンドル
returned_filename
[out] 次に見つかったファイルまたはサブディレクトリの名称拡張子を含んだファイル名のみが返されます。ディレクトリ及びサブディレクトリは検索フィルタに含まれている場合でも結果に含まれません。
戻り値
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— フィルタ
input string InpFilter=“*”;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string file_name;
int i=1;
//— ローカルフォルダのルートで検索ハンドルを受け取る
long search_handle=FileFindFirst(InpFilter,file_name);
//— FileFindFirst() の実行が成功したかをチェックする
if(search_handle!=INVALID_HANDLE)
{
//— 渡された文字列がファイル名かディレクトリ名かをループでチェックする
do
{
ResetLastError();
//— ファイルであれば trueを返し、ディレクトリであれば ERR_FILE_IS_DIRECTORY エラーを生成する
FileIsExist(file_name);
PrintFormat(“%d : %s name = %s”,i,GetLastError()==ERR_FILE_IS_DIRECTORY ? “Directory” : “File”,file_name);
i++;
}
while(FileFindNext(search_handle,file_name));
//— 検索ハンドルを閉じる
FileFindClose(search_handle);
}
else
Print(“Files not found!”);
}
|
参照
FileFindFirst、FileFindClose
FileFindClose
この関数は検索ハンドルを閉じます。
void FileFindClose(
long search_handle
);
|
パラメータ
search_handle
[in] FileFindFirst() で取得される検索ハンドル
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— フィルタ
input string InpFilter=“*”;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string file_name;
int i=1;
//— ローカルフォルダのルートで検索ハンドルを受け取る
long search_handle=FileFindFirst(InpFilter,file_name);
//— FileFindFirst() の実行が成功したかをチェックする
if(search_handle!=INVALID_HANDLE)
{
//— 渡された文字列がファイル名かディレクトリ名かをループでチェックする
do
{
ResetLastError();
//— ファイルであれば trueを返し、ディレクトリであればエラーを生成する
FileIsExist(file_name);
PrintFormat(“%d : %s name = %s”,i,GetLastError()==5018 ? “Directory” : “File”,file_name);
i++;
}
while(FileFindNext(search_handle,file_name));
//— 検索ハンドルを閉じる
FileFindClose(search_handle);
}
else
Print(“Files not found!”);
}
|
参照
FileFindFirst、FileFindNext
FileIsExist
ファイルの存在をチェックします。
bool FileIsExist(
const string file_name,
int common_flag=0
);
|
パラメータ
file_name
[in] チェックされているファイルの名称
common_flag=0
[in] ファイルの場所を決めるフラグ。common_flag = FILE_COMMON の場合、ファイルは全てのクライアント端末の共有フォルダ \Terminal\Common\Files 内に存在します。その他の場合、ファイルはローカルフォルダに存在します。
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 古いファイルの日付
input datetime InpFilesDate=D’2013.01.01 00:00′;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string file_name; // ファイル名を格納する変数
string filter=“*.txt”; // ファイル検索フィルタ
datetime create_date; // ファイル作成日
string files[]; // ファイル名のリスト
int def_size=25; // デフォルトの配列サイズ
int size=0; // ファイル数
//— 配列へのメモリ追加
ArrayResize(files,def_size);
//— ローカルフォルダのルートで検索ハンドルを受け取る
long search_handle=FileFindFirst(filter,file_name);
//— FileFindFirst() の実行が成功したかをチェックする
if(search_handle!=INVALID_HANDLE)
{
//— ループでファイルを検索する
do
{
files[size]=file_name;
//— 配列サイズを増やす
size++;
if(size==def_size)
{
def_size+=25;
ArrayResize(files,def_size);
}
//— エラー値をリセットする
ResetLastError();
//— 作成日を受け取る
create_date=(datetime)FileGetInteger(file_name,FILE_CREATE_DATE,false);
//— ファイルが古いかをチェックする
if(create_date<InpFilesDate)
{
PrintFormat(“%s file deleted!”,file_name);
//— 古いファイルを削除する
FileDelete(file_name);
}
}
while(FileFindNext(search_handle,file_name));
//— 検索ハンドルを閉じる
FileFindClose(search_handle);
}
else
{
Print(“Files not found!”);
return;
}
//— 何のファイルが残っているかをチェックする
PrintFormat(“Results:”);
for(int i=0;i<size;i++)
{
if(FileIsExist(files[i]))
PrintFormat(“%s file exists!”,files[i]);
else
PrintFormat(“%s file deleted!”,files[i]);
}
}
|
参照
FileFindFirst
FileOpen
この関数は、指定された名称とフラグでファイルを開きます。
int FileOpen(
string file_name,
int open_flags,
short delimiter=’\t’,
uint codepage=CP_ACP
);
|
パラメータ
file_name
[in] ファイルの名称はサブフォルダを含むことが出来ます。ファイルが書き込み用に開かれている場合は、存在しないサブフォルダは作成されます。
open_flags
[in] ファイル操作のモードを決めるフラグの組み合わせフラグは次の通りです。
FILE_READ – ファイルが読み込みのために開かれる
FILE_WRITE – ファイルが書き込みのために開かれる
FILE_BIN – バイナリ読み書きモード(文字列から/への変換はなし)
FILE_CSV – csv ファイル(unicode または ansi 文字列への変換され区切り文字で区切られる)
FILE_TXT – 単純なテキストファイル( csv と同じだが区切り文字がない)
FILE_ANSI – ANSI 文字列( 1 バイト文字)
FILE_UNICODE – UNICODE 文字列(2 バイト文字)
FILE_SHARE_READ – 複数プログラムから読み込まれる
FILE_SHARE_WRITE – 複数プログラムから書き込まれる
FILE_COMMON – 全てのクライエント端末に共通なファイルの位置( \Terminal\Common\Files )
delimiter=’\t’
[in] txt または csv ファイルでセパレータとして使用される値。csv ファイルのデリミタが指定されていない場合、デフォルトはタブです。txt ファイルのデリミタが指定されていない場合、セパレータは使用されません。セパレータが明らかに 0 に設定されている場合、セパレータは何も使用されません。
codepage=CP_ACP
[in] コードページの値。よく使用される コードページ では定数が提供されています。
戻り値
注意事項
- パイプ名は文字列で「\\servername\pipe\pipename」の様な外観を持つべきです。ここで servername はネットワーク内のサーバ名でpipename はパイプ名です。パイプが同じコンピュータ上で使用されている場合はサーバ名は省略出来ますが「\\.\pipe\pipename」のように点を挿入する必要があります。パイプに接続しようとしているクライアントはその名称を知っているべきです。
- FileFlush() 及び FileSeek() は、パイプから読み込み、それへ書き込みという一連の動作の間に、ファイルの先頭に呼び出す必要があります。
例:
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
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(“Failed to open the file by the absolute path “);
Print(“Error code “,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(“Operation FileOpen failed, error “,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(“The file must be created in the folder “+terminal_data_path+“\\”+subfolder);
}
else Print(“File open failed, error “,GetLastError());
}
|
参照
コードページの利用、FileFindFirst、FolderCreate、ファイルを開く際のフラグ
FileClose
FileOpen() で既に開いたファイルを閉じます。
void FileClose(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string InpFileName=“file.txt”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
input int InpEncodingType=FILE_ANSI; // ANSI=32 または UNICODE=64
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— 使用するファイルへのパスを出力する
PrintFormat(“Working %s\\Files\\ folder”,TerminalInfoString(TERMINAL_DATA_PATH));
//— エラー値をリセットする
ResetLastError();
//— ファイルを読み込みのために開く(ファイルが存在しない場合、エラーが発生する)
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//— ファイルの内容を出力
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
//— ファイルを閉じる
FileClose(file_handle);
}
else
PrintFormat(“Error, code = %d”,GetLastError());
}
|
FileCopy
この関数は、ファイルをローカルまたは共有フォルダから別のファイルに複製します。
bool FileCopy(
const string src_file_name,
int common_flag,
const string dst_file_name,
int mode_flags
);
|
パラメータ
src_file_name
[in] 複製するファイルの名称
common_flag
[in] ファイルの場所を決めるフラグ。common_flag = FILE_COMMON の場合、ファイルは全てのクライアント端末の共有フォルダ \Terminal\Common\Files 内に存在します。その他の場合、ファイルはローカルフォルダに存在します(例えばcommon_flag=0)。
dst_file_name
[in] 結果ファイル名
mode_flags
[in] アクセスフラグ。パラメータは FILE_REWRITE 及び/または FILE_COMMON の 2 つのフラグのみを含むことができ、他のフラグは無視されます。宇ファイルが既存し FILE_REWRITE フラグが指定されていない場合、ファイルは書き換えされず、関数は false を返します。
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string InpSrc=“source.txt”; // ソース
input string InpDst=“destination.txt”; // コピー
input int InpEncodingType=FILE_ANSI; // ANSI=32 または UNICODE=64
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— ソースの内容を表示する(存在が必要)
if(!FileDisplay(InpSrc))
return;
//— コピーファイルが既に存在するかどうかを確認(作成されない場合がある)
if(!FileDisplay(InpDst))
{
//— コピーファイルが既に存在しないので FILE_REWRITE フラグなしで複製する(正しいやり方)
if(FileCopy(InpSrc,0,InpDst,0))
Print(“File is copied!”);
else
Print(“File is not copied!”);
}
else
{
//— コピーファイルが既に存在するので FILE_REWRITE フラグなしでのコピーを試みる(不正)
if(FileCopy(InpSrc,0,InpDst,0))
Print(“File is copied!”);
else
Print(“File is not copied!”);
//— InpDst file の内容は変わらない
FileDisplay(InpDst);
//— FILE_REWRITE フラグで再コピー(ファイルが既存する場合の正しいやり方)
if(FileCopy(InpSrc,0,InpDst,FILE_REWRITE))
Print(“File is copied!”);
else
&nbsnbsp; Print(“File is not copied!”);
}
//— InpSrc ファイルコピーを受け取る
FileDisplay(InpDst);
}
//+——————————————————————+
//| ファイルの内容を読む |
//+——————————————————————+
bool FileDisplay(const string file_name)
{
//— エラー値をリセットする
ResetLastError();
//— ファイルを開く
int file_handle=FileOpen(file_name,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//— ファイルの内容をループで表示する
Print(“+———————+”);
PrintFormat(“File name = %s”,file_name);
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
Print(“+———————+”);
//— ファイルを閉じる
FileClose(file_handle);
return(true);
}
//— ファイルを開くのに失敗
PrintFormat(“%s is not opened, error = %d”,file_name,GetLastError());
return(false);
}
|
FileDelete
指定されたクライアント端末のローカルフォルダ内のファイルを削除します。
bool FileDelete(
const string file_name,
int common_flag=0
);
|
パラメータ
file_name
[in] ファイル名
common_flag=0
[in] ファイルの場所を決定するフラグcommon_flag = FILE_COMMON の場合、ファイルは全てのクライアント端末の共有フォルダ \Terminal\Common\Files 内に存在します。その他の場合、ファイルはローカルフォルダに存在します。
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 古いファイルの日付
input datetime InpFilesDate=D’2013.01.01 00:00′;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string file_name; // ファイル名を格納する変数
string filter=“*.txt”; // ファイル検索フィルタ
datetime create_date; // ファイル作成日
string files[]; // ファイル名のリスト
int def_size=25; // デフォルトの配列サイズ
int size=0; // ファイル数
//— 配列へのメモリ追加
ArrayResize(files,def_size);
//— ローカルフォルダのルートで検索ハンドルを受け取る
long search_handle=FileFindFirst(filter,file_name);
//— FileFindFirst() の実行が成功したかをチェックする
if(search_handle!=INVALID_HANDLE)
{
//— ループでファイルを検索する
do
{
files[size]=file_name;
//— 配列サイズを増やす
size++;
if(size==def_size)
{
def_size+=25;
ArrayResize(files,def_size);
}
//— エラー値をリセットする
ResetLastError();
//— 作成日を受け取る
create_date=(datetime)FileGetInteger(file_name,FILE_CREATE_DATE,false);
//— ファイルが古いかをチェックする
if(create_date<InpFilesDate)
{
PrintFormat(“%s file deleted!”,file_name);
//— 古いファイルを削除する
FileDelete(file_name);
}
}
while(FileFindNext(search_handle,file_name));
//— 検索ハンドルを閉じる
FileFindClose(search_handle);
}
else
{
Print(“Files not found!”);
return;
}
//— 何のファイルが残っているかをチェックする
PrintFormat(“Results:”);
for(int i=0;i<size;i++)
{
if(FileIsExist(files[i]))
PrintFormat(“%s file exists!”,files[i]);
else
PrintFormat(“%s file deleted!”,files[i]);
}
}
|
FileMove
ファイルをローカルまたは共有フォルダから別のフォルダに移動します。
bool FileMove(
const string src_file_name,
int common_flag,
const string dst_file_name,
int mode_flags
);
|
パラメータ
src_file_name
[in] 移動/名称変更されるファイル名
common_flag
[in] ファイルの場所を決めるフラグ。common_flag = FILE_COMMON の場合、ファイルは全てのクライアント端末の共有フォルダ \Terminal\Common\Files 内に存在します。その他の場合、ファイルはローカルフォルダに存在します(common_flag=0)。
dst_file_name
[in] 操作後のファイル名
mode_flags
[in] アクセスフラグ。パラメータは FILE_REWRITE 及び/または FILE_COMMON の 2 つのフラグのみを含むことができ、他のフラグは無視されます。宇ファイルが既存し FILE_REWRITE フラグが指定されていない場合、ファイルは書き換えされず、関数は false を返します。
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string InpSrcName=“data.txt”;
input string InpDstName=“newdata.txt”;
input string InpSrcDirectory=“SomeFolder”;
input string InpDstDirectory=“OtherFolder”;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string local=TerminalInfoString(TERMINAL_DATA_PATH);
string common=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
//— ファイルパスを受け取る
string src_path;
string dst_path;
StringConcatenate(src_path,InpSrcDirectory,“//”,InpSrcName);
StringConcatenate(dst_path,InpDstDirectory,“//”,InpDstName);
//— ソースファイルが存在するかをチェック(存在しなければ終了する)
if(FileIsExist(src_path))
PrintFormat(“%s file exists in the %s\\Files\\%s folder”,InpSrcName,local,InpSrcDirectory);
else
{
PrintFormat(“Error, %s source file not found”,InpSrcName);
return;
}
//— ターゲットファイルが既存するかをチェックする
if(FileIsExist(dst_path,FILE_COMMON))
{
PrintFormat(“%s file exists in the %s\\Files\\%s folder”,InpDstName,common,InpDstDirectory);
//— ファイルが存在するので移動は FILE_REWRITE フラグで行うべき
ResetLastError();
if(FileMove(src_path,0,dst_path,FILE_COMMON|FILE_REWRITE))
PrintFormat(“%s file moved”,InpSrcName);
else
PrintFormat(“Error! Code = %d”,GetLastError());
}
else
{
PrintFormat(“%s file does not exist in the %s\\Files\\%s folder”,InpDstName,common,InpDstDirectory);
//— ファイルが存在しないので移動は FILE_REWRITE フラグなしで行うべき
ResetLastError();
if(FileMove(src_path,0,dst_path,FILE_COMMON))
PrintFormat(“%s file moved”,InpSrcName);
else
PrintFormat(“Error! Code = %d”,GetLastError());
}
//— ファイルが移動されたのでみてみる
if(FileIsExist(dst_path,FILE_COMMON) && !FileIsExist(src_path,0))
Print(“Success!”);
else
Print(“Error!”);
}
|
参照
FileIsExist
FileFlush
入力/出力ファイルのバッファに残っている全てのデータをディスクに書き込みます。
void FileFlush(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 書き込みするファイル名
input string InpFileName=“example.csv”; // ファイル名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— エラー値をリセットする
ResetLastError();
//— ファイルを開く
int file_handle=FileOpen(InpFileName,FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
//— データをファイルに書く
for(int i=0;i<1000;i++)
{
//— write 関数を呼び出す
FileWrite(file_handle,TimeCurrent(),SymbolInfoDouble(Symbol(),SYMBOL_BID),SymbolInfoDouble(Symbol(),SYMBOL_ASK));
//— 各128番目の繰り返しでディスク上のデータを保存する
if((i & 127)==127)
{
//— データはファイルに配置され、重大なエラーの場合に失われることはない
FileFlush(file_handle);
PrintFormat(“i = %d, OK”,i);
}
//— 0.01 秒の休止
Sleep(10);
}
//— ファイルを閉じる
FileClose(file_handle);
}
else
PrintFormat(“Error, code = %d”,GetLastError());
}
|
参照
FileClose
FileGetInteger
ファイルの整数プロパティを取得します。この関数には 2 つのバージョンがあります。
1. ファイルハンドルでプロパティを取得
long FileGetInteger(
int file_handle,
ENUM_FILE_PROPERTY_INTEGER property_id
);
|
2. ファイル名でプロパティを取得
long FileGetInteger(
const string file_name,
ENUM_FILE_PROPERTY_INTEGER property_id,
bool common_folder=false
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
file_name
[in] ファイル名
property_id
[in] ファイルプロパティ識別子値は ENUM_FILE_PROPERTY_INTEGER 列挙のいずれかです。関数の2 番目のバージョンが使用されている場合は以下のプロパティ値のみを受け取ることが出来ます。 FILE_EXISTS、FILE_CREATE_DATE、FILE_MODIFY_DATE、FILE_ACCESS_DATE 及び FILE_SIZE。
common_folder=false
[in] ファイルの位置にポイントするパラメータが false の場合、端末データフォルダがみられます。さもなければ、ファイルは全てのクライアント端末の共有フォルダ \Terminal\Common\Files (FILE_COMMON)に位置すると想定されます。
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string InpFileName=“data.csv”;
input string InpDirectoryName=“SomeFolder”;
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string path=InpDirectoryName+“//”+InpFileName;
long l=0;
//— ファイルを開く
ResetLastError();
int handle=FileOpen(path,FILE_READ|FILE_CSV);
if(handle!=INVALID_HANDLE)
{
//— ファイルの情報を全て出力する
Print(InpFileName,” file info:”);
FileInfo(handle,FILE_EXISTS,l,“bool”);
FileInfo(handle,FILE_CREATE_DATE,l,“date”);
FileInfo(handle,FILE_MODIFY_DATE,l,“date”);
FileInfo(handle,FILE_ACCESS_DATE,l,“date”);
FileInfo(handle,FILE_SIZE,l,“other”);
FileInfo(handle,FILE_POSITION,l,“other”);
FileInfo(handle,FILE_END,l,“bool”);
FileInfo(handle,FILE_IS_COMMON,l,“bool”);
FileInfo(handle,FILE_IS_TEXT,l,“bool”);
FileInfo(handle,FILE_IS_BINARY,l,“bool”);
FileInfo(handle,FILE_IS_CSV,l,“bool”);
FileInfo(handle,FILE_IS_ANSI,l,“bool”);
FileInfo(handle,FILE_IS_READABLE,l,“bool”);
FileInfo(handle,FILE_IS_WRITABLE,l,“bool”);
//— ファイルを閉じる
FileClose(handle);
}
else
PrintFormat(“%s file is not opened, ErrorCode = %d”,InpFileName,GetLastError());
}
//+——————————————————————+
//| ファイルプロパティ値を表示する |
//+——————————————————————+
void FileInfo(const int handle,const ENUM_FILE_PROPERTY_INTEGER id,
long l,const string type)
{
//— プロパティ値を受け取る
ResetLastError();
if((l=FileGetInteger(handle,id))!=-1)
{
//— 値を受け取ったので、正しいフォーマットで表示する
if(!StringCompare(type,“bool”))
Print(EnumToString(id),” = “,l ? “true” : “false”);
if(!StringCompare(type,“date”))
Print(EnumToString(id),” = “,(datetime)l);
if(!StringCompare(type,“other”))
Print(EnumToString(id),” = “,l);
}
else
Print(“Error, Code = “,GetLastError());
}
|
参照
ファイル操作、ファイルプロパティ
FileIsEnding
読み出し処理において、ファイルの終わりを定義します。
bool FileIsEnding(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string InpFileName=“file.txt”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
input int InpEncodingType=FILE_ANSI; // ANSI=32 または UNICODE=64
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— 使用するファイルへのパスを出力する
PrintFormat(“Working %s\\Files\\ folder”,TerminalInfoString(TERMINAL_DATA_PATH));
//— エラー値をリセットする
ResetLastError();
//— ファイルを読み込みのために開く(ファイルが存在しない場合、エラーが発生する)
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//— ファイルの内容を出力
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
//— ファイルを閉じる
FileClose(file_handle);
}
else
PrintFormat(“Error, code = %d”,GetLastError());
}
|
FileIsLineEnding
読み出し処理において、テキストファイルの行の終わりを定義します。
bool FileIsLineEnding(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
例 ( FileWriteString 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileIsLineEnding.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
//—- Label1 をプロットする
#property indicator_label1 “Overbought & Oversold”
#property indicator_type1 DRAW_COLOR_BARS
#property indicator_color1 clrRed, clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
//— データ読み込みのパラメータ
input string InpFileName=“RSI.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— 指標バッファ
double open_buff[];
double high_buff[];
double low_buff[];
double close_buff[];
double color_buff[];
//— 買いすぎ変数
int ovb_ind=0;
int ovb_size=0;
datetime ovb_time[];
//— 売りすぎ変数
int ovs_ind=0;
int ovs_size=0;
datetime ovs_time[];
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
//— デフォルトの配列サイズの変数
int ovb_def_size=100;
int ovs_def_size=100;
//— 変数にメモリを割り当てる
ArrayResize(ovb_time,ovb_def_size);
ArrayResize(ovs_time,ovs_def_size);
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_CSV|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
double value;
//— ファイルからデータを読む
while(!FileIsEnding(file_handle))
{
//— 文字列の初めの値を読む
value=FileReadNumber(file_handle);
//— 関数の結果に応じて異なる配列を読む
if(value>=70)
ReadData(file_handle,ovb_time,ovb_size,ovb_def_size);
else
ReadData(file_handle,ovs_time,ovs_size,ovs_def_size);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列の結合
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);
//—- チャートでは表示されない指標値を設定する
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| ファイルの文字列データを読む |
//+——————————————————————+
void ReadData(const int file_handle,datetime &arr[],int &size,int &def_size)
{
bool flag=false;
//— 文字列の終わりかファイルの終わりまで読む
while(!FileIsLineEnding(file_handle) && !FileIsEnding(file_handle))
{
//— 数字を読んで位置をシフトする
if(flag)
FileReadNumber(file_handle);
//— 現在の日付を格納する
arr[size]=FileReadDatetime(file_handle);
size++;
//— 必要な場合配列サイズを増やす
if(size==def_size)
{
def_size+=100;
ArrayResize(arr,def_size);
}
//— 最初の反復をすり抜ける
flag=true;
}
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
open_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
close_buff[i]=0;
color_buff[i]=0;
//— まだデータがあるかをチェック
if(ovb_ind<ovb_size)
for(int j=ovb_ind;j<ovb_size;j++)
{
//— 日付が一致した場合、バーが買われ過ぎ領域にある
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 – 赤
color_buff[i]=0;
//— カウンタを増加する
ovb_ind=j+1;
break;
}
}
//— データがまだあるかをチェック
if(ovs_ind<ovs_size)
for(int j=ovs_ind;j<ovs_size;j++)
{
//— 日付が一致した場合、バーが売られ過ぎ領域にある
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 – 青
color_buff[i]=1;
//— カウンタを増加する
ovs_ind=j+1;
break;
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
//+——————————————————————+
//| ChartEvent イベントハンドラ |
//+——————————————————————+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam
)
{
//— スケールに合わせて指標の幅を変更する
if(ChartGetInteger(0,CHART_SCALE)>3)
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
else
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
}
|
参照
FileWriteString
FileReadArray
string 以外の任意型のBIN 型配列(文字列を含まない構造体の配列、動的配列)のファイルから読み込みを行います。
uint FileReadArray(
int file_handle,
void& array[],
int start=0,
int count=WHOLE_ARRAY
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
array[]
[out] データが読み込まれる配列
start=0
[in] 配列に書く開始位置
count=WHOLE_ARRAY
[in] 読まれる要素数。デフォルトでは配列全体が読まれます(count=WHOLE_ARRAY)。
戻り値
注意事項
例 (FileWriteArray 関数の例の実行によって取得されたファイルが使用されます)
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string InpFileName=“data.bin”;
input string InpDirectoryName=“SomeFolder”;
//+——————————————————————+
//| 価格データを格納する構造体 |
//+——————————————————————+
struct prices
{
datetime date; // 日付
double bid; // 売値
double ask; // 買値
};
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— 構造体配列
prices arr[];
//— ファイルパス
string path=InpDirectoryName+“//”+InpFileName;
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(path,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
//— ファイルのデータを全部配列に読見込む
FileReadArray(file_handle,arr);
//— 配列サイズを受け取る
int size=ArraySize(arr);
//— 配列からデータを出力する
for(int i=0;i<size;i++)
Print(“Date = “,arr[i].date,” Bid = “,arr[i].bid,” Ask = “,arr[i].ask);
Print(“Total data = “,size);
//— ファイルを閉じる
FileClose(file_handle);
}
else
Print(“File open failed, error “,GetLastError());
}
|
参照
変数、FileWriteArray
FileReadBool
CSV 形式のファイルの現在位置から区切り文字までの文字列(またはテキスト行の終わり)を読み込み、読んだ文字列を bool 型の値に変換します。
bool FileReadBool(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
例 (FileWrite 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadBool.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 2
#property indicator_plots 2
//—- Label1 をプロットする
#property indicator_label1 “UpSignal”
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 4
//—- Label2 をプロットする
#property indicator_label2 “DownSignal”
#property indicator_type2 DRAW_ARROW
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 4
//— データ読み込みのパラメータ
input string InpFileName=“MACD.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— グローバル変数
int ind=0; // インデックス
double upbuff[]; // 上向き矢印の指標バッファ
double downbuff[]; // 下向き矢印の指標バッファ
bool sign_buff[]; // シグナル配列(true – 買、false – 売)
datetime time_buff[]; // シグナル到着時の配列
int size=0; // シグナル配列のサイズ
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is open for reading”,InpFileName);
//— 初めにシグナルの数を読む
size=(int)FileReadNumber(file_handle);
//— 配列へメモリを割り当てる
ArrayResize(sign_buff,size);
ArrayResize(time_buff,size);
//— ファイルからデータを読む
for(int i=0;i<size;i++)
{
//— 時間シグナル
time_buff[i]=FileReadDatetime(file_handle);
//— 値シグナル
sign_buff[i]=FileReadBool(file_handle);
}
//— ファイルを閉じる
FileClose(file_handle);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列の結合
SetIndexBuffer(0,upbuff,INDICATOR_DATA);
SetIndexBuffer(1,downbuff,INDICATOR_DATA);
//— PLOT_ARROW での描画のためにシンボルコードを設定
PlotIndexSetInteger(0,PLOT_ARROW,241);
PlotIndexSetInteger(1,PLOT_ARROW,242);
//—- チャートでは表示されない指標値を設定
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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(low,false);
ArraySetAsSeries(high,false);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
upbuff[i]=0;
downbuff[i]=0;
//— まだデータがあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//— 日付が同じならファイルの値を使用する
if(time[i]==time_buff[j])
{
//— シグナルに合わせて矢印を描画する
if(sign_buff[j])
upbuff[i]=high[i];
else
downbuff[i]=low[i];
//— カウンタを増加する
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
ブール型、FileWrite
FileReadDatetime
CSV 形式のファイルから、「YYYY.MM.DD HH:MM:SS」、「YYYY.MM.DD」または「HH:MM:SS」フォーマットの文字列を読み込みdatetime 型の値に変換します。
datetime FileReadDatetime(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
例 (FileWrite 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadDateTime.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 2
#property indicator_plots 2
//—- Label1 をプロットする
#property indicator_label1 “UpSignal”
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 4
//—- Label2 をプロットする
#property indicator_label2 “DownSignal”
#property indicator_type2 DRAW_ARROW
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 4
//— データ読み込みのパラメータ
input string InpFileName=“MACD.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— グローバル変数
int ind=0; // インデックス
double upbuff[]; // 上向き矢印の指標バッファ
double downbuff[]; // 下向き矢印の指標バッファ
bool sign_buff[]; // シグナル配列(true – 買、false – 売)
datetime time_buff[]; // シグナル到着時の配列
int size=0; // シグナル配列のサイズ
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is open for reading”,InpFileName);
//— 初めにシグナルの数を読む
size=(int)FileReadNumber(file_handle);
//— 配列へメモリを割り当てる
ArrayResize(sign_buff,size);
ArrayResize(time_buff,size);
//— ファイルからデータを読む
for(int i=0;i<size;i++)
{
//— 時間シグナル
time_buff[i]=FileReadDatetime(file_handle);
//— 値シグナル
sign_buff[i]=FileReadBool(file_handle);
}
//— ファイルを閉じる
FileClose(file_handle);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列の結合
SetIndexBuffer(0,upbuff,INDICATOR_DATA);
SetIndexBuffer(1,downbuff,INDICATOR_DATA);
//— PLOT_ARROW での描画のためにシンボルコードを設定
PlotIndexSetInteger(0,PLOT_ARROW,241);
PlotIndexSetInteger(1,PLOT_ARROW,242);
//—- チャートでは表示されない指標値を設定
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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(low,false);
ArraySetAsSeries(high,false);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
upbuff[i]=0;
downbuff[i]=0;
//— まだデータがあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//— 日付が同じならファイルの値を使用する
if(time[i]==time_buff[j])
{
//— シグナルに合わせて矢印を描画する
if(sign_buff[j])
upbuff[i]=high[i];
else
downbuff[i]=low[i];
//— カウンタを増加する
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
日付時刻型、StringToTime、TimeToString、FileWrite
FileReadDouble
バイナリファイルの現在位置から倍精度浮動小数点数(double)を読み込みます。
double FileReadDouble(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
注意事項
例 ( FileWriteDouble 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadDouble.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 1
#property indicator_plots 1
//—- Label1 をプロットする
#property indicator_label1 “MA”
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
#property indicator_separate_window
//— データ読みのパラメータ
input string InpFileName=“MA.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— グローバル変数
int ind=0;
int size=0;
double ma_buff[];
datetime time_buff[];
//— 指標バッファ
double buff[];
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 初めに、ファイルのデータ量を読み込む
size=(int)FileReadDouble(file_handle);
//— 配列へメモリを割り当てる
ArrayResize(ma_buff,size);
ArrayResize(time_buff,size);
//— ファイルからデータを読む
for(int i=0;i<size;i++)
{
time_buff[i]=(datetime)FileReadDouble(file_handle);
ma_buff[i]=FileReadDouble(file_handle);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列をインデックス0で指標バッファと結合する
SetIndexBuffer(0,buff,INDICATOR_DATA);
//—- チャートでは表示されない指標値を設定する
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
buff[i]=0;
//— データがまだあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//— 日付が同じならファイルの値を使用する
if(time[i]==time_buff[j])
{
buff[i]=ma_buff[j];
//— カウンタを増加する
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
浮動小数点数型(ダブル、フロート)、StringToDouble、DoubleToString、FileWriteDouble
FileReadFloat
バイナリファイルの現在位置から単精度浮動小数点数(float)を読み込みます。
float FileReadFloat(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
注意事項
例 (FileWriteFloat 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadFloat.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_separate_window
#property indicator_buffers 2
#property indicator_plots 1
//—- Label1 をプロットする
#property indicator_label1 “CloseLine”
#property indicator_type1 DRAW_COLOR_LINE
#property indicator_color1 clrRed,clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
//— データ読み込みのパラメータ
input string InpFileName=“Close.bin”; // file name
input string InpDirectoryName=“Data”; // ディレクトリ名
//— グローバル変数
int ind=0;
int size=0;
double close_buff[];
datetime time_buff[];
//— 指標バッファ
double buff[];
double color_buff[];
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
int def_size=100;
//— 配列へメモリを割り当てる
ArrayResize(close_buff,def_size);
ArrayResize(time_buff,def_size);
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— ファイルからデータを読む
while(!FileIsEnding(file_handle))
{
//— 時間と価格値を読む
time_buff[size]=(datetime)FileReadDouble(file_handle);
close_buff[size]=(double)FileReadFloat(file_handle);
size++;
//— オーバーフローしている場合は、配列のサイズを増やす
if(size==def_size)
{
def_size+=100;
ArrayResize(close_buff,def_size);
ArrayResize(time_buff,def_size);
}
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is read, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列と指標バッファを関連付ける
SetIndexBuffer(0,buff,INDICATOR_DATA);
SetIndexBuffer(1,color_buff,INDICATOR_COLOR_INDEX);
//—- チャートでは表示されない指標値を設定する
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
buff[i]=0;
color_buff[i]=0; // デフォルトでは赤
//— まだデータがあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//— 日付が同じならファイルの値を使用する
if(time[i]==time_buff[j])
{
//— 価格を受け取る
buff[i]=close_buff[j];
//— 現在の価格は以前の価格を超えた場合、色は青
if(buff[i-1]>buff[i])
color_buff[i]=1;
//— カウンタを増加する
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
浮動小数点数型(ダブル、フロート)、FileReadDouble、FileWriteFloat
FileReadInteger
この関数は、ファイルポインタの現在位置から、バイト単位で指定された長差に従って int、short または char 値を読み込みます。
int FileReadInteger(
int file_handle,
int size=INT_VALUE
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
size=INT_VALUE
[in] 読まれるべきバイト数(4 以下)。関数が char、short または int 型の値を読めるように、CHAR_VALUE=1、SHORT_VALUE=2 t及び INT_VALUE=4 と対応する定数が用意されています。
戻り値
注意事項
例 (FileWriteInteger 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadInteger.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 1
#property indicator_plots 1
//—- Label1 をプロットする
#property indicator_label1 “Trends”
#property indicator_type1 DRAW_SECTION
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//— データ読み込みのパラメータ
input string InpFileName=“Trend.bin”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— グローバル変数
int ind=0;
int size=0;
datetime time_buff[];
//— 指標バッファ
double buff[];
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
int def_size=100;
//— 配列へのメモリ追加
ArrayResize(time_buff,def_size);
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 追加の変数
int arr_size;
uchar arr[];
//— ファイルからデータを読む
while(!FileIsEnding(file_handle))
{
//— 時間を書くのに使用されるシンボルの数を見つける
arr_size=FileReadInteger(file_handle,INT_VALUE);
ArrayResize(arr,arr_size);
for(int i=0;i<arr_size;i++)
arr[i]=(char)FileReadInteger(file_handle,CHAR_VALUE);
//— 時間値を格納する
time_buff[size]=StringToTime(CharArrayToString(arr));
size++;
//— オーバーフローしている場合は、配列のサイズを増やす
if(size==def_size)
{
def_size+=100;
ArrayResize(time_buff,def_size);
}
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is read, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列と指標バッファを関連付ける
SetIndexBuffer(0,buff,INDICATOR_DATA);
//—- チャートでは表示されない指標値を設定する
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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(close,false);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
buff[i]=0;
//— まだデータがあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//— 日付が同じならファイルの値を使用する
if(time[i]==time_buff[j])
{
//— 価格を受け取る
buff[i]=close[i];
//— カウンタを増加する
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
IntegerToString、StringToInteger、整数型、FileWriteInteger
FileReadLong
この関数は、バイナリファイルのファイルポインタの現在位置から long 型( 8 バイト)の値を読み込みます。
long FileReadLong(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
例 (FileWriteLong 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadLong.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_buffers 1
#property indicator_plots 1
//—- Label1 をプロットする
#property indicator_label1 “Volume”
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrYellow
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
#property indicator_separate_window
//— データ読み込みのパラメータ
input string InpFileName=“Volume.bin”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— グローバル変数
int ind=0;
int size=0;
long volume_buff[];
datetime time_buff[];
//— 指標バッファ
double buff[];
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is open for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 初めに、ファイルのデータ量を読み込む
size=(int)FileReadLong(file_handle);
//— 配列へメモリを割り当てる
ArrayResize(volume_buff,size);
ArrayResize(time_buff,size);
//— ファイルからデータを読む
for(int i=0;i<size;i++)
{
time_buff[i]=(datetime)FileReadLong(file_handle);
volume_buff[i]=FileReadLong(file_handle);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is read, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列をインデックス0で指標バッファと結合するx
SetIndexBuffer(0,buff,INDICATOR_DATA);
//—- チャートで表示される指標値を設定する
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
buff[i]=0;
//— まだデータがあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//— 日付が同じならファイルの値を使用する
if(time[i]==time_buff[j])
{
buff[i]=(double)volume_buff[j];
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
整数型、FileReadInteger、FileWriteLong
FileReadNumber
CSV ファイルから、現在の位置から区切り文字までの文字列(またはテキスト行の終わり)を読み込み、読んだ文字列をdouble 型の値に変換します。
double FileReadNumber(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
例 ( FileWriteString 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| 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
//—- Label1 をプロットする
#property indicator_label1 “Overbought & Oversold”
#property indicator_type1 DRAW_COLOR_BARS
#property indicator_color1 clrRed, clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
//— データ読み込みのパラメータ
input string InpFileName=“RSI.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//— 指標バッファ
double open_buff[];
double high_buff[];
double low_buff[];
double close_buff[];
double color_buff[];
//— 買いすぎ変数
int ovb_ind=0;
int ovb_size=0;
datetime ovb_time[];
//— 売りすぎ変数
int ovs_ind=0;
int ovs_size=0;
datetime ovs_time[];
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
//— デフォルトの配列サイズの変数
int ovb_def_size=100;
int ovs_def_size=100;
//— 変数にメモリを割り当てる
ArrayResize(ovb_time,ovb_def_size);
ArrayResize(ovs_time,ovs_def_size);
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_CSV|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
double value;
//— ファイルからデータを読む
while(!FileIsEnding(file_handle))
{
//— 文字列の初めの値を読む
value=FileReadNumber(file_handle);
//— 関数の結果に応じて異なる配列を読む
if(value>=70)
ReadData(file_handle,ovb_time,ovb_size,ovb_def_size);
else
ReadData(file_handle,ovs_time,ovs_size,ovs_def_size);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 配列の結合
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);
//—- チャートでは表示されない指標値を設定する
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| ファイルの文字列データを読む |
//+——————————————————————+
void ReadData(const int file_handle,datetime &arr[],int &size,int &def_size)
{
bool flag=false;
//— 文字列の終わりかファイルの終わりまで読む
while(!FileIsLineEnding(file_handle) && !FileIsEnding(file_handle))
{
//— 数を読んだ後にキャリッジをシフトする
if(flag)
FileReadNumber(file_handle);
//— 現在の日付を格納する
arr[size]=FileReadDatetime(file_handle);
size++;
//— 必要な場合配列サイズを増やす
if(size==def_size)
{
def_size+=100;
ArrayResize(arr,def_size);
}
//— 最初の反復をすり抜ける
flag=true;
}
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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);
//— まだ処理されてないバーのループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
open_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
close_buff[i]=0;
color_buff[i]=0;
//— まだデータがあるかをチェック
if(ovb_ind<ovb_size)
for(int j=ovb_ind;j<ovb_size;j++)
{
//— 日付が一致した場合、バーが買われ過ぎ領域にある
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 – 赤
color_buff[i]=0;
//— カウンタを増加する
ovb_ind=j+1;
break;
}
}
//— データがまだあるかをチェック
if(ovs_ind<ovs_size)
for(int j=ovs_ind;j<ovs_size;j++)
{
//— 日付が一致した場合、バーが売られ過ぎ領域にある
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 – 青
color_buff[i]=1;
//— カウンタを増加する
ovs_ind=j+1;
break;
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
//+——————————————————————+
//| ChartEvent イベントハンドラ |
//+——————————————————————+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam
)
{
//— スケールに合わせて指標の幅を変更する
if(ChartGetInteger(0,CHART_SCALE)>3)
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,2);
else
PlotIndexSetInteger(0,PLOT_LINE_WIDTH,1);
}
|
参照
FileWriteString
FileReadString
この関数は、ファイルポインタの現在位置から文字列を読み込みます。
string FileReadString(
int file_handle,
int length=-1
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
length=-1
[in] 読まれる文字数
戻り値
注意事項
例 (FileWriteInteger 関数の例の実行によって取得されたファイルが使用されます)
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— データ読み込みのパラメータ
input string InpFileName=“Trend.bin”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_BIN|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 追加の変数
int str_size;
string str;
//— ファイルからデータを読む
while(!FileIsEnding(file_handle))
{
//— 時間を書くのに使用されるシンボルの数を見つける
str_size=FileReadInteger(file_handle,INT_VALUE);
//— 文字列を読む
str=FileReadString(file_handle,str_size);
//— 文字列を出力する
PrintFormat(str);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is read, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
String Type, Conversion Functions, FileWriteInteger
FileReadStruct
バイナリファイルのファイルポインタの現在位置から、パラメータとして渡される構造体にコンテンツを読み込みます。
uint FileReadStruct(
int file_handle,
const void& struct_object,
int size=-1
);
|
パラメータ
file_handle
[in] バイナリファイルのファイル記述子
struct_object
[out] 構造体オブジェクト構造体は文字列、動的配列 また 仮想関数を含むことは出来ません。
size=-1
[in] 読まれるバイト数サイズが無指定、または示された値が構造体のサイズよりも大きい場合は、指定された構造のサイズが使用されます。
戻り値
例 (FileWriteStruct 関数の例の実行によって取得されたファイルが使用されます)
//+——————————————————————+
//| Demo_FileReadStruct.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_separate_window
#property indicator_buffers 4
#property indicator_plots 1
//—- Label1 をプロットする
#property indicator_label1 “Candles”
#property indicator_type1 DRAW_CANDLES
#property indicator_color1 clrOrange
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
#property indicator_separate_window
//— データ受信のパラメータ
input string InpFileName=“EURUSD.txt”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| ローソク足データを格納する構造体 |
//+——————————————————————+
struct candlesticks
{
double open; // 始値
double close; // 終値
double high; // 高値
double low; // 安値
datetime date; // 日付
};
//— 指標バッファ
double open_buff[];
double close_buff[];
double high_buff[];
double low_buff[];
//— グローバル変数
candlesticks cand_buff[];
int size=0;
int ind=0;
//+——————————————————————+
//| カスタム指標を初期化する関数 |
//+——————————————————————+
int OnInit()
{
int default_size=100;
ArrayResize(cand_buff,default_size);
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_BIN|FILE_COMMON);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_COMMONDATA_PATH));
//— ファイルからデータを読む
while(!FileIsEnding(file_handle))
{
//— データを配列に書く
FileReadStruct(file_handle,cand_buff[size]);
size++;
//— 配列がオーバーフローしているかチェックする
if(size==default_size)
{
//— 配列サイズを増やす
default_size+=100;
ArrayResize(cand_buff,default_size);
}
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is read, %s file is closed”,InpFileName);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
return(INIT_FAILED);
}
//— 指標バッファマッピング
SetIndexBuffer(0,open_buff,INDICATOR_DATA);
SetIndexBuffer(1,high_buff,INDICATOR_DATA);
SetIndexBuffer(2,low_buff,INDICATOR_DATA);
SetIndexBuffer(3,close_buff,INDICATOR_DATA);
//— 空の値
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| カスタム指標の反復関数 |
//+——————————————————————+
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);
//— まだ処理されてないローソク足のループ
for(int i=prev_calculated;i<rates_total;i++)
{
//— デフォルトでは 0
open_buff[i]=0;
close_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
//— まだデータがあるかをチェック
if(ind<size)
{
for(int j=ind;j<size;j++)
nbsp; {
//— 日付が同じならファイルの値を使用する
if(time[i]==cand_buff[j].date)
{
open_buff[i]=cand_buff[j].open;
close_buff[i]=cand_buff[j].close;
high_buff[i]=cand_buff[j].high;
low_buff[i]=cand_buff[j].low;
//— カウンタを増加する
ind=j+1;
break;
}
}
}
}
//— 次の呼び出しのために prev_calculated の値を返す
return(rates_total);
}
|
参照
構造体とクラス、FileWriteStruct
FileSeek
この関数は、ファイルポインタの位置を指定された位置から指定されたバイト数で移動します。
bool FileSeek(
int file_handle,
long offset,
ENUM_FILE_POSITION origin
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
offset
[in] バイト単位でのシフト(負の値も可能)
origin
[in] シフトの開始点。ENUM_FILE_POSITION 列挙のいずれかの値。
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FileSeek.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 script_show_inputs
//— 入力パラメータ
input string InpFileName=“file.txt”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
input int InpEncodingType=FILE_ANSI; // ANSI=32 または UNICODE=64
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— 乱数を生成するための変数の値を指定する
_RandomSeed=GetTickCount();
//— 文字列の開始位置のための変数
ulong pos[];
int size;
//— エラー値をリセットする
ResetLastError();
//— ファイルを開く
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
//— ファイル内の各文字列の開始位置を受け取る
GetStringPositions(file_handle,pos);
//— ファイル内の文字列の数を定義する
size=ArraySize(pos);
if(!size)
{
//— ファイルに文字列がない場合、停止する
PrintFormat(“%s file is empty!”,InpFileName);
FileClose(file_handle);
return;
}
//— 文字列番号をランダムに選ぶ
int ind=MathRand()%size;
//— 位置を文字列の始めにシフトする
if(FileSeek(file_handle,pos[ind],SEEK_SET)==true)
{
//— ind 番号で文字列を読んで出力する
PrintFormat(“String text with %d number: \”%s\“”,ind,FileReadString(file_handle));
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“%s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
//+——————————————————————————-+
//| この関数はファイル内の文字列の開始点を定義して |
//| 配列に格納する |
//+——————————————————————————-+
void GetStringPositions(const int handle,ulong &arr[])
{
//— デフォルトの配列サイズ
int def_size=127;
//— 配列へのメモリ追加
ArrayResize(arr,def_size);
//— 文字列カウンタ
int i=0;
//— これがファイルの最後でない場合、少なくても 1 つの文字列がある
if(!FileIsEnding(handle))
{
arr[i]=FileTell(handle);
i++;
}
else
return; // ファイルが空なので終了する
//— エンコーディングに応じてバイト単位のシフトを定義する
int shift;
if(FileGetInteger(handle,FILE_IS_ANSI))
shift=1;
else
shift=2;
//— ループで文字列をみる
while(1)
{
//— 文字列を読む
FileReadString(handle);
//— ファイルの終わりをチェックする
if(!FileIsEnding(handle))
{
//— 文字列の次の位置を格納する
arr[i]=FileTell(handle)+shift;
i++;
//— オーバーフローしている場合は、配列のサイズを増やす
if(i==def_size)
{
def_size+=def_size+1;
ArrayResize(arr,def_size);
}
}
else
break; // ファイルの終わり。終了する。
}
//— 配列の実際のサイズを定義する
ArrayResize(arr,i);
}
|
FileSize
この関数は、ファイルサイズをバイト単位で返します。
ulong FileSize(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
注意事項
例:
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input ulong InpThresholdSize=20; // キロバイト単位でのファイルのしきい値サイズ
input string InpBigFolderName=“big”; // 大きいファイルのフォルダ
input string InpSmallFolderName=“small”; // 小さいファイルのフォルダ
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string file_name; // ファイル名を格納する変数
string filter=“*.csv”; // ファイル検索フィルタ
ulong file_size=0; // バイト単位のファイルサイズ
int size=0; // ファイル数
//— 操作するファイルへのパスを出力する
PrintFormat(“Working in %s\\Files\\ folder”,TerminalInfoString(TERMINAL_COMMONDATA_PATH));
//— 全ての端末に共通なフォルダのルートで検索ハンドルを受け取る
long search_handle=FileFindFirst(filter,file_name,FILE_COMMON);
//— FileFindFirst() の実行が成功したかをチェックする
if(search_handle!=INVALID_HANDLE)
{
//— サイズによってファイルをループで移動する
do
{
//— ファイルを開く
ResetLastError();
int file_handle=FileOpen(file_name,FILE_READ|FILE_CSV|FILE_COMMON);
if(file_handle!=INVALID_HANDLE)
{
//— ファイルサイズを受け取る
file_size=FileSize(file_handle);
//— ファイルを閉じる
FileClose(file_handle);
}
else
{
PrintFormat(“Failed to open %s file, Error code = %d”,file_name,GetLastError());
continue;
}
//— ファイルサイズを出力する
PrintFormat(“Size of %s file is equal to %d bytes”,file_name,file_size);
//— ファイル移動のパスを定義する
string path;
if(file_size>InpThresholdSize*1024)
path=InpBigFolderName+“//”+file_name;
else
path=InpSmallFolderName+“//”+file_name;
//— ファイルを移動する
ResetLastError();
if(FileMove(file_name,FILE_COMMON,path,FILE_REWRITE|FILE_COMMON))
PrintFormat(“%s file is moved”,file_name);
else
PrintFormat(“Error, code = %d”,GetLastError());
}
while(FileFindNext(search_handle,file_name));
//— 検索ハンドルを閉じる
FileFindClose(search_handle);
}
else
Print(“Files not found!”);
}
|
FileTell
この関数は、開かれているファイルのファイルポインタの現在位置を返します。
ulong FileTell(
int file_handle
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FileTell.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 script_show_inputs
//— 入力パラメータ
input string InpFileName=“file.txt”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
input int InpEncodingType=FILE_ANSI; // ANSI=32 または UNICODE=64
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— 乱数を生成するための変数の値を指定する
_RandomSeed=GetTickCount();
//— 文字列の開始位置のための変数
ulong pos[];
int size;
//— エラー値をリセットする
ResetLastError();
//— ファイルを開く
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for reading”,InpFileName);
//— ファイル内の各文字列の開始位置を受け取る
GetStringPositions(file_handle,pos);
//— ファイル内の文字列の数を定義する
size=ArraySize(pos);
if(!size)
{
//— ファイルに文字列がない場合、停止する
PrintFormat(“%s file is empty!”,InpFileName);
FileClose(file_handle);
return;
}
//— 文字列番号をランダムに選ぶ
int ind=MathRand()%size;
//— 位置を文字列の始めにシフトする
FileSeek(file_handle,pos[ind],SEEK_SET);
//— ind 番号で文字列を読んで出力する
PrintFormat(“String text with %d number: \”%s\“”,ind,FileReadString(file_handle));
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“%s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
//+——————————————————————————-+
//| この関数はファイル内の文字列の開始点を定義して |
//| 配列に格納する |
//+——————————————————————————-+
void GetStringPositions(const int handle,ulong &arr[])
{
//— デフォルトの配列サイズ
int def_size=127;
//— 配列へのメモリ追加
ArrayResize(arr,def_size);
//— 文字列カウンタ
int i=0;
//— これがファイルの最後でない場合、少なくても 1 つの文字列がある
if(!FileIsEnding(handle))
{
arr[i]=FileTell(handle);
i++;
}
else
return; // ファイルが空なので終了する
//— エンコーディングに応じてバイト単位のシフトを定義する
int shift;
if(FileGetInteger(handle,FILE_IS_ANSI))
shift=1;
else
shift=2;
//— ループで文字列をみる
while(1)
{
//— 文字列を読む
FileReadString(handle);
//— ファイルの終わりをチェックする
if(!FileIsEnding(handle))
{
//— 文字列の次の位置を格納する
arr[i]=FileTell(handle)+shift;
i++;
//— オーバーフローしている場合は、配列のサイズを増やす
if(i==def_size)
{
def_size+=def_size+1;
ArrayResize(arr,def_size);
}
}
else
break; // ファイルの終わり。終了する。
}
//— 配列の実際のサイズを定義する
ArrayResize(arr,i);
}
|
FileWrite
この関数は、0である場合以外は区切りを自動的に挿入してのCSVファイルへのデータの書き込みのために意図されています。ファイル書き込みの後で「\r\n」改行文字が加えられます。
uint FileWrite(
int file_handle,
…
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
…
[in] ファイルに書かれる、コンマで区切られたパラメータのリスト(パラメータは 63 まで)
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FileWrite.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
input string InpSymbolName=“EURUSD”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // 時間軸
input int InpFastEMAPeriod=12; // 高速 EMA 期間
input int InpSlowEMAPeriod=26; // 低速 EMA 期間
input int InpSignalPeriod=9; // 差分平均期間
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // 価格の種類
input datetime InpDateStart=D’2012.01.01 00:00′; // データコピー開始日
//— ファイルにデータを書き込むためのパラメータ
input string InpFileName=“MACD.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish; // データコピー終了日
bool sign_buff[]; // シグナル配列(true – 買、false – 売)
datetime time_buff[]; // シグナル到着時の配列
int sign_size=0; // シグナル配列サイズ
double macd_buff[]; // 指標値の配列
datetime date_buff[]; // 指標日付の配列
int macd_size=0; // 指標配列のサイズ
//— 終了時刻が現在時刻
date_finish=TimeCurrent();
//— MACD 指標ハンドルを受け取る
ResetLastError();
int macd_handle=iMACD(InpSymbolName,InpSymbolPeriod,InpFastEMAPeriod,InpSlowEMAPeriod,InpSignalPeriod,InpAppliedPrice);
if(macd_handle==INVALID_HANDLE)
{
//— 指標ハンドルの受け取りに失敗
PrintFormat(“Error when receiving indicator handle. Error code = %d”,GetLastError());
return;
}
//— 全ての指標値が計算されるまでループに留まる
while(BarsCalculated(macd_handle)==-1)
Sleep(10); // 指標が全ての値を計算出来るように一時停止
//— 一定期間の指標値を複製する
ResetLastError();
if(CopyBuffer(macd_handle,0,InpDateStart,date_finish,macd_buff)==-1)
{
PrintFormat(“Failed to copy indicator values. Error code = %d”,GetLastError());
return;
}
//— 指標値に適切な時間を複製する
ResetLastError();
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,date_buff)==-1)
{
PrintFormat(“Failed to copy time values. Error code = %d”,GetLastError());
return;
}
//— 指標で使用されたメモリを解放する
IndicatorRelease(macd_handle);
//— バッファサイズを受け取る
macd_size=ArraySize(macd_buff);
//— データを分析し指標シグナルを配列に保存する
ArrayResize(sign_buff,macd_size-1);
ArrayResize(time_buff,macd_size-1);
for(int i=1;i<macd_size;i++)
{
//— 買いシグナル
if(macd_buff[i-1]<0 && macd_buff[i]>=0)
{
sign_buff[sign_size]=true;
time_buff[sign_size]=date_buff[i];
sign_size++;
}
//— 売りシグナル
if(macd_buff[i-1]>0 && macd_buff[i]<=0)
{
sign_buff[sign_size]=false;
time_buff[sign_size]=date_buff[i];
sign_size++;
}
}
//— 指標値を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 初めにシグナル数を書く
FileWrite(file_handle,sign_size);
//— シグナルの時間と値をファイルに書く
for(int i=0;i<sign_size;i++)
FileWrite(file_handle,time_buff[i],sign_buff[i]);
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
コメント、Print、StringFormat
FileWriteArray
この関数は string 以外の任意の型の配列を BIN ファイルに書きます(文字列や動的配列を含まない構造体の配列も可能)
uint FileWriteArray(
int file_handle,
const void& array[],
int start=0,
int count=WHOLE_ARRAY
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
array[]
[out] 記録する配列
start=0
[in] 配列内の最初のインデックス(最初に記録された要素の番号)
count=WHOLE_ARRAY
[in] 書かれる項目数(WHOLE_ARRAY は.開始点から配列の最後までの全ての項目が書き込まれることを意味します)。
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FileWriteArray.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”
//— 入力パラメータ
input string InpFileName=“data.bin”;
input string InpDirectoryName=“SomeFolder”;
//+——————————————————————+
//| 価格データを格納する構造体 |
//+——————————————————————+
struct prices
{
datetime date; // 日付
double bid; // 売値
double ask; // 買値
};
//— グローバル変数
int count=0;
int size=20;
string path=InpDirectoryName+“//”+InpFileName;
prices arr[];
//+——————————————————————+
//| エキスパート初期化に使用される関数 |
//+——————————————————————+
int OnInit()
{
//— 配列へのメモリ追加
ArrayResize(arr,size);
//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| エキスパート初期化解除に使用される関数 |
//+——————————————————————+
void OnDeinit(const int reason)
{
//— count<n の場合、残り数を書く
WriteData(count);
}
//+——————————————————————+
//| エキスパートティック関数 |
//+——————————————————————+
void OnTick()
{
//— データを配列に保存する
arr[count].date=TimeCurrent();
arr[count].bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
arr[count].ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
//— 現在のデータを表示する
Print(“Date = “,arr[count].date,” Bid = “,arr[count].bid,” Ask = “,arr[count].ask);
//— カウンタを増やす
count++;
//— 配列がすでに記入済みなら、データをファイルに書いてゼロで書きなおす
if(count==size)
{
WriteData(size);
count=0;
}
}
//+——————————————————————+
//| 配列の n 要素をファイルに書く |
//+——————————————————————+
void WriteData(const int n)
{
//— ファイルを開く
ResetLastError();
int handle=FileOpen(path,FILE_READ|FILE_WRITE|FILE_BIN);
if(handle!=INVALID_HANDLE)
{
//— 配列データをファイルの終わりに書く
FileSeek(handle,0,SEEK_END);
FileWriteArray(handle,arr,0,n);
//— ファイルを閉じる
FileClose(handle);
}
else
Print(“Failed to open the file, error “,GetLastError());
}
|
参照
変数、FileSeek
FileWriteDouble
この関数は、ファイルポインタの現在位置から開始して、ファイルに double パラメータの値を書き込みます。
uint FileWriteDouble(
int file_handle,
double value
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
value
[in] double 型の値
戻り値
例:
//+——————————————————————+
//| Demo_FileWriteDouble.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
。input string InpSymbolName=“EURJPY”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_M15; // 時間軸
input int InpMAPeriod=10; // 平滑化期間
input int InpMAShift=0; // 指標のシフト shift
input ENUM_MA_METHOD InpMAMethod=MODE_SMA; // 平滑化の種類
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // 価格の種類
input datetime InpDateStart=D’2013.01.01 00:00′; // データコピー開始日
//— データをファイルに書くパラメータ
input string InpFileName=“MA.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish=TimeCurrent();
double ma_buff[];
datetime time_buff[];
int size;
//— MA 指標ハンドルを受け取る
ResetLastError();
int ma_handle=iMA(InpSymbolName,InpSymbolPeriod,InpMAPeriod,InpMAShift,InpMAMethod,InpAppliedPrice);
if(ma_handle==INVALID_HANDLE)
{
//— 指標ハンドルの受け取りに失敗
PrintFormat(“Error when receiving indicator handle. Error code = %d”,GetLastError());
return;
}
//— 全ての指標値が計算されるまでループに留まる
while(BarsCalculated(ma_handle)==-1)
Sleep(20); // 指標が全ての値を計算出来るように一時停止
PrintFormat(“Indicator values starting from %s will be written to the file”,TimeToString(InpDateStart));
//— 指標値を複製する
ResetLastError();
if(CopyBuffer(ma_handle,0,InpDateStart,date_finish,ma_buff)==-1)
{
PrintFormat(“Failed to copy the indicator values. Error code = %d”,GetLastError());
return;
}
//— 適切なバーの到着時間を複製する
ResetLastError();
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat(“Failed to copy time values. Error code = %d”,GetLastError());
return;
}
//— バッファサイズを受け取る
size=ArraySize(ma_buff);
//— 指標で使用されたメモリを解放する
IndicatorRelease(ma_handle);
//— 指標値を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 初めにデータサンプルのサイズを書く
FileWriteDouble(file_handle,(double)size);
//— 指標の時間と値をファイルに書く
for(int i=0;i<size;i++)
{
FileWriteDouble(file_handle,(double)time_buff[i]);
FileWriteDouble(file_handle,ma_buff[i]);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
浮動小数点数型(ダブル、フロート)
FileWriteFloat
この関数は、ファイルポインタの現在位置から開始して、バイナリファイルに float パラメータの値を書き込みます。
uint FileWriteFloat(
int file_handle,
float value
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
value
[in] float 型の値
戻り値
例:
//+——————————————————————+
//| Demo_FileWriteFloat.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
input string InpSymbolName=“EURUSD”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_M15; // 時間軸
input datetime InpDateStart=D’2013.01.01 00:00′; // データコピー開始日
//— データをファイルに書くパラメータ
input string InpFileName=“Close.bin”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish=TimeCurrent();
double close_buff[];
datetime time_buff[];
int size;
//— エラー値をリセットする
ResetLastError();
//— バーに終値を複製する
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-1)
{
PrintFormat(“Failed to copy close price values. Error code = %d”,GetLastError());
return;
}
//— バーに時間を複製する
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat(“Failed to copy the time values. Error code = %d”,GetLastError());
return;
}
//— バッファサイズを受け取る
size=ArraySize(close_buff);
//— 値を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is open for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 終値の時間と値をファイルに書く
for(int i=0;i<size;i++)
{
FileWriteDouble(file_handle,(double)time_buff[i]);
FileWriteFloat(file_handle,(float)close_buff[i]);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
浮動小数点数型(ダブル、フロート)、FileWriteDouble
FileWriteInteger
この関数は、ファイルポインタの現在位置から開始して、バイナリファイルに int パラメータの値を書き込みます。
uint FileWriteInteger(
int file_handle,
int value,
int size=INT_VALUE
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
value
[in] 整数値
size=INT_VALUE
[in] 書かれるバイト数(4以下)。関数が char、short または int 型の値を書けるように、CHAR_VALUE=1、SHORT_VALUE=2 t及び INT_VALUE=4 と対応する定数が用意されています。
戻り値
例:
//+——————————————————————+
//| Demo_FileWriteInteger.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
input string InpSymbolName=“EURUSD”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // 時間軸
input datetime InpDateStart=D’2013.01.01 00:00′; // データコピー開始日
//— データをファイルに書くパラメータ
input string InpFileName=“Trend.bin”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish=TimeCurrent();
double close_buff[];
datetime time_buff[];
int size;
//— エラー値をリセットする
ResetLastError();
//— バーに終値を複製する
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-1)
{
PrintFormat(“Failed to copy the values of close prices. Error code = %d”,GetLastError());
return;
}
//— バーに時間を複製する
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat(“Failed to copy time values. Error code = %d”,GetLastError());
return;
}
//— バッファサイズを受け取る
size=ArraySize(close_buff);
//— 値を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//—
int up_down=0; // トレンドフラグ
int arr_size; // arr 配列サイズ
uchar arr[]; // uchar 型の配列
//— 時間値をファイルに書く
for(int i=0;i<size-1;i++)
{
//— 現在と次のバーの終値を比べる
if(close_buff[i]<=close_buff[i+1])
{
if(up_down!=1)
{
//— FileWriteInteger を使用してデータ値をファイルに書く
StringToCharArray(TimeToString(time_buff[i]),arr);
arr_size=ArraySize(arr);
//— 初めにシンボル数を配列に書く
FileWriteInteger(file_handle,arr_size,INT_VALUE);
//— シンボルを書く
for(int j=0;j<arr_size;j++)
FileWriteInteger(file_handle,arr[j],CHAR_VALUE);
//— トレンドフラグを変更する
up_down=1;
}
}
else
{
if(up_down!=-1)
{
//— FileWriteInteger を使用してデータ値をファイルに書く
StringToCharArray(TimeToString(time_buff[i]),arr);
arr_size=ArraySize(arr);
//— 初めにシンボル数を配列に書く
FileWriteInteger(file_handle,arr_size,INT_VALUE);
//— シンボルを書く
for(int j=0;j<arr_size;j++)
FileWriteInteger(file_handle,arr[j],CHAR_VALUE);
//— トレンドフラグを変更する
up_down=-1;
}
}
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
IntegerToString、StringToInteger、整数型
FileWriteLong
この関数は、ファイルポインタの現在位置から開始して、バイナリファイルに long 型のパラメータの値を書き込みます。
uint FileWriteLong(
int file_handle,
long value
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
value
[in] long 型の値
戻り値
例:
//+——————————————————————+
//| Demo_FileWriteLong.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
input string InpSymbolName=“EURUSD”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // 時間軸
input datetime InpDateStart=D’2013.01.01 00:00′; // データコピー開始日
//— データをファイルに書くパラメータ
input string InpFileName=“Volume.bin”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish=TimeCurrent();
long volume_buff[];
datetime time_buff[];
int size;
//— エラー値をリセットする
ResetLastError();
//— バーにティックボリュームを複製する
if(CopyTickVolume(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,volume_buff)==-1)
{
PrintFormat(“Failed to copy values of the tick volume. Error code = %d”,GetLastError());
return;
}
//— バーに時間を複製する
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat(“Failed to copy time values. Error code = %d”,GetLastError());
return;
}
//— バッファサイズを受け取る
size=ArraySize(volume_buff);
//— 指標値を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 初めにデータサンプルサイズを書く
FileWriteLong(file_handle,(long)size);
//— 時間とボリューム値をファイルに書く
for(int i=0;i<size;i++)
{
FileWriteLong(file_handle,(long)time_buff[i]);
FileWriteLong(file_handle,volume_buff[i]);
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
整数型、FileWriteInteger
FileWriteString
この関数は、BIN、CSV または TXT ファイルのファイルポインタの現在位置に string 型のパラメータの値を書き込みます。CSV や TXT ファイルに書き込む場合、文字列が、事前に 「\r」 (CR) がない 「\n」 (LF) を含む場合, 「\n」の前に「\r」が加えられます。
uint FileWriteString(
int file_handle,
const string text_string,
int length=-1
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
text_string
[in] 文字列
length=-1
[in] 書かれる文字数。このオプションはBINファイルに文字列を書き込むために必要です。サイズが指定されていない場合には、トレーラー 0 を含まない文字列全体が書かれます。文字列の長さよりも小さいサイズが指定された場合は、その部分がトレーラー 0 を含まずに書かれます。文字列の長さよりも大きいサイズが指定された場合は、適切な数のゼロが書き足されます。CSV 及び TXT 形式のファイルではこのパラメータは無視され、文字列全体が書かれます。
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FileWriteString.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
input string InpSymbolName=“EURUSD”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // 時間軸
input int InpMAPeriod=14; // MA 期間
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // 価格の種類
input datetime InpDateStart=D’2013.01.01 00:00′; // データコピー開始日
//— データをファイルに書くパラメータ
input string InpFileName=“RSI.csv”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish; // データコピー終了日
double rsi_buff[]; // 指標値の配列
datetime date_buff[]; // 指標日付の配列
int rsi_size=0; // 指標配列のサイズ
//— 終了時刻が現在の時刻
date_finish=TimeCurrent();
//— RSI 指標ハンドルを受け取る
ResetLastError();
int rsi_handle=iRSI(InpSymbolName,InpSymbolPeriod,InpMAPeriod,InpAppliedPrice);
if(rsi_handle==INVALID_HANDLE)
{
//— 指標ハンドルの受け取りに失敗
PrintFormat(“Error when receiving indicator handle. Error code = %d”,GetLastError());
return;
}
//— 指標が全ての値を計算するまでループ内にとどまる
while(BarsCalculated(rsi_handle)==-1)
Sleep(10); // 指標が全ての値を計算出来るように一時停止
//— 一定期間の指標値を複製する
ResetLastError();
if(CopyBuffer(rsi_handle,0,InpDateStart,date_finish,rsi_buff)==-1)
{
PrintFormat(“Failed to copy indicator values. Error code = %d”,GetLastError());
return;
}
//— 指標値に適切な時間を複製する
ResetLastError();
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,date_buff)==-1)
{
PrintFormat(“Failed to copy time values. Error code = %d”,GetLastError());
return;
}
//— 指標で使用されたメモリを解放する
IndicatorRelease(rsi_handle);
//— バッファサイズを受け取る
rsi_size=ArraySize(rsi_buff);
//— 指標値を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_CSV|FILE_ANSI);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is available for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_DATA_PATH));
//— 追加の変数を準備する
string str=“”;
bool is_formed=false;
//— 買われ過ぎと売られ過ぎ領域を作る日付を書く
for(int i=0;i<rsi_size;i++)
{
//— 指標値をチェックする
if(rsi_buff[i]>=70 || rsi_buff[i]<=30)
{
//— これが領域の初めの値の場合
if(!is_formed)
{
//— 値と日付を加える
str=(string)rsi_buff[i]+“\t”+(string)date_buff[i];
is_formed=true;
}
else
str+=“\t”+(string)rsi_buff[i]+“\t”+(string)date_buff[i];
//— 次のループ反復に移る
continue;
}
//— フラグをチェックする
if(is_formed)
{
//— 文字列が用意できたのでファイルに書く
FileWriteString(file_handle,str+“\r\n”);
is_formed=false;
}
}
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
String Type, StringFormat
FileWriteStruct
この関数は、バイナリファイルのファイルポインタの現在の位置から、パラメータとして渡される構造体のコンテンツを書き込みます。
uint FileWriteStruct(
int file_handle,
const void& struct_object,
int size=-1
);
|
パラメータ
file_handle
[in] FileOpen() から戻されたファイル記述子
struct_object
[in] 構造体オブジェクトへの参照。構造体は文字列、動的配列 また 仮想関数を含むことは出来ません。
size=-1
[in] 書かれるバイト数サイズが指定されない、または指定されたバイト数が構造のサイズよりも大きい場合は、構造体全体が書かれます。
戻り値
例:
//+——————————————————————+
//| Demo_FileWiteStruct.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 script_show_inputs
//— 端末からデータを受け取るパラメータ
input string InpSymbolName=“EURUSD”; // 通貨ペア
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // 時間軸
input datetime InpDateStart=D’2013.01.01 00:00′; // データコピー開始日
//— データをファイルに書くパラメータ
input string InpFileName=“EURUSD.txt”; // ファイル名
input string InpDirectoryName=“Data”; // ディレクトリ名
//+——————————————————————+
//| ローソク足データを格納する構造体 |
//+——————————————————————+
struct candlesticks
{
double open; // 始値
double close; // 終値
double high; // 高値
double low; // 安値
datetime date; // 日付
};
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
datetime date_finish=TimeCurrent();
int size;
datetime time_buff[];
double open_buff[];
double close_buff[];
double high_buff[];
double low_buff[];
candlesticks cand_buff[];
//— エラー値をリセットする
ResetLastError();
//— 範囲内のバーの到着時間を受信
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat(“Failed to copy time values. Error code = %d”,GetLastError());
return;
}
//— 範囲内の足の高値を受信
if(CopyHigh(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,high_buff)==-1)
{
PrintFormat(“Failed to copy values of high prices. Error code = %d”,GetLastError());
return;
}
//— 範囲内のバーの安値を受信
if(CopyLow(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,low_buff)==-1)
{
PrintFormat(“Failed to copy values of low prices. Error code = %d”,GetLastError());
return;
}
//— 範囲内のバーの始値を受信
if(CopyOpen(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,open_buff)==-1)
{
PrintFormat(“Failed to copy values of open prices. Error code = %d”,GetLastError());
return;
}
//— 範囲内のバーの終値を受信
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-1)
{
PrintFormat(“Failed to copy values of close prices. Error code = %d”,GetLastError());
return;
}
//— 配列の次元を定義
size=ArraySize(time_buff);
//— データを構造体配列に保存
ArrayResize(cand_buff,size);
for(int i=0;i<size;i++)
{
cand_buff[i].open=open_buff[i];
cand_buff[i].close=close_buff[i];
cand_buff[i].high=high_buff[i];
cand_buff[i].low=low_buff[i];
cand_buff[i].date=time_buff[i];
}
//— 構造体配列を書き込むためにファイルを開く(ファイルが存在しない場合は自動的に作成される)
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+“//”+InpFileName,FILE_READ|FILE_WRITE|FILE_BIN|FILE_COMMON);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat(“%s file is open for writing”,InpFileName);
PrintFormat(“File path: %s\\Files\\”,TerminalInfoString(TERMINAL_COMMONDATA_PATH));
//— バイト数カウンタを準備する
uint counter=0;
//— ループで配列値を書く
for(int i=0;i<size;i++)
counter+=FileWriteStruct(file_handle,cand_buff[i]);
PrintFormat(“%d bytes of information is written to %s file”,InpFileName,counter);
PrintFormat(“Total number of bytes: %d * %d * %d = %d, %s”,size,5,8,size*5*8,size*5*8==counter ? “Correct” : “Error”);
//— ファイルを閉じる
FileClose(file_handle);
PrintFormat(“Data is written, %s file is closed”,InpFileName);
}
else
PrintFormat(“Failed to open %s file, Error code = %d”,InpFileName,GetLastError());
}
|
参照
構造体とクラス
FileLoad
指定されたバイナリファイルのすべてのデータを渡された数値型または単純な構造体型の配列に読み込みます。この関数を使用すると、既知の型のデータをすぐに適切な配列に読み取ることができます。
long FileLoad(
const string file_name,
void& buffer[],
int common_flag=0
);
|
パラメータ
file_name
[in] 含まれるデータが読まれるファイル名。
buffer
[out] 数値型または単純な構造体型の配列。
common_flag=0
[in] 操作モードを示すファイルフラグ。このパラメータが指定されていない場合、ファイルは MQL5\Files サブフォルダ(または検証の場合 <testing_agent_directory>\MQL5\Files )で検索されます。
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FileLoad.mq5 |
//| Copyright 2016, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+——————————————————————+
#property copyright “Copyright 2016, MetaQuotes Software Corp.”
#property link “https://www.mql5.com”
#property version “1.00”
#property copyright “Copyright 2016, MetaQuotes Software Corp.”
#property link “https://www.mql5.com”
#property version “1.00”
#property script_show_inputs
//— 入力パラメータ
input int bars_to_save=10; // バー数
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string filename=_Symbol+“_rates.bin”;
MqlRates rates[];
//—
int copied=CopyRates(_Symbol,_Period,0,bars_to_save,rates);
if(copied!=-1)
{
PrintFormat(” CopyRates(%s) copied %d bars”,_Symbol,copied);
//— 相場をファイルに書く
if(!FileSave(filename,rates,FILE_COMMON))
PrintFormat(“FileSave() failed, error=%d”,GetLastError());
}
else
PrintFormat(“Failed CopyRates(%s), error=”,_Symbol,GetLastError());
//— 相場をファイルに読み返す
ArrayFree(rates);
long count=FileLoad(filename,rates,FILE_COMMON);
if(count!=-1)
{
Print(“Time\tOpen\tHigh\tLow\tClose\tTick Voulme\tSpread\tReal Volume”);
for(int i=0;i<count;i++)
{
PrintFormat(“%s\t%G\t%G\t%G\t%G\t%I64u\t%d\t%I64u”,
TimeToString(rates[i].time,TIME_DATE|TIME_SECONDS),
rates[i].open,rates[i].high,rates[i].low,rates[i].close,
rates[i].tick_volume,rates[i].spread,rates[i].real_volume);
}
}
}
|
参照
構造体とクラス、FileReadArray、FileReadStruct, FileSave
FileSave
配列のすべての要素をパラメータとして渡されたバイナリファイルに書き込みます。この関数を使用すると、数値型または単純な構造体型の配列をすぐに単一の文字列として書くことができます。
bool FileSave(
const string file_name,
void& buffer[],
int common_flag=0
);
|
パラメータ
file_name
[in] データ配列の書き込み先のファイル名
buffer
[in] 数値型または単純な構造体型の配列。
common_flag=0
[in] 操作モードを示すファイルフラグ。このパラメータが指定されていない場合、ファイルは MQL5\Files サブフォルダ(または検証の場合 <testing_agent_directory>\MQL5\Files )に書かれます。
戻り値
例:
//+——————————————————————+
//| Demo_FileSave.mq5 |
//| Copyright 2016, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+——————————————————————+
#property copyright “Copyright 2016, MetaQuotes Software Corp.”
#property link “https://www.mql5.com”
#property version “1.00”
#property script_show_inputs
//— 入力パラメータ
input int ticks_to_save=1000; // ティック数
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string filename=_Symbol+“_ticks.bin”;
MqlTick ticks[];
u//—
int copied=CopyTicks(_Symbol,ticks,COPY_TICKS_ALL,0,ticks_to_save);
if(copied!=-1)
{
PrintFormat(” CopyTicks(%s) copied %d ticks”,_Symbol,copied);
//— ティック履歴が同期されている場合はエラーコードは0に等しい
if(!GetLastError()==0)
PrintFormat(“%s: Ticks are not synchronized, error=%d”,_Symbol,copied,_LastError);
//— ティックをファイルに書く
if(!FileSave(filename,ticks,FILE_COMMON))
PrintFormat(“FileSave() failed, error=%d”,GetLastError());
}
else
PrintFormat(“Failed CopyTicks(%s), Error=”,_Symbol,GetLastError());
//— ティックをファイルに読み返す
ArrayFree(ticks);
long count=FileLoad(filename,ticks,FILE_COMMON);
if(count!=-1)
{
Print(“Time\tBid\tAsk\tLast\tVolume\tms\tflags”);
for(int i=0;i<count;i++)
{
PrintFormat(“%s.%03I64u:\t%G\t%G\t%G\t%I64u\t0x%04x”,
TimeToString(ticks[i].time,TIME_DATE|TIME_SECONDS),ticks[i].time_msc%1000,
ticks[i].bid,ticks[i].ask,ticks[i].last,ticks[i].volume,ticks[i].flags);
}
}
}
|
参照
構造体とクラス、FileWriteArray、FileWriteStruct, FileLoad, FileWrite
FolderCreate
この関数は、common_flag の値によって、Files ディレクトリ内にフォルダを作成します。
bool FolderCreate(
string folder_name,
int common_flag=0
);
|
パラメータ
folder_name
[in] Name of the directory to be created. Contains the relative path to the folder.
common_flag=0
[in] ディレクトリの場所を決めるフラグ。common_flag=FILE_COMMON の場合、ディレクトリは全てのクライアント端末の共有フォルダ \Terminal\Common\Filesに位置します。その他の場合、ディレクトリはローカルフォルダ(MQL5\Files またはテストの場合 MQL5\Tester\Files)に位置します。
戻り値
注意事項
例:
#property copyright “Copyright 2011, MetaQuotes Software Corp.”
#property link “https://www.mql5.com”
#property version “1.00”
//— description
#property description “The script shows FolderCreate() application sample.”
#property description “The external parameter defines the directory for creating folders.”
#property description “The folder structure is created after executing the script”
//— display window of the input parameters during the script’s launch
#property script_show_inputs
//— the input parameter defines the folder, in which the script works
input bool common_folder=false; // common folder for all terminals
//+——————————————————————+
//| Script program start function |
//+——————————————————————+
void OnStart()
{
//— folder to be created in MQL5\Files
string root_folder=“Folder_A”;
if(CreateFolder(root_folder,common_folder))
{
//— create the Child_Folder_B1 sub-folder in it
string folder_B1=“Child_Folder_B1”;
string path=root_folder+“\\”+folder_B1; // create the folder name considering the structure
if(CreateFolder(path,common_folder))
{
//— create 3 more sub-directories in this folder
string folder_C11=“Child_Folder_C11”;
string child_path=root_folder+“\\”+folder_C11;// create the folder name considering the structure
CreateFolder(child_path,common_folder);
//— second sub-directory
string folder_C12=“Child_Folder_C12”;
child_path=root_folder+“\\”+folder_C12;
CreateFolder(child_path,common_folder);
//— third sub-directory
string folder_C13=“Child_Folder_C13”;
child_path=root_folder+“\\”+folder_C13;
CreateFolder(child_path,common_folder);
}
}
//—
}
//+——————————————————————+
//| Try creating a folder and display a message about that |
//+——————————————————————+
bool CreateFolder(string folder_path,bool common_flag)
{
int flag=common_flag?FILE_COMMON:0;
string working_folder;
//— define the full path depending on the common_flag parameter
if(common_flag)
working_folder=TerminalInfoString(TERMINAL_COMMONDATA_PATH)+“\\MQL5\\Files”;
else
working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+“\\MQL5\\Files”;
//— debugging message
PrintFormat(“folder_path=%s”,folder_path);
//— attempt to create a folder relative to the MQL5\Files path
if(FolderCreate(folder_path,flag))
{
//— display the full path for the created folder
PrintFormat(“Created the folder %s”,working_folder+“\\”+folder_path);
//— reset the error code
ResetLastError();
//— successful execution
return true;
}
else
PrintFormat(“Failed to create the folder %s. Error code %d”,working_folder+folder_path,GetLastError());
//— execution failed
return false;
}
|
参照
FileOpen()、FolderClean()、FileCopy()
FolderDelete
この関数は、指定されたディレクトリを削除します。フォルダが空でない場合は、削除出来ません。
bool FolderDelete(
string folder_name,
int common_flag=0
);
|
パラメータ
folder_name
[in] 削除するディレクトリ名。フォルダの絶対パスを含みます。
common_flag=0
[in] ディレクトリの場所を決めるフラグ。common_flag=FILE_COMMON の場合、ディレクトリは全てのクライアント端末の共有フォルダ \Terminal\Common\Filesに位置します。その他の場合、ディレクトリはローカルフォルダ(MQL5\Files またはテストの場合 MQL5\Tester\Files)に位置します。
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FolderDelete.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.MQL5.com |
//+——————————————————————+
#property copyright “Copyright 2011, MetaQuotes Software Corp.”
#property link “https://www.mql5.com”
#property version “1.00”
//— 説明
#property description “The script shows a sample use of FolderDelete().”
#property description “First two folders are created; one of them is empty, the second one contains a file.”
#property description “When trying to delete a non-empty folder, an error is returned and a warning is shown.”
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string firstFolder=“empty”; // 空のフォルダ
input string secondFolder=“nonempty”;// ファイルが作成されるフォルダ
string filename=“delete_me.txt”; // secondFolder フォルダに作成されるファイルの名称
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
//— ここにファイルハンドルを書く
int handle;
//— 作業を行うフォルダを見つける
string working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+“\\MQL5\\Files”;
//— デバッグメッセージ
PrintFormat(“working_folder=%s”,working_folder);
//— MQL5\Files パスに相対した空フォルダ作成を試みる
if(FolderCreate(firstFolder,0)) // 0 は端末のローカルフォルダでの作業を意味する
{
//— 作成されたフォルダの絶対パスを書く
PrintFormat(“Folder %s has been created”,working_folder+“\\”+firstFolder);
//— エラーコードをリセットする
ResetLastError();
}
else
PrintFormat(“Failed to create folder %s. Error code %d”,working_folder+“\\”+firstFolder, GetLastError());
//— FileOpen() 関数で空でないフォルダを作成する
string filepath=secondFolder+“\\”+filename; // 存在しないフォルダに作成して書き込むファイルのパスを作る
handle=FileOpen(filepath,FILE_WRITE|FILE_TXT); // この場合 FILE_WRITE は必須です。FileOpen のヘルプをご参照ください。
if(handle!=INVALID_HANDLE)
PrintFormat(“File %s has been opened for reading”,working_folder+“\\”+filepath);
else
PrintFormat(“Failed to create file %s in folder %s. Error code=”,filename,secondFolder, GetLastError());
Comment(StringFormat(“Prepare to delete folders %s and %s”, firstFolder, secondFolder));
//— チャートのメッセージを読む5秒の休止
Sleep(5000); // Sleep() cannot be used in indicators!
//— ダイアログを表示してユーザに聞く
int choice=MessageBox(StringFormat(“Do you want to delete folders %s and %s?”, firstFolder, secondFolder),
“Deleting folders”,
MB_YESNO|MB_ICONQUESTION); // 「はい(Y)」 と 「いいえ(N)」 の 2 つのボタン
//— 選択されたバージョンに応じてアクションを実行する
if(choice==IDYES)
{
//— チャートからコメントを削除
Comment(“”);
//— エキスパート操作ログにメッセージを加える
PrintFormat(“Trying to delete folders %s and %s”,firstFolder, secondFolder);
ResetLastError();
//— 空のフォルダを削除
if(FolderDelete(firstFolder))
//— フォルダが空なので次のメッセージが表示されるべき
PrintFormat(“Folder %s has been successfully deleted”,firstFolder);
else
PrintFormat(“Failed to delete folder %s. Error code=%d”, firstFolder, GetLastError());
ResetLastError();
//— ファイルを含むフォルダを削除
if(FolderDelete(secondFolder))
PrintFormat(“Folder %s has been successfully deleted”, secondFolder);
else
//— フォルダにファイルが存在するので次のメッセージが表示されるべき
PrintFormat(“Failed to delete folder %s. Error code=%d”, secondFolder, GetLastError());
}
else
Print(“Deletion canceled”);
//—
}
|
参照
FileOpen()、FolderClean()、FileMove()
FolderClean
この関数は、指定されたフォルダ内の全てのファイルを削除します。
bool FolderClean(
string folder_name,
int common_flag=0
);
|
パラメータ
folder_name
[in] 削除されるファイルのディレクトリ名。フォルダの絶対パスを含みます。
common_flag=0
[in] ディレクトリの場所を決めるフラグ。common_flag = FILE_COMMON の場合、ディレクトリは全てのクライアント端末の共有フォルダ \Terminal\Common\Filesに位置します。その他の場合、ディレクトリはローカルフォルダ(MQL5\Files またはテストの場合 MQL5\Tester\Files)に位置します。
戻り値
注意事項
例:
//+——————————————————————+
//| Demo_FolderClean.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.MQL5.com |
//+——————————————————————+
#property copyright “Copyright 2011, MetaQuotes Software Corp.”
#property link “https://www.mql5.com”
#property version “1.00”
//— 説明
#property description “The script shows a sample use of FolderClean().”
#property description “First, files are created in the specified folder using the FileOpen() function.”
#property description “Then, before the files are deleted, a warning is shown using MessageBox().”
//— スクリプトの起動時に入力パラメータのウィンドウを表示する
#property script_show_inputs
//— 入力パラメータ
input string foldername=“demo_folder”; // MQL5/Files/ にフォルダを作成
input int files=5; // 作成及び削除するファイルの数
//+——————————————————————+
//| スクリプトプログラムを開始する関数 |
//+——————————————————————+
void OnStart()
{
string name=“testfile”;
//— 初めに端末データフォルダでファイルを開けるか作成する
for(int N=0;N<files;N++)
{
//— ファイル名は「demo_folder\testfileN.txt」
string filemane=StringFormat(“%s\\%s%d.txt”,foldername,name,N);
//— ファイルを書き入れフラグで開く。この場合「demo_folder」が自動的に作成される
int handle=FileOpen(filemane,FILE_WRITE);
//— FileOpen() 関数が成功したか見つける
if(handle==INVALID_HANDLE)
{
PrintFormat(“Failed to create file %s. Error code”,filemane,GetLastError());
ResetLastError();
}
else
{
PrintFormat(“File %s has been successfully opened”,filemane);
//— 開かれたファイルがもう必要ないので閉じる
FileClose(handle);
}
}
//— フォルダ内のファイル数をチェックする
int k=FilesInFolder(foldername+“\\*.*”,0);
PrintFormat(“Totally the folder %s contains %d files”,foldername,k);
//— ダイアログを表示してユーザに聞く
int choice=MessageBox(StringFormat(“You are going to delete %d files from folder %s. Do you want to continue?”,foldername,k),
“Deleting files from the folder”,
MB_YESNO|MB_ICONQUESTION); // 「はい(Y)」 と 「いいえ(N)」 の 2 つのボタン
ResetLastError();
//— 選択されたバージョンによってアクションを実行する
if(choice==IDYES)
{
//— ファイル削除を開始
PrintFormat(“Trying to delete all files from folder %s”,foldername);
if(FolderClean(foldername,0))
PrintFormat(“Files have been successfully deleted, %d files left in folder %s”,
foldername,
FilesInFolder(foldername+“\\*.*”,0));
else
PrintFormat(“Failed to delete files from folder %s. Error code %d”,foldername,GetLastError());
}
else
PrintFormat(“Deletion canceled”);
//—
}
//+——————————————————————+
//| 指定されたフォルダ内のファイル数を返す |
//+——————————————————————+
int FilesInFolder(string path,int flag)
{
int count=0;
long handle;
string filename;
//—
handle=FileFindFirst(path,filename,flag);
//— ファイルが見つかったらもっと探す
if(handle!=INVALID_HANDLE)
{
//— ファイル名を表示
PrintFormat(“File %s found”,filename);
//— 見つかったファイル・フォルダのカウンタを増やす
count++;
//— 全てのファイル・フォルダで検索を開始
while(FileFindNext(handle,filename))
{
PrintFormat(“File %s found”,filename);
count++;
}
//— 終了後に忘れずに検索ハンドルを閉じる
FileFindClose(handle);
}
else // ハンドル取得に失敗
{
PrintFormat(“Files search in folder %s failed”,path);
}
//— 結果を返す
return count;
}
|
参照
FileFindFirst、FileFindNext、FileFindClose
Originally posted 2019-07-30 09:31:48.