Overall Statistics
Total Orders
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Start Equity
100000
End Equity
100000
Net Profit
0%
Sharpe Ratio
0
Sortino Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
0
Tracking Error
0
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
Portfolio Turnover
0%
# region imports
from AlgorithmImports import *
from datetime import timezone
# endregion

class CustomTimeRuleAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2021, 1, 4)
        self.set_end_date(2021, 1, 5)
        self.set_cash(100000)
        self.add_equity("SPY", Resolution.MINUTE)
        self.use_extended_hrs = False  # Set to True if you want to use extended market hours

        # Schedule an event using the custom time rule
        self.schedule.on(
            self.date_rules.every_day("SPY"),
            self.custom_time_rule("SPY", timedelta(minutes=5)),
            self.my_scheduled_function
        )

    def custom_time_rule(self, symbol, interval):
        # Define the custom time rule using FuncTimeRule with a lambda function
        return FuncTimeRule(
            name="EveryIntervalDuringMarketHours",
            createUtcEventTimesFunction=lambda dates: [
                dt for date in dates
                for dt in self.get_custom_times(symbol, date, interval)
            ]
        )
    
    def get_custom_times(self, symbol, date, interval):
        # Get market open and close times for the specified date
        exchange = self.securities[symbol].exchange
        market_open = exchange.hours.get_next_market_open(date, self.use_extended_hrs)
        market_close = exchange.hours.get_next_market_close(market_open, self.use_extended_hrs)

        # Convert market times from EST to UTC
        market_open = market_open.replace(tzinfo=timezone(timedelta(hours=-5))).astimezone(timezone.utc)
        market_close = market_close.replace(tzinfo=timezone(timedelta(hours=-5))).astimezone(timezone.utc)
        
        # Generate times every 'interval' minutes between market open and close
        times = []
        current_time = market_open
        while current_time < market_close:
            times.append(current_time)
            current_time += interval
        return times

    def my_scheduled_function(self):
        self.log(f"Executed at: {self.time}")
        self.debug(f"Executed at: {self.time}")