读取报价

Python API 允许您使用三个函数来获取价格数组(柱线),这三个函数在指定请求数据范围的方式上有所不同:按柱线编号或按时间。所有函数都类似于不同形式的 CopyRates

对于所有函数,前两个参数用于指定交易品种名称和时间范围。时间范围列于 TIMEFRAME 枚举中,它类似于 MQL5 中的 ENUM_TIMEFRAMES 枚举。

请注意:在 Python 中,该枚举的元素以 TIMEFRAME_ 为前缀,而 MQL5 中类似枚举的元素以 PERIOD_ 为前缀。

标识符

说明

TIMEFRAME_M1

1 分钟

TIMEFRAME_M2

2 分钟

TIMEFRAME_M3

3 分钟

TIMEFRAME_M4

4 分钟

TIMEFRAME_M5

5 分钟

TIMEFRAME_M6

6 分钟

TIMEFRAME_M10

10 分钟

TIMEFRAME_M12

12 分钟

TIMEFRAME_M12

15 分钟

TIMEFRAME_M20

20 分钟

TIMEFRAME_M30

30 分钟

TIMEFRAME_H1

1 小时

TIMEFRAME_H2

2 小时

TIMEFRAME_H3

3 小时

TIMEFRAME_H4

4 小时

TIMEFRAME_H6

6 小时

TIMEFRAME_H8

8 小时

TIMEFRAME_H12

12 小时

TIMEFRAME_D1

1 天

TIMEFRAME_W1

1 周

TIMEFRAME_MN1

1 个月

这三个函数都将柱线作为 numpy 批处理数组返回,其中包含命名列 timeopenhighlowclosetick_volumespreadreal_volumenumpy.ndarray 数组类似于命名元组,但更高效。要访问列,请使用方括号表示法,例如 array['column']

None 如果发生错误,则不返回任何值。

所有函数参数都是强制的和未命名的。

numpy.ndarray copy_rates_from(symbol, timeframe, date_from, count)

copy_rates_from 函数请求从指定日期 (date_from) 开始、count 根柱线的数据。该日期可以由 datetime 对象设置,或者设置为自 1970.01.01 以来经历的秒数。

创建 datetime 对象时,Python 使用本地时区,而 MetaTrader 5 终端使用 UTC(GMT,无偏移)存储分时报价和柱线的开盘时间。因此,要执行使用时间的函数,必须以 UTC 格式创建datetime变量。要配置时区,可以使用pytz软件包。例如(参见 MQL5/Scripts/MQL5Book/Python/eurusdrates.py):

from datetime import datetime
import MetaTrader5 as mt5   
import pytz                    # import the pytz module to work with the timezone
# let's establish a connection to the MetaTrader 5 terminal
if not mt5.initialize():
   print("initialize() failed, error code =", mt5.last_error())
   mt5.shutdown()
   quit()
   
# set the timezone to UTC
timezone = pytz.timezone("Etc/UTC")
   
# create a datetime object in the UTC timezone so that the local timezone offset is not applied
utc_from = datetime(2022110, tzinfo = timezone)
   
# get 10 bars from EURUSD H1 starting from 10/01/2022 in the UTC timezone
rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_H1, utc_from, 10)
   
# complete the connection to the MetaTrader 5 terminal
mt5.shutdown()
   
# display each element of the received data (tuple)
for rate in rates:
   print(rate)

接收数据的范例:

(1641567600, 1.12975, 1.13226, 1.12922, 1.13017, 8325, 0, 0)
(1641571200, 1.13017, 1.13343, 1.1299, 1.13302, 7073, 0, 0)
(1641574800, 1.13302, 1.13491, 1.13293, 1.13468, 5920, 0, 0)
(1641578400, 1.13469, 1.13571, 1.13375, 1.13564, 3723, 0, 0)
(1641582000, 1.13564, 1.13582, 1.13494, 1.13564, 1990, 0, 0)
(1641585600, 1.1356, 1.13622, 1.13547, 1.13574, 1269, 0, 0)
(1641589200, 1.13572, 1.13647, 1.13568, 1.13627, 1031, 0, 0)
(1641592800, 1.13627, 1.13639, 1.13573, 1.13613, 982, 0, 0)
(1641596400, 1.1361, 1.13613, 1.1358, 1.1359, 692, 1, 0)
(1641772800, 1.1355, 1.13597, 1.13524, 1.1356, 1795, 10, 0)

 

numpy.ndarray copy_rates_from_pos(symbol, timeframe, start, count)

copy_rates_from_pos 函数请求从指定 start 索引开始、count 根柱线的数据。

