import pandas as pd
import MetaTrader5 as mt5

# Set up MetaTrader5 connection
mt5.initialize()

# Path to CSV file containing strategy tester parameters
csv_path = r"C:\Users\bahgat\Documents\Sheet1.csv"

# Name of worksheet containing parameters
worksheet_name = "Sheet1"

# Currency pairs to test
currency_pairs = ["USD/CAD", "EUR/JPY", "EUR/USD", "EUR/CHF", "USD/CHF", "EUR/GBP",
                  "GBP/USD", "AUD/CAD", "NZD/USD", "GBP/CHF", "AUD/USD", "GBP/JPY",
                  "USD/JPY", "CHF/JPY", "EUR/CAD", "AUD/JPY", "EUR/AUD", "AUD/NZD"]

# Number of months to test
test_months = 3

# Create an empty DataFrame with desired column names
results_df = pd.DataFrame(columns=["Symbol", "Period", "Model quality", "Bars in test", "Modelling quality", "Initial deposit", "Total net profit", "Gross profit", "Gross loss", "Profit factor", "Expected payoff", "Absolute drawdown", "Maximal drawdown", "Trades", "Short positions (won %)", "Long positions (won %)", "Profit trades (% of total)", "Loss trades (% of total)", "Largest profit trade", "Largest loss trade"])

def run_backtest(params):
    """
    Runs a backtest with the given parameters and returns the results.
    """

    # Set up backtest parameters
    symbol = params["Symbol"]
    timeframe = int(params["Timeframe"])
    fast_ma_period = int(params["Fast MA Period"])
    fast_ma_method = int(params["Fast MA Method"])
    fast_ma_applied_price = params["Fast MA Applied Price"]
    fast_ma_shift = int(params["Fast MA Shift"])
    slow_ma_period = params.get("Slow MA Period")
    slow_ma_method = int(params["Slow MA Method"])
    slow_ma_applied_price = params["Slow MA Applied Price"]
    slow_ma_shift = params["Slow MA Shift"]
    break_even = params.get("Break Even in pips (zero = not used)",0)
    trailing_stop = params["Trailing Stop (Small = tight, Big = wide)"]
    trailing_step = int(params["Trailing Step in pips (Min increase in SL)"])
    stop_loss = int(params["Stop Loss in pips (zero = not used)"])
    take_profit = int(params["Take Profit in pips (zero = not used)"])
    start_hour = int(params["Start Hour GMT [0-23]"])
    end_hour = int(params["End Hour GMT [0-23]"])
    monday = params["Monday"]
    tuesday = params["Tuesday"]
    wednesday = params["Wednesday"]
    thursday = params["Thursday"]
    friday = params["Friday"]
    saturday = params["Saturday"]
    sunday = params["Sunday"]
    money_management = params["Money Management Behavior"]
    lotsize_multiplier = int(params["Martingale Lotsize Multiplier"])
    magic_number = int(params["Magic Number for trades"])
    custom_order_comment = params["Custom Order Comment"]

    # Set up backtest settings
    settings = mt5.EA_Setup()
    settings.symbol = symbol
    settings.timeframe = timeframe
    settings.fast_ma_period = fast_ma_period
    settings.fast_ma_method = fast_ma_method
    settings.fast_ma_applied_price = fast_ma_applied_price
    settings.fast_ma_shift = fast_ma_shift
    settings.slow_ma_period = slow_ma_period
    settings.slow_ma_method = slow_ma_method
    settings.slow_ma_applied_price = slow_ma_applied_price
    settings.slow_ma_shift = slow_ma_shift
    settings.break_even = break_even
    settings.trailing_stop = trailing_stop
    settings.trailing_step = trailing_step
    settings.stop_loss = stop_loss
    settings.take_profit = take_profit
    settings.start_hour = start_hour
    settings.end_hour = end_hour
    settings.monday = monday
    settings.tuesday = tuesday
    settings.wednesday = wednesday
    settings.thursday = thursday
    settings.friday = friday
    settings.saturday = saturday
    settings.sunday = sunday
    settings.money_management = money_management
    settings.lotsize_multiplier = lotsize_multiplier
    settings.magic_number = magic_number
    settings.custom_order_comment = custom_order_comment

    # Run backtest and get results
    result = mt5.EA_Backtest(settings, test_months)
    return result

def main():
    # Read the CSV file containing strategy tester parameters
    params_df = pd.read_csv(csv_path,encoding='ISO-8859-1')

    # Iterate through each row in the DataFrame
    for index, row in params_df.iterrows():
        params = row.to_dict()
        params["Symbol"] = currency_pairs[index % len(currency_pairs)]
        result = run_backtest(params)

        # Append the result to the results_df DataFrame
        results_df = results_df.append(result, ignore_index=True)

    # Save the results DataFrame to a CSV file
    results_df.to_csv(r"C:\Users\bahgat\Documents\h.csv", index=False)

# Call the main function
main()