MQL4のインディケータを半年に一回くらい触るのですが、基礎的な部分を忘れてしまうので、メモします。
目次
最初のテンプレート
MQLエディタでカスタムインディケータを作成すると、以下のテンプレートが出現。
#property copyright "xxx" #property link "https://www.mql5.com" #property version "1.00" #property strict #property indicator_chart_window //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- indicator buffers mapping //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ 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[]) { //--- Print("Hello"); //--- return value of prev_calculated for next call return(rates_total); }
テンプレートのポイント
OnCalculate関数は、ティック毎に動作する。
Print文の出力は、エキスパートタブに出力される。
平日だとチャートが動作するので、ティック毎にPrint文の実行を確認できる。休日はリアルタイムに動作しないので、バックテストで動作を確認。
カスタマイズしたテンプレート
#property copyright "xxx" #property link "https://www.mql5.com" #property version "1.00" #property strict #property indicator_chart_window //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { //--- indicator buffers mapping EventSetTimer(60);//set timer seconds. //--- return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason){ Print("deinit"); EventKillTimer(); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ 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[]) { //--- Print("ティック毎の処理"); //--- return value of prev_calculated for next call return(rates_total); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Detect every one minuit. | //+------------------------------------------------------------------+ void OnTimer() { Print("タイマー処理(60秒毎)"); }
・OnInit:初期化関数
・OnDeinit:終了時関数
・OnCalculate:ティック毎計算関数
・OnTimer:一定時間で処理を行うタイマー関数
初期化時に、EventSetTimer(60);など、実行間隔秒数指定を行う。
インディケータ終了時に、EventKillTimer();でタイマー削除を行う。