Automating a Trading System Using Python, MetaTrader 5, and Mean Reversion Theory

Sourabh KumarSourabh Kumar
4 min read

Automating trading systems has gained significant traction due to their ability to make data-driven decisions without constant human intervention. This article explores a Python-based automated trading system using MetaTrader 5 (MT5) and Mean Reversion theory, focusing on the logic behind the algorithm and its advantages and disadvantages.

Overview of the Trading System

The core of this automated trading system involves several key components:

  • MetaTrader 5: The platform handles the execution of buy/sell orders based on the signals generated by the algorithm.

  • Socket Communication: The system uses socket programming to receive real-time OHLC (Open, High, Low, Close) data, vital for making informed trading decisions.

  • Mean Reversion Theory: This strategy assumes that asset prices will revert to their mean (average) over time. When the price deviates significantly from this average, it creates opportunities to buy low or sell high.

Code Breakdown

  1. Socket Setup and Real-time Data Feed: The system receives live OHLC data through a socket connection. This data is processed and stored in a pandas DataFrame, which calculates indicators like SMA (Simple Moving Average), EMA (Exponential Moving Average), and the Z-score.

Example Code:

import socket
import pandas as pd
from datetime import datetime

# Initialize socket connections
buffer_size = 1024
s_data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_data.bind(("localhost", 78))  # Data port
s_data.listen(10)
print("[INFO]\tWaiting for a connection...")
connection, addr = s_data.accept()
print("[INFO]\tConnection established with:", addr)

# DataFrame to store received data
ohlc_data = pd.DataFrame(columns=['time', 'symbol', 'open', 'high', 'low', 'close'])

# Define the moving average window
window = 20

def calculate_sma(data, window):
    return data.rolling(window=window).mean()

def calculate_ema(data, window):
    return data.ewm(span=window, adjust=False).mean()

# Define thresholds for Z-score
z_threshold = 2
  1. Mean Reversion Strategy: The strategy involves calculating the Z-score to measure how far the price deviates from its moving average. When the Z-score crosses predefined thresholds, it signals the system to either buy (when the score is low) or sell (when the score is high).

Example Code:

while True:
    try:
        data_received = connection.recv(buffer_size).decode('ascii')
        if not data_received:
            break

        # Parse the received data
        data_list = data_received.split(", ")
        time_str = data_list[0].split(": ")[1]
        symbol = data_list[1].split(": ")[1]
        open_price = float(data_list[2].split(": ")[1])
        close_price = float(data_list[3].split(": ")[1])
        high_price = float(data_list[4].split(": ")[1])
        low_price = float(data_list[5].split(": ")[1])

        time_value = datetime.strptime(time_str, '%Y.%m.%d %H:%M')

        # Extract OHLC data
        new_row = {
            'time': time_value,
            'symbol': symbol,
            'open': open_price,
            'high': high_price,
            'low': low_price,
            'close': close_price
        }

        # Convert new row to DataFrame and concatenate
        new_row_df = pd.DataFrame([new_row])
        ohlc_data = pd.concat([ohlc_data, new_row_df], ignore_index=True)

        # Ensure there are enough data points to calculate indicators
        if len(ohlc_data) >= window:
            ohlc_data['SMA'] = calculate_sma(ohlc_data['close'], window)
            ohlc_data['EMA'] = calculate_ema(ohlc_data['close'], window)
            ohlc_data['stddev'] = ohlc_data['close'].rolling(window=window).std()
            ohlc_data['zscore'] = (ohlc_data['close'] - ohlc_data['SMA']) / ohlc_data['stddev']
  1. Order Placement and Closing: The system automates the order execution using the mt5.order_send() function. Based on the Z-score signals, the system places buy or sell orders and closes existing positions when conditions are met.

Example Code:

import MetaTrader5 as mt5

def place_order(symbol, order_type, lot=0.4, deviation=20):
    price = mt5.symbol_info_tick(symbol).ask if order_type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(symbol).bid
    point = mt5.symbol_info(symbol).point
    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": order_type,
        "price": price,
        "sl": price - 50 * point,
        "tp": price + 80 * point,
        "deviation": deviation,
        "magic": 234000,
        "comment": "python script open",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }
    result = mt5.order_send(request)
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print(f"order_send failed, retcode={result.retcode}")
        return None
    else:
        print(f"Order sent successfully: {result}")
        return result.order

Advantages of Using Mean Reversion Strategy

  1. Simplicity and Reliability: Mean reversion strategies are straightforward and work well in markets where prices fluctuate around an average value.

  2. Clear Entry and Exit Points: The Z-score provides definitive signals for entering and exiting trades, minimizing guesswork.

  3. Low Transaction Frequency: This strategy typically leads to fewer trades, reducing transaction costs and slippage.

Disadvantages of the Strategy

  1. Not Suitable for Trending Markets: In strong trending markets, mean reversion may generate false signals, leading to losses.

  2. Lagging Indicators: Moving averages and Z-scores are lagging indicators, which means they might react slowly to sudden market changes.

  3. Risk of Large Drawdowns: If prices continue deviating from the mean without reverting, the strategy could accumulate losses.

Visualization of the Strategy

The following images could help in understanding the algorithm's functioning better:

  1. OHLC Chart with SMA/EMA Overlay: A visual representation showing how the system tracks the price along with moving averages.

  2. Z-Score Thresholds and Trade Signals: A chart displaying Z-scores over time, highlighting buy/sell zones based on threshold levels.

  3. Order Placement and Closing: A sequence showing when and how orders are placed and closed based on signal generation.

This automated trading system leverages the robust MetaTrader 5 platform, allowing traders to execute mean reversion strategies in real-time efficiently. While this approach has its limitations, it remains a powerful tool in markets that exhibit mean-reverting behaviors.

0
Subscribe to my newsletter

Read articles from Sourabh Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sourabh Kumar
Sourabh Kumar