MetaTrader 5 终端仅在图表上用户可见的历史范围内呈现柱线。用户可见的柱线数量由设置中的“窗口中的最大柱线数”参数设定。

以下例子 (MQL5/Scripts/MQL5Book/Python/ratescorr.py) 展示了基于报价的几种货币的相关矩阵的图形表示。

import MetaTrader5 as mt5
import pandas as pd              # connect the pandas module to output data
import matplotlib.pyplot as plt  # connect the matplotlib module for drawing
   
# let's establish a connection to the MetaTrader 5 terminal
if not mt5.initialize():
   print("initialize() failed, error code =", mt5.last_error())
   mt5.shutdown()
   quit()
   
# create a path in the sandbox for the image with the result
image = mt5.terminal_info().data_path + r'\MQL5\Files\MQL5Book\ratescorr'
   
# the list of working currencies for calculating correlation
sym = ['EURUSD','GBPUSD','USDJPY','USDCHF','AUDUSD','USDCAD','NZDUSD','XAUUSD']
   
# copy the closing prices of bars into DataFrame structures
d = pd.DataFrame()
for i in sym:        # last 1000 M1 bars for each symbol
   rates = mt5.copy_rates_from_pos(i, mt5.TIMEFRAME_M1, 01000)
   d[i] = [y['close'for y in rates]
   
# complete the connection to the MetaTrader 5 terminal
mt5.shutdown()
   
# calculate the price change as a percentage
rets = d.pct_change()
   
# compute correlations
corr = rets.corr()
   
# draw the correlation matrix
fig = plt.figure(figsize = (55))
fig.add_axes([0.150.10.80.8])
plt.imshow(corr, cmap = 'RdYlGn', interpolation = 'none', aspect = 'equal')
plt.colorbar()
plt.xticks(range(len(corr)), corr.columns, rotation = 'vertical')
plt.yticks(range(len(corr)), corr.columns)
plt.show()
plt.savefig(image)

图像文件ratescorr.png是在 MetaTrader 5 的当前工作副本的沙盒中形成的。如果你 Python 安装不包括可选功能“tcl/tk 和 IDLE”或者如果你没有添加 pip install.tk 软件包,则通过调用 plt.show() 在单独的窗口中交互显示图像可能不起作用。

外汇货币相关矩阵

外汇货币相关矩阵

numpy.ndarray copy_rates_range(symbol, timeframe, date_from, date_to)

copy_rates_range 函数允许您获取 date_fromdate_to 之间的指定日期和时间范围内的柱线:这两个值作为 UTC 时区中自 1970 年开始的秒数给出(由于 Python 使用 datetime 当地时区,因此应使用 pytz 模块进行转换)。结果包括开盘时间在 time >= date_fromtime <= date_to 的柱线。

在下面的脚本中,我们将请求特定时间范围内的柱线。

from datetime import datetime
import MetaTrader5 as mt5
import pytz             # connect the pytz module to work with the timezone
import pandas as pd     # connect the pandas module to display data in a tabular form
   
pd.set_option('display.max_columns'500# how many columns to show
pd.set_option('display.width'1500)      # max. table width to display
   
# let's establish a connection to the MetaTrader 5 terminal
if not mt5.initialize():
   print("initialize() failed, error code =", mt5.last_error())
   quit()
   
# set the timezone to UTC
timezone = pytz.timezone("Etc/UTC")
# create datetime objects in UTC timezone so that local timezone offset is not applied
utc_from = datetime(2020110, tzinfo=timezone)
utc_to = datetime(2020110, minute = 30, tzinfo=timezone)
   
# get bars for USDJPY M5 for period 2020.01.10 00:00 - 2020.01.10 00:30 in UTC timezone
rates = mt5.copy_rates_range("USDJPY", mt5.TIMEFRAME_M5, utc_from, utc_to)
   
# complete the connection to the MetaTrader 5 terminal
mt5.shutdown()
   
# create a DataFrame from the received data
rates_frame = pd.DataFrame(rates)
# convert time from number of seconds to datetime format
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit = 's')
   
# output data
print(rates_frame)

结果示例:

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 0:05:00 109.521 109.549 109.518 109.543 215 8 0

2 2020-01-10 0:10:00 109.543 109.543 109.466 109.505 98 10 0

3 2020-01-10 0:15:00 109.504 109.534 109.502 109.517 155 8 0

4 2020-01-10 0:20:00 109.517 109.539 109.513 109.527 71 4 0

5 2020-01-10 0:25:00 109.526 109.537 109.484 109.520 106 9 0

6 2020-01-10 0:30:00 109.520 109.524 109.508 109.510 205 7 0