from datetime import datetime
import MetaTrader5 as mt5
# MetaTrader 5パッケージについてのデータを表示する
print("MetaTrader5 package author: ",mt5.__author__)
print("MetaTrader5 package version: ",mt5.__version__)
# テーブル形式で取得されたデータを表示するための「pandas」モジュールをインポートする
import pandas as pd
pd.set_option('display.max_columns', 500) # 表示する列の数
pd.set_option('display.width', 1500) # 表示するテーブルの最大幅
# タイムゾーンを使用するためのpytzモジュールをインポートする
import pytz
# MetaTrader 5ターミナルとの接続を確立する
if not mt5.initialize():
print("initialize() failed, error code =",mt5.last_error())
quit()
# タイムゾーンをUTCに設定する
timezone = pytz.timezone("Etc/UTC")
# create 'datetime' objects in UTC time zone to avoid the implementation of a local time zone offset
utc_from = datetime(2020, 1, 10, tzinfo=timezone)
utc_to = datetime(2020, 1, 11, hour = 13, tzinfo=timezone)
# 2020.01.10 00:00-2020.01.11 13:00 UTCでUSDJPY M5からバーを取得する
rates = mt5.copy_rates_range("USDJPY", mt5.TIMEFRAME_M5, utc_from, utc_to)
# MetaTrader 5ターミナルへの接続をシャットダウンする
mt5.shutdown()
# 取得したデータの各要素を新しい行に表示する
print("Display obtained data 'as is'")
counter=0
for rate in rates:
counter+=1
if counter<=10:
print(rate)
# 取得されたデータからDataFrameを作成する
rates_frame = pd.DataFrame(rates)
# 秒での時間を「datetime」形式に変換する
rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s')
# データを表示する
print("\nDisplay dataframe with data")
print(rates_frame.head(10))
結果:
MetaTrader5 package author: MetaQuotes Software Corp.
MetaTrader5 package version: 5.0.29
Display obtained data 'as is'
(1578614400, 109.513, 109.527, 109.505, 109.521, 43, 2, 0)
(1578614700, 109.521, 109.549, 109.518, 109.543, 215, 8, 0)
(1578615000, 109.543, 109.543, 109.466, 109.505, 98, 10, 0)
(1578615300, 109.504, 109.534, 109.502, 109.517, 155, 8, 0)
(1578615600, 109.517, 109.539, 109.513, 109.527, 71, 4, 0)
(1578615900, 109.526, 109.537, 109.484, 109.52, 106, 9, 0)
(1578616200, 109.52, 109.524, 109.508, 109.51, 205, 7, 0)
(1578616500, 109.51, 109.51, 109.491, 109.496, 44, 8, 0)
(1578616800, 109.496, 109.509, 109.487, 109.5, 85, 5, 0)
(1578617100, 109.5, 109.504, 109.487, 109.489, 82, 7, 0)
Display dataframe with data
time open high low close tick_volume spread real_volume
0 2020-01-10 00:00:00 109.513 109.527 109.505 109.521 43 2 0
1 2020-01-10 00:05:00 109.521 109.549 109.518 109.543 215 8 0
2 2020-01-10 00:10:00 109.543 109.543 109.466 109.505 98 10 0
3 2020-01-10 00:15:00 109.504 109.534 109.502 109.517 155 8 0
4 2020-01-10 00:20:00 109.517 109.539 109.513 109.527 71 4 0
5 2020-01-10 00:25:00 109.526 109.537 109.484 109.520 106 9 0
6 2020-01-10 00:30:00 109.520 109.524 109.508 109.510 205 7 0
7 2020-01-10 00:35:00 109.510 109.510 109.491 109.496 44 8 0
8 2020-01-10 00:40:00 109.496 109.509 109.487 109.500 85 5 0
9 2020-01-10 00:45:00 109.500 109.504 109.487 109.489 82 7 0
|