0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Metatraderを用いた自動売買Bot制作

Last updated at Posted at 2025-04-17

Metatraderを用いた自動売買Bot制作

概要

Metatrader5とPSAR、EMAを用いた為替などの自動売買プログラムの記事です。
全部で3回の構成で解説を行います。

第1回(今回)
環境構築とMetaTrader5ライブラリの基礎構文一覧
第2回(制作中)
PASRなどのインジケーターの関数化
第3回(制作中)
インジケーターを用いてフラグを立ててエントリー管理

環境構築

※前提:Python3.9が利用可能になっていることを前提とします。

MetaTrader5のインストール

以下URLからMetaTrader5をインストールしてください。
これがないとMetaTrader5ライブラリが利用できません。
※Linux環境だとwineが必須になり、環境構築の難易度が跳ね上がるのでMacかWindowsを用いましょう
筆者はWindowsです。

インストール後はご自身が利用している証券会社のIDとパスでログインを行ってください。
最初はデモ口座で試すことを推奨します

ライブラリのインストール

以下が利用しているライブラリ一覧です。
pipコマンドで実行できます。

requirements.txt
MetaTrader5
pandas
datetime
ta

MetaTrader5の基礎構文について

基本的には以下ブログにまとまっています。
その中でもよく使うものを切り取って説明します。

MetaTrader5へのアクセス

以下コードはMetaTrader5へのアクセス時に初期化を行っているかを判断してくれるものです。
エラーハンドリングのために初めに記載してください

main.py
import MetaTrader5 as mt5

if not mt5.initialize():
    print("MT5に接続できません")
    mt5.shutdown()
else:
    print("MT5に接続しました")
MetaTrader5上の登録情報確認

ログイン情報を取得します
今回はログインID、残高、証拠金を取得します

main.py
import MetaTrader5 as mt5

# MT5の起動と接続
if not mt5.initialize():
    print("MT5に接続できません")
    mt5.shutdown()
else:
    print("MT5に接続しました")

# 口座情報の取得
account_info = mt5.account_info()
if account_info:
    print(f"ログインID: {account_info.login}")
    print(f"残高: {account_info.balance}")
    print(f"証拠金: {account_info.equity}")
else:
    print("口座情報を取得できません")
ヒストリカルデータの取得
main.py
import MetaTrader5 as mt5
import pandas as pd

# MT5の初期化
mt5.initialize()

# 取得する通貨ペアと時間足の設定
symbol = "EURUSD"
timeframe = mt5.TIMEFRAME_M1  # 1分足

# 過去100本のローソク足データを取得
rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, 100)

# データをpandasのデータフレームに変換
df = pd.DataFrame(rates)
df['time'] = pd.to_datetime(df['time'], unit='s')  # 時間を変換

# 表示
print(df.head())

# MT5の終了
mt5.shutdown()
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?