How to calculate a 200-Day SMA with Python 3 and MetaTrader 5
Automated Trading Bot with MetaTrader5 and Python
There are a ton of signals to analyze when using quantitative analysis for stock/crypto/futures/FOREX trading!
About This Series
This series demonstrates the automated analysis of 8 different market signals.
Using Python 3, Python Pandas, and MetaTrader5, I’ll show you how to calculate 8 common signals.
All code for this tutorial can be found on my GitHub, and I’ve included working code samples throughout (use at your own risk, give me a shout-out if you do).
What You Need
Requirements and assumed knowledge as follows:
- Already connected to MetaTrader 5.
- Windows 10 or above. For reasons known only to MetaTrader, the Python API only works on Windows 😊
- Python 3. This series was built with Python 3.10
The 200-Day SMA
Introduction to the SMA
The Simple Moving Average (SMA) is a popular signal amongst traders. The signal is often used to indicate the support or resistance to price movements. It’s one of the most common trendlines to be seen on a trading chart.
While the SMA can be calculated on any timeframe, it is commonly applied to the close price of a series of days. The three most common time periods are:
- 50-day SMA
- 100-day SMA
- 200-day SMA
In this episode, I’ll show you how to calculate the 200-day SMA.
How to Calculate
How to Code
Generic SMA Function
The first step will be to build a generic SMA calculator. This will calculate the SMA for a defined number of candles across a specified timeframe. I’ll use Pandas to calculate the average (mean).
Here’s the code:
import mt5_interface
import pandas
# Function to search for a defined number of candles across a specified timeframe.
def generic_sma_calculator(symbol, timeframe, num_candles):
# Retrieve the raw data from MT 5
raw_data = mt5_interface.query_historic_data(symbol=symbol, timeframe=timeframe, number_of_candles=num_candles)
# Convert the raw data into a Pandas Dataframe
sma_data = pandas.DataFrame(raw_data)
# Calculate the mean of rows
sma = sma_data['close'].mean()
# Return the mean
return sma
Note. Check out the mt5_interface.py
file if you’re looking for how to connect to MT5.
To demonstrate how this fits into __main__
check out this Gist:
import json
import os
import mt5_interface
import generic_sma
# Set up the import filepath
import_filepath = "settings.json"
# 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__':
# 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"])
mt5_interface.initialize_symbols(project_settings['symbols'])
# Queries
sma = generic_sma.generic_sma_calculator(symbol=project_settings['symbols'][0], timeframe="H1", num_candles=50)
print(sma)
200-Day SMA Function
Abstracting this function, you can create a 200-Day SMA in 2 lines of code (I’ve included the import statement and comments in the code sample below):
import generic_sma
# Function to calculate a 50-day SMA
def calc_200_sma(symbol):
return generic_sma.generic_sma_calculator(symbol=symbol, timeframe="D1", num_candles=200)
If you update your main.py
to import simple_ma_200
and __main__
to use this new function, you’ll get an outcome similar to the below (the number will be different depending on what day and symbol you use):
Wrapping Up
All sorted! You can now include a 200-Day SMA into your Python Trading Bot. Let me know in the comments how you plan on using it!
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.
❤