1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonとJinja2でMT5のEA(MQL5コード)を自動生成する仕組み

1
Posted at

はじめに

MetaTrader 5(MT5)で使うEA(エキスパートアドバイザー)は通常MQL5というC++ライクな言語で書く必要があります。
しかしテンプレートエンジンを使えば、PythonからMQL5コードを自動生成できます。

本記事では個人開発中の「EA Creater」で実装したMQL5自動生成の仕組みを解説します。

アーキテクチャ

ユーザー入力(パラメータ)
    ↓
Python(Jinja2でテンプレートレンダリング)
    ↓
MQL5ファイル生成(.mq5)
    ↓
MetaEditorでコンパイル(.ex5)
    ↓
MT5テスターでバックテスト実行
    ↓
結果をPythonで解析・表示

Jinja2テンプレートの構造

MQL5コードをJinja2テンプレートとして記述します。

// {{ea_name}} — 自動生成EA
input double Lot         = {{lot}};
input int    FastMA      = {{fast_ma}};
input int    SlowMA      = {{slow_ma}};
input int    RSIPeriod   = {{rsi_period}};
input double StopLoss    = {{stop_loss_pips}};
input double TakeProfit  = {{take_profit_pips}};

int OnInit() {
    return INIT_SUCCEEDED;
}

void OnTick() {
    double fastMA = iMA(NULL, 0, FastMA, 0, MODE_EMA, PRICE_CLOSE);
    double slowMA = iMA(NULL, 0, SlowMA, 0, MODE_EMA, PRICE_CLOSE);
    double rsi    = iRSI(NULL, 0, RSIPeriod, PRICE_CLOSE);

    {% if strategy == 'trend_follow_v1' %}
    // MAクロス + RSIフィルター
    if (fastMA > slowMA && rsi > {{rsi_buy_threshold}}) {
        // 買いエントリー
    }
    {% endif %}
}

Pythonでのレンダリング

from jinja2 import Environment, FileSystemLoader

def generate_ea(template_key: str, params: dict) -> str:
    env = Environment(loader=FileSystemLoader("templates/"))
    template = env.get_template(f"{template_key}.mq5.j2")
    return template.render(**params)

MetaEditorでの自動コンパイル

import subprocess

def compile_ea(mq5_path: str, metaeditor_path: str) -> bool:
    result = subprocess.run(
        [metaeditor_path, "/compile", mq5_path, "/log"],
        capture_output=True,
        timeout=60,
    )
    return result.returncode == 0

まとめ

  • Jinja2テンプレートを使えばMQL5コードをPythonから動的生成できる
  • パラメータを変えるだけで異なる戦略のEAを量産できる
  • コンパイルもPythonから自動化することでパイプラインが完結する

現在このツールをオープンに開発中です。進捗はXで発信しています。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?