img

How to Build a MetaTrader 5 Python Trading Bot: Getting Started

img
valuezone 06 October 2022

How to Build a MetaTrader 5 Python Trading Bot: Getting Started

Ever wanted to build an automated trading bot? Got a strategy in mind? Got some skills in Python?

My new series “How to Build a Meta Trader 5 Python Trading Bot” was written just for you.

About the Series

The series shows you how to build your very own Python Trading Bot for Meta Trader 5 using the MetaTrader module for Python.

The series assumes that you have a working knowledge of Python scripting, know how to use an IDE and understand the basics of trading (stop loss, take profit, and so on). All code is used at your own discretion and risk, including developing your own strategy 😊

In This Episode

By the end of this episode, your project will be set up and MT5 will be getting started by Python.

Getting Started

About MetaTrader5

MetaTrader5 (MT5) is one of the most widely used retail trading platforms for Foreign Exchange (Forex), Stocks, and Futures on the planet. Many large brokers (for instance IC Markets) provide it to their retail clients.

Before MT5, there was Meta Trader 4 (MT4). For our purposes, the biggest functional difference between MT4 and MT5 is the Python-based Application Programming Interface (API) implemented in MT5. This expanded the previous C++ based Meta Query Language (MQL) into the more readable and vastly more popular Python Programming Language.

What You Need

For the rest of this series, you need the following:

  • A Windows 10 or above computer (for reasons known only to Meta Trader, the macOS and Linux versions of MT5 don’t interface with Python)
  • Python 3 installed (I used Python 3.10 for this series)
  • A trading account set up through your broker (I highly recommend that you use a Demo Account for this series)

Project Setup

Your project will use main.py and three other files. Set these up now in your IDE of choice (I use Jetbrains Pycharm):

  • main.py — the main function for our trading bot
  • mt5_interface.py — our interface with MT5
  • strategy.py — our trading strategy
  • settings.json — your project settings. If you’re using a Version Control System (VCS), immediately add your settings.json to .gitignore or equivalent

It should look something like this:


How to build a Meta Trader 5 Python Trading Bot setup

Loading Your Settings

For this series, all settings variables are stored in JSON format in a separate file called settings.json. JSON is used as it is a widely used text-based format for representing structured data, especially on websites, and it is stored in a separate file to prevent the hard-coding of sensitive information into scripts.

An example of what settings.json looks like can be found in the file example_settings.json, linked to GitHub here. This file contains the full list of settings needed for the tutorial, with any sensitive information removed.

Let’s get settings.json implemented.

Set Up settings.json

Four variables are needed initially:

  • username — the username being used for your MT5 login (demo account!)
  • password — the password for the MT5 login
  • server — the server your broker gives you to log in to
  • mt5Pathway — this is the pathway to your MT5 .exe on windows

Typically the username, password, and server variables are provided by your broker, while the mt5Pathway is where your MT5 executable is stored. Here’s what mine looked like (fake information used for username/password 😊):

{
"username": "your_username - typically an 8 digit number",
"password": "Do not share with anyone!",
"server": "ICMarkets-Demo",
"mt5Pathway": "C:/Program Files/ICMarkets - MetaTrader 5/terminal64.exe"
}

Importing Settings Function

Next, you need to import these settings into the program. This will be done through main.py Here’s the function:


Function to get project settings for How to Build a MetaTrader 5 Python Trading Bot

In this code we:

  • Imported the libraries json and os
  • Tested if the filepath provided works, returning an ImportError if it didn’t
  • Returned the settings from the file

Import Settings Through Main

Now, still in main.py, add two more lines under the if __name__ == '__main__':

  • import_filepath = "Path/To/Your/Settings.json" the filepath to your settings
  • project_settings = get_project_settings(import_filepath) retrieve the project settings

Here’s what your main function should look like (your filepath will probably be different):

# Main function
if __name__ == '__main__':
import_filepath = "C:/Users/james/PycharmProjects/how_to_build_a_metatrader5_trading_bot_expert_advisor/settings.json"
project_settings = get_project_settings(import_filepath)
Initial __main__ function for How to Build a MetaTrader 5 Python Trading Bot

Start MetaTrader5 with Python

Awesome work on getting your settings imported!

The next stage is to initialize your MT5 using Python. Let’s get going!

MetaTrader5 Python API

The MetaTrader5 Python API, while extensive, can be quite fiddly. Ensuring that variables are explicitly cast to their correct type (int, float, string, etc) is always required.

Quick Note. I know for many of my advanced programming readers this is not uncommon. Especially for those who use languages like Rust, C, Go, etc. However, for those with simple Pythonic experience, this can be quite the wake-up call!

Starting MT5

MT5 can be ‘fiddly’ to get started. In my experience, the only consistent way to ensure that it is started AND working properly is to implement two functions: initialize and login. Weirdly enough, there have been times when I’ve initialized but not logged in and MT5 has worked. Many tutorials only talk about the initialize function, which can leave you stranded when it doesn’t work ❤

The function below includes both initialize and login . This __should__ ensure a consistent startup experience and save you many hours of troubleshooting.

Implement this function in the mt5_interface.py file created at the start of the tutorial.

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):
print("Trading Bot Starting")
# Login to MT5
if MetaTrader5.login(login=uname, password=pword, server=trading_server):
print("Trading Bot Logged in and Ready to Go!")
return True
else:
print("Login Fail")
quit()
return PermissionError
else:
print("MT5 Initialization Failed")
quit()
return ConnectionAbortedError
view rawmt5_interface.py hosted with ❤ by GitHub
Starting MT5 using Python for How to Build a MetaTrader 5 Python Trading Bot

Next, in main.py include the following:

  • import mt5_interface at the top of the file
  • In __main__ , add mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server], project_settings["mt5Pathway"])

Hit Play on your IDE now and MetaTrader5 should start! Sweet!

If you go to your Journal on MT5, you will see that your account has been authorized and synchronized:

MT5 Successfully Authorized

Main.py

Here’s what your main.py should look like (a few comments added):

import json
import os
import mt5_interface
# Function to import settings from settings.json
def get_project_settings(importFilepath):
# Test the filepath to sure it exists
if os.path.exists(importFilepath):
# Open the file
f = open(importFilepath, "r")
# Get the information from file
project_settings = json.load(f)
# Close the file
f.close()
# Return project settings to program
return project_settings
else:
return ImportError
# Main function
if __name__ == '__main__':
# Set up the import filepath
import_filepath = "settings.json"
# Import project settings
project_settings = get_project_settings(import_filepath)
# Start MT5
mt5_interface.start_mt5(project_settings["username"], project_settings["password"], project_settings["server"],
project_settings["mt5Pathway"])
view rawmain.py hosted with ❤ by GitHub