avatarJames Hinton

Summary

This content is a tutorial on building a MetaTrader5 Python trading bot, with a focus on setting up the project and starting MetaTrader5 with Python.

Abstract

The tutorial starts by introducing the MetaTrader5 Python trading bot and the need for a working knowledge of Python and trading basics. It then moves on to explain the project setup, including the creation of four files: main.py, mt5_interface.py, strategy.py, and settings.json. The tutorial provides examples of what these files should look like and how they should be structured. It then explains how to load the settings from settings.json into the program using a function called get_project_settings(). The tutorial concludes by explaining how to start MetaTrader5 with Python using the initialize() and login() functions.

Bullet points

  • The tutorial is about building a MetaTrader5 Python trading bot.
  • The tutorial assumes a working knowledge of Python and trading basics.
  • The project setup includes creating four files: main.py, mt5_interface.py, strategy.py, and settings.json.
  • The settings.json file contains settings variables in JSON format, which are imported into the program using the get_project_settings() function.
  • The tutorial explains how to start MetaTrader5 with Python using the initialize() and login() functions.
  • The tutorial is part of a series and includes links to other episodes and resources.
Image from Adobe Stock, published under the Standard Licence

MetaTrader5 Python Trading Bot

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.

Update August 2023

I could never have anticipated how popular this series, along with a YouTube channel would become.

After a listening to my readers/viewers feedback, I realized that many people were spending huge amounts of time trying to solve installation/configuration problems — rather than experiencing the joy of algorithmic trading.

I want to change this narrative — and in so doing, open up algorithmic trading for everyone.

To do this, I’ve recently launched Tradeoxy: Trading For Everyone.

If you’re reading this, Tradeoxy will simplify 90% of this series, using a series of powerful API’s and easy to use tooling.

Currently it’s in the early-access / building stage and I’d be incredibly grateful if you’d join us on this adventure. Your feedback will help us shape a better product.

Join the early access program (for free) here.

You can also view our launch video, and follow our journey on LinkedIn, Twitter, Instagram, YouTube.

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:

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):

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.

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):

Conclusion

And that’s a wrap for Episode 1. Nice work!

So far you’ve set up your project and automatically initialized your MT5 program. You’re well on your way to using MetaTrader 5 with Python!

In the next episode, you’ll be implementing your trading functions for MT5. See you there.

List of Episodes

  1. Getting Started
  2. Making Trades
  3. Automated Strategy
  4. Automated Trading
  5. Bonus: MetaTrader 5 Python Trailing Stop

Say Hi or Give a Clap

I love hearing from my readers! Feel free to drop a comment or reach out on LinkedIn.

Resources

  1. Project GitHub Repo
  2. MQL5 Python Library
  3. IC Markets
  4. Jetbrains Pycharm
Programming
Data Science
Machine Learning
Technology
Artificial Intelligence
Recommended from ReadMedium
avatarAakash Chavan Ravindranath, Ph.D
🚨 Why You Need an Alternative to yfinance

3 min read