3 min read

How to calculate a 50-Day SMA with Python and MetaTrader 5

Learn how easy it is to calculate a 50-day SMA for your quantitative analysis using Python 3, Python Pandas and MetaTrader 5
How to calculate a 50-Day SMA with Python and MetaTrader 5
Helpful Python Code samples

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. If you’ve been following my previous series “How to Build a MetaTrader 5 Python Trading Bot”, you’ll be able to immediately integrate these into your python Trading Bot.

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. Check out this article to see how to do it!
  • 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 50-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 50-day SMA.

How to Calculate

The calculation for the 50-Day SMA is as follows:

50-Day SMA Formula, part of series 8 Market Signals in 8 Days for Your MetaTrader 5 Python Trading Bot

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__ here is the code:

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)

50-Day SMA Function

Abstracting this function, you can create a 50-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_50_sma(symbol):
    return generic_sma.generic_sma_calculator(symbol=symbol, timeframe="D1", num_candles=50)

If you update your main.py to import simple_ma_50 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):

Demonstration of how the 50-Day SMA code works once integrated into Python. Part of the series 8 Market Signals in 8 Days for Your MetaTrader 5 Python Trading Bot
Demonstration of 50-day SMA being calculated as part of the 8 Market Signals in 8 Days for Your MetaTrader 5 Python Trading Bot

Wrapping Up

I hope that helps! Now you can integrate the 50-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.