MetaTrader 5(MT5)作为 MetaTrader 4(MT4)的继承者,是一款俄罗斯人开发的,在全球外汇零售业务中市场占有率超过70%的交易软件。MetaTrader 5内置了Python的API接口,可以通过Python编程语言进行市场数据分析、交易策略开发和自动化交易等复杂任务。Python以其简单易用的特性,成为科学统计和量化交易领域的首选语言之一,在MT5中使用Python可以极大地提升交易策略的执行效率和准确性,且无需重新学习MT5平台中基于C++开发的MQL语言,降低了编程开发的二次学习成本。本文总结了在Python中安装MT5库和连接MT5账户的流程,为在MT5中进行Python程序开发做好环境配置工作。

一、升级Python包管理工具pip
按照以下流程,将Python的包管理工具pip升级到最新版,以确保Python的本地版本能够匹配MT5模块的最新版。
在Windows中打开CMD窗口,命令行中输入以下命令:
C:\Users\mac>pip install --upgrade pip
窗口中显示如下信息,说明已更新成功。
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pip in c:\program files\windowsapps\pythonsoftwarefoundation.python.3.13_3.13.752.0_x64__qbz5n2kfra8p0\lib\site-packages (24.3.1)
Collecting pip
Using cached pip-25.0.1-py3-none-any.whl.metadata (3.7 kB)
Using cached pip-25.0.1-py3-none-any.whl (1.8 MB)
Installing collected packages: pip
WARNING: The scripts pip.exe, pip3.13.exe and pip3.exe are installed in 'C:\Users\mac\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-25.0.1
二、安装MT5库
在开始使用Python与MT5进行交互之前,首先需要在Python中安装MetaTrader 5库。该库提供了与MT5平台进行通信的必要接口。
1. 安装MetaTrader 5库
要安装 MetaTrader 5 库,可以使用 Python的包管理工具pip。在Windows中打开 CMD 窗口,命令行中输入以下命令:
pip install MetaTrader5
该命令会自动联网,从Python包索引(PyPI)中下载并安装MetaTrader 5库。
窗口中显示如下信息,说明已安装成功。
Defaulting to user installation because normal site-packages is not writeable
Collecting MetaTrader5
Using cached MetaTrader5-5.0.4874-cp313-cp313-win_amd64.whl.metadata (2.4 kB)
Collecting numpy>=1.7 (from MetaTrader5)
Using cached numpy-2.2.3-cp313-cp313-win_amd64.whl.metadata (60 kB)
Using cached MetaTrader5-5.0.4874-cp313-cp313-win_amd64.whl (50 kB)
Downloading numpy-2.2.3-cp313-cp313-win_amd64.whl (12.6 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 12.6/12.6 MB 191.5 kB/s eta 0:00:00
Installing collected packages: numpy, MetaTrader5
WARNING: The scripts f2py.exe and numpy-config.exe are installed in 'C:\Users\mac\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed MetaTrader5-5.0.4874 numpy-2.2.3
另一种方法是,在Pycharm或Spyder等Python的 IDE 环境中,输入以下代码:
pip install MetaTrader5
窗口中显示如下信息,说明已安装成功。
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: MetaTrader5 in c:\programdata\anaconda3\lib\site-packages (5.0.4803)
Requirement already satisfied: numpy>=1.7 in c:\programdata\anaconda3\lib\site-packages (from MetaTrader5) (1.26.4)
Note: you may need to restart the kernel to use updated packages.
2. 检查安装是否成功
安装完成后,可以在Pycharm或Spyder等Python的 IDE 环境中,输入以下代码来检查MetaTrader 5库是否安装成功。这段代码尝试初始化MetaTrader 5库,并打印相应的结果。如果显示“MetaTrader 5 initialized successfully”,说明库安装正确。
import MetaTrader5 as mt5
if mt5.initialize():
print("MetaTrader 5 initialized successfully")
mt5.shutdown()
else:
print("Failed to initialize MetaTrader 5")
三、连接MT5账户
安装好MetaTrader 5库后,下一步是连接到MT5账户。连接前需要准备好账户信息,包括登录号、密码和服务器地址。
1. 登录MT5账户
在Pycharm或Spyder等Python的IDE环境中,输入以下命令连接MT5账户:
import MetaTrader5 as mt5
account = 12345678 # 此处替换为你的登录号
password = "yourpassword" # 此处替换为你的密码
server = "yourserver" # 此处替换为你的服务器地址
if not mt5.initialize():
print("Initialization failed")
mt5.shutdown()
quit()
authorized = mt5.login(account, password, server)
if authorized:
print("Connected to account:", account)
else:
print("Failed to connect to account. Error code:", mt5.last_error())
这段代码尝试连接到MT5账户,并打印连接结果。输入代码后,在Python中点击“Run”或执行箭头按钮,如显示以下内容说明已成功连接账户。
Connected to account: 12345678
2. 检查账户信息
连接成功后,可以获取账户信息,以确保连接到正确的账户。在Pycharm或Spyder等Python的 IDE 环境中,输入以下命令:
account_info = mt5.account_info()
if account_info is not None:
print("Account info:", account_info)
else:
print("Failed to get account info. Error code:", mt5.last_error())
这段代码尝试连接到MT5账户,并显示账户信息。输入代码后,在Python中点击“Run”或执行箭头按钮,如显示以下内容说明已成功显示账户信息。
Account info: AccountInfo(login=12345678, trade_mode=2, leverage=2000000000, limit_orders=0, margin_so_mode=0, trade_allowed=True, trade_expert=True, margin_mode=2, currency_digits=2, fifo_close=False, balance=0.0, credit=0.0, profit=0.0, equity=0.0, margin=0.0, margin_free=0.0, margin_level=0.0, margin_so_call=60.0, margin_so_so=0.0, margin_initial=0.0, margin_maintenance=0.0, assets=0.0, liabilities=0.0, commission_blocked=0.0, name='AAA', server='Exness-MT5Real5', currency='USD', company='Exness Technologies Ltd')
注意其中的这个参数“leverage=2000000000”。Exness平台账户中的资金在1000美元以下时,账户的杠杆是无限倍。这是穷人的核武器,如果能够承受爆仓当作止损的仓位管理策略,在交易方向正确的情况下,几十美元或几百美元的账户一天翻几倍到十几倍的情况经常发生。
让我们引入Python的力量,争取让这种交易奇迹能够自动化地经常发生。