We've been getting a lot of questions about how to automate trading strategies using MT5 and Python. Since it's a popular topic, we're going to cover it in detail in today's Quantra Classroom. This email is the first part of a two-part series. In this article, we'll talk about the setup you need and how you can get the data. Then, you can learn more about backtesting from Quantra. In the second part, we'll cover how to generate trading signals, manage risk, and place orders.
But why bother automating your trading strategies?Well, when you trade manually, emotions and errors can impact the results of your strategy. But with automated trading, you can remove emotional biases and reduce the chances of mistakes.
Python and MT5 are great tools for automating your trading strategies. Python has powerful libraries for analysing data and developing trading strategies, while MT5 supports automated trading with Expert Advisors and other tools. By combining the two, you can retrieve data, generate signals, and place orders automatically. This can save you time and improve your trading performance.
Step 1: Installation
Please note that the following steps are specific toWindows operating system, as there is currentlyno compatible MetaTrader5 Python package for other operating systems. If you are using an operating system other than Windows, you may consider running these steps on a cloud platform such as Amazon Web Services.
To get started on Windows OS, you need to install two things: the MT5 platform and a Jupyter notebook with the MetaTrader5 package.
!pip install MetaTrader5
Step 2: Open a Demo Account & Get Login Credentials
To start, open the MetaTrader5 platform on your desktop. Once it's open, you'll need to follow a few simple steps to open a demo account:
And that's it! Your login and password for the MetaQuotes-Demo server will be displayed in the "Accounts" tab of the "Navigator" window. The MetaQuotes-Demo server is for demo/training purposes only and does not use real money. Any profits or losses made on this server are not real and do not affect your real trading account.
Step 3: Initialize Connection
To start, you'll need to copy your login account number and password from the previous step. You'll also need to locate theterminal64.exefile, which is usually located in theC:\\Program Files\\MetaTrader 5\\terminal64.exefolder for Windows users.
Once you have these details, you need to set the server toMetaQuotes-Demo. This tells the MetaTrader 5 platform which server to connect to. To initialize your connection, you can use the following code:
importMetaTrader5asmt5
importpandasaspd
importnumpyasnp
path ="C:\\Program Files\\MetaTrader 5\\terminal64.exe"
login = <Your Login Account Here>
password ="<Your Password Here>"
server ="MetaQuotes-Demo"
timeout =10000
portable =False
ifmt5.initialize(path=path, login=login, password=password, server=server, timeout=timeout, portable=portable):
Recommended by LinkedIn
print("Initialization successful")
Once you run this code, you should see a message indicating whether the initialization was successful or not. If it was successful, you're ready to move on to the next step! If not, double-check your login, password, and path to make sure everything is entered correctly.
Step 4: Account Information
You can find important information about your account using the account_info function. It will give you all the details you need to know, like your profit, equity, margin, and margin free.
# get account information
account_info_dict = mt5.account_info()._asdict()
account_info_df = pd.DataFrame(account_info_dict, index=[0])
# display relevant information
print("Profit:", account_info_df["profit"].iloc[0])
print("Equity:", account_info_df["equity"].iloc[0])
print("Margin:", account_info_df["margin"].iloc[0])
print("Margin Free:", account_info_df["margin_free"].iloc[0])
Step 5.1: Retrieve Hourly Data
You can choose the timeframe you want, like hourly or minute, and specify how far back you want to retrieve the data. Then, we convert the data into a Pandas DataFrame, which makes it easy to work with in Python.
Step 5.2: Get Tick Data
This code retrieves tick data for the EUR/AUD currency pair, 20 ticks before the end_time. The mt5.copy_ticks_from() function is used to retrieve the tick data, and the resulting data is converted to a pandas DataFrame using pd.DataFrame().
euraud_tick = mt5.copy_ticks_from("EURAUD", end_time,20, mt5.COPY_TICKS_ALL)
euraud_tick = pd.DataFrame(euraud_tick)
euraud_tick['time'] = pd.to_datetime(euraud_tick['time'], unit='s')
time_msc: The timestamp of the tick data in milliseconds.
You can replicate the steps on your local computer and experiment with different timeframes by adjusting the parameter timeframe. For example, to obtain data for 1-minute intervals, update the code with timeframe = mt5.TIMEFRAME_M1, orchoose any other desired timeframe.
In the next article, we'll learn about generating signals, placing orders and closing positions. But before we move on to automating strategies, it's crucial to backtest and evaluate the effectiveness of our strategy. If you're interested, you can check out the Quantra course on backtesting trading strategies to learn more about backtesting.
If you run into any issues while following the steps specified in the email, don't hesitate to reach out to theQuantra communityfor help.