How to Connect to MetaTrader 5 with Python
Python Trading Bot
MetaTrader is one of the most popular retail investing platforms on the planet. Many brokers use it, including IC Markets and Blueberry Markets.
For the longest time, programming in MetaTrader was restricted to the MetaQuotes Trading Language — a C++ derivative. While this was great from a speed-of-execution standpoint, it drastically raised the barriers to entry.
MetaTrader 5 (MT5) changed this. As part of the development, a Cython-based Python Trading library was introduced, enabling everyday scripters to access many of the backend functions that had matured over the years.
If you’re looking to use MT5 in your Algorithmic Trading Bot, you’ll need to know how to successfully connect to MT5.
I’ll assume that you’ve already figured out a way to safely import the credentials and variables you’ll need, including:
- Username. This will be an 8-digit integer number
- Password. A random alpha-numeric string, typically 8 characters long
- Server. Provided to you by your broker
- Pathway. The location of the
terminal64.exe
program on your endpoint (by default, stored inC:\Program Files\<broker name>\terminal64.exe
)
P.S. If you haven’t got a way to safely store and import these variables, check out my tutorial below
Two Step Process
Successfully connecting to MetaTrader 5 is actually a 2 step process, the steps being:
- Initialize MetaTrader 5
- Login to MetaTrader 5
If you don’t do the second step (login), you’ll find that there will be times when your script will suddenly fail to pull data, for no discernable reason.
Here’s the full function (including importing the MetaTrader5
python library.
import MetaTrader5
# Function to start Meta Trader 5 (MT5)
def start_mt5(username, password, server, path):
# Ensure that all variables are the correct type
uname = int(username) # Username must be an int
pword = str(password) # Password must be a string
trading_server = str(server) # Server must be a string
filepath = str(path) # Filepath must be a string
# Attempt to start MT5
if MetaTrader5.initialize(login=uname, password=pword, server=trading_server, path=filepath):
# Login to MT5
if MetaTrader5.login(login=uname, password=pword, server=trading_server):
return True
else:
print("Login Fail")
quit()
return PermissionError
else:
print("MT5 Initialization Failed")
quit()
return ConnectionAbortedError
Say Hi!
I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.
❤