Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (2024)

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.

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (1)

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.

  • To install the MT5 desktop version, you can simplyvisit their websiteand follow the instructions.
  • Next, you need to ensure that you have Python installed on your computer. No worries if you don't have Python already! You can easily install it by following the steps outlined inthis blog post.
  • Once you have Python installed, you can open a Jupyter notebook and install the MetaTrader5 package by typing the following command. This will allow you to connect to the MT5 platform from Python:

!pip install MetaTrader5

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (2)

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:

  • In the "Navigator" window on the left-hand side, click on the "Accounts" tab.
  • In the "Accounts" tab, click on the "MetaQuotes-Demo" server.
  • Click the "Open an Account" button in the bottom left corner of the window.
  • In the "Open an Account" dialog box, select "MetaQuotes-Demo" as the server and click "Next".
  • Fill in the required personal information and click "Next".
  • Choose the account type and currency and click "Next".
  • Choose your leverage and deposit amount and click "Next".
  • Copy your account details and click "Finish".

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (3)

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

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (4)

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

Review, "The Python Workshop" (Packt) Dr. Mark Peters, PhD, DSS 1 year ago
How long does it take to learn Python Basic? Aashi Parashar 1 year ago
Unpacking Python's Power: Mastering Packing and… Akhilesh Singh 4 months ago

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.

  • First, you need to specify the symbol and timeframe you want to retrieve data for:
  • symbol ="EURUSD"
  • timeframe = mt5.TIMEFRAME_H1
  • In this example, we are using the EURUSD currency pair and hourly time frame.
  • Next, you need to set the end date and time before which you want to retrieve the data. You can use the datetime module to set the end time to the current time. MT5 takes input in UTC time. Therefore, we are converting the current time to UTC:fromdatetimeimportdatetimeimportpytzend_time = datetime.today().astimezone(pytz.utc)
  • Now you can retrieve the historical data using the copy_rates_from function:eurusd_rates = mt5.copy_rates_from(symbol, timeframe, end_time,10).This retrieves the 10 candles of hourly EURUSD data before the end time.
  • We convert the data to a Pandas DataFrame:eurusd_df = pd.DataFrame(eurusd_rates)

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (8)

  • To convert Unix timestamps to datetime objects, we use the "pd.to_datetime" function with two arguments: the column containing the Unix timestamps and the unit of time. Unix timestamp represents time as seconds since January 1, 1970, at 00:00:00 UTC.
  • eurusd_df['time'] = pd.to_datetime(eurusd_df['time'], unit='s').dt.tz_localize('UTC')
  • We are using the "dt.tz_localize" function to set the timezone of the datetime objects to UTC. This is because the Unix timestamps we retrieved from MT5 are in UTC.
  • Finally, we are using the "dt.tz_convert" function to convert the timezone of the datetime objects in the "time" column from UTC to US/Eastern. This is because we may want to work with the data in a different timezone than UTC.
  • eurusd_df['time'] = eurusd_df['time'].dt.tz_convert('US/Eastern')

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (9)

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

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (10)

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.

Automate Trading using MT5 and Python - Part 2 | Quantra Classroom (2024)
Top Articles
Security of Air Cargo Shipments, Operations, and Facilities
Find your apps in App Library on iPhone
Devotion Showtimes Near Xscape Theatres Blankenbaker 16
Craigslist Monterrey Ca
O'reilly's Auto Parts Closest To My Location
Ffxiv Palm Chippings
Plaza Nails Clifton
Robot or human?
Rondale Moore Or Gabe Davis
Acts 16 Nkjv
Tlc Africa Deaths 2021
Roblox Character Added
Luciipurrrr_
2016 Hyundai Sonata Price, Value, Depreciation & Reviews | Kelley Blue Book
Med First James City
Morocco Forum Tripadvisor
U/Apprenhensive_You8924
Premier Reward Token Rs3
Nwi Arrests Lake County
Les Schwab Product Code Lookup
Slope Tyrones Unblocked Games
NHS England » Winter and H2 priorities
Watch The Lovely Bones Online Free 123Movies
Daylight Matt And Kim Lyrics
Craigslist Appomattox Va
Tinker Repo
Rs3 Eldritch Crossbow
Www.patientnotebook/Atic
Koninklijk Theater Tuschinski
Restored Republic June 16 2023
Pawn Shop Moline Il
Accuradio Unblocked
Meggen Nut
Deepwoken: Best Attunement Tier List - Item Level Gaming
Ravens 24X7 Forum
Kokomo Mugshots Busted
About | Swan Medical Group
Teenage Jobs Hiring Immediately
Staar English 1 April 2022 Answer Key
Collier Urgent Care Park Shore
Skip The Games Grand Rapids Mi
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Natasha Tosini Bikini
Booknet.com Contract Marriage 2
Babykeilani
Arch Aplin Iii Felony
Strange World Showtimes Near Marcus La Crosse Cinema
Paradise leaked: An analysis of offshore data leaks
Every Type of Sentinel in the Marvel Universe
Morgan State University Receives $20.9 Million NIH/NIMHD Grant to Expand Groundbreaking Research on Urban Health Disparities
Who We Are at Curt Landry Ministries
Latest Posts
Article information

Author: Francesca Jacobs Ret

Last Updated:

Views: 6257

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Francesca Jacobs Ret

Birthday: 1996-12-09

Address: Apt. 141 1406 Mitch Summit, New Teganshire, UT 82655-0699

Phone: +2296092334654

Job: Technology Architect

Hobby: Snowboarding, Scouting, Foreign language learning, Dowsing, Baton twirling, Sculpting, Cabaret

Introduction: My name is Francesca Jacobs Ret, I am a innocent, super, beautiful, charming, lucky, gentle, clever person who loves writing and wants to share my knowledge and understanding with you.