pythonmetatrader5

How to get weekly data on Python MetaTrader 5


I'm developing a script to get historical data. I'm trying to get weekly data but MetaTrader 5 is returning an empty dataframe. I'm using:

import MetaTrader5 as mt5
import pandas as pd

mt5.initialize()

ticks = mt5.copy_rates_range(
    'WIN$N', 
    mt5.TIMEFRAME_W1, 
    datetime(2022, 2, 28),
    datetime(2022, 3, 4)
)

print (pd.DataFrame(ticks))

Why I'm getting an empty dataframe? Using this script with Minutes or Hourly data it works perfectly. I try to look at MT5 documentation but there is none example using WEEKLY or MONTLHY data.


Solution

  • The solution to get weekly and monthly data is (change WIN$N for your stock):

    years = [2001, 2002, 2003, 2004, 2005,
            2006, 2007, 2008, 2009, 2010,
            2011, 2012, 2013, 2014, 2015,
            2016, 2017, 2018, 2019, 2020,
            2021]
    
    months = [1, 2, 3, 4, 5, 6,
             7, 8, 9, 10, 11, 12]
    
    timeframes = {
        'W1' : 1  | 0x8000,
        'MN1': 1  | 0xC000
    }        
    
        
    for year in years:
        for month in months:
            for timeframe in timeframes:
                path = day.strftime("data/" + str(timeframe) + "/%Y/%m")
                os.makedirs(path, exist_ok=True)
                # request tick data
                if month != 12:
                    ticks = mt5.copy_rates_range(
                        'WIN$N', 
                        timeframes[timeframe], 
                        datetime(year, month, 1), 
                        datetime(year, month + timedelta(month=1), 1)
                    )
                    ticks = pd.DataFrame(ticks)
                    ticks.to_csv(path + "/" + str(year) + '_' + str(month) + ".csv")
                else:
                    ticks = mt5.copy_rates_range(
                        'WIN$N', 
                        timeframes[timeframe], 
                        datetime(year, month, 1), 
                        datetime(year, month, calendar.monthrange(ano,mes)[1])
                    )
                    ticks = pd.DataFrame(ticks)
                    ticks.to_csv(path + "/" + str(year) + '_' + str(month) + ".csv")