How to Use schedule_function and time_rules in IBridgePy
Why Scheduling Matters in Algorithmic Trading
Most trading strategies do not need to evaluate every tick. A mean-reversion strategy might check prices every 5 minutes. A portfolio rebalancer might run once per day at close. An earnings-based strategy might execute only at market open. IBridgePy provides schedule_function() to precisely control when your code runs, reducing unnecessary computation and avoiding unintended trades.
Basic Syntax
def initialize(context):
schedule_function(function_to_run, time_rule=time_rules.some_rule())
The function you schedule must accept context as its only parameter:
def my_scheduled_task(context):
# Your logic here
pass
Available time_rules
market_open and market_close
Run relative to market hours (US stock market: 9:30 AM - 4:00 PM Eastern):
def initialize(context):
# Run 5 minutes after market opens (9:35 AM ET)
schedule_function(morning_check,
time_rule=time_rules.market_open(minutes=5))
# Run 10 minutes before market closes (3:50 PM ET)
schedule_function(eod_rebalance,
time_rule=time_rules.market_close(minutes=10))
spot_time
Run at an exact time (Eastern timezone):
def initialize(context):
# Run at exactly 10:30 AM Eastern
schedule_function(midmorning_scan,
time_rule=time_rules.spot_time(hour=10, minute=30))
# Run at 3:45 PM for MOC order decisions
schedule_function(moc_decision,
time_rule=time_rules.spot_time(hour=15, minute=45))
every_minute
Run the function on every handle_data cycle (frequency depends on your configuration):
def initialize(context):
schedule_function(check_stops, time_rule=time_rules.every_minute())
Multiple Scheduled Functions
You can schedule as many functions as needed. They will all be checked on each cycle and fire when their time condition is met:
def initialize(context):
# Morning: scan for opportunities
schedule_function(scan_universe,
time_rule=time_rules.market_open(minutes=30))
# Midday: check existing positions
schedule_function(position_check,
time_rule=time_rules.spot_time(hour=12, minute=0))
# End of day: send summary email
schedule_function(daily_summary,
time_rule=time_rules.spot_time(hour=16, minute=30))
def scan_universe(context):
print(f'Scanning at {get_datetime()}')
# ... scanning logic ...
def position_check(context):
print(f'Checking positions at {get_datetime()}')
# ... position management ...
def daily_summary(context):
print(f'Sending summary at {get_datetime()}')
# ... email/notification logic ...
Practical Example: Market-on-Close Order Strategy
This example demonstrates a strategy that makes trading decisions at 3:45 PM and places Market-on-Close (MOC) orders before the 3:50 PM cutoff:
def initialize(context):
context.security = symbol('SPY')
schedule_function(daily_decision,
time_rule=time_rules.spot_time(hour=15, minute=45))
def daily_decision(context):
# Get today's price data
hist = request_historical_data(context.security, '1 day', '5 D')
today_return = (hist['close'].iloc[-1] - hist['close'].iloc[-2]) / hist['close'].iloc[-2]
# Mean reversion: buy after a down day, sell after an up day
current_position = int(get_position(context.security).amount)
if today_return < -0.01 and current_position == 0:
order_id = order(context.security, 100,
style=MarketOnCloseOrder())
print(f'MOC BUY signal: return={today_return:.3f}')
elif today_return > 0.01 and current_position > 0:
order_id = order(context.security, -current_position,
style=MarketOnCloseOrder())
print(f'MOC SELL signal: return={today_return:.3f}')
Tips for Effective Scheduling
- Use spot_time for precision: When your strategy has a hard deadline (like MOC order cutoffs at 3:50 PM), use
spot_timerather thanmarket_close(minutes=10)to avoid any ambiguity. - Keep scheduled functions fast: Each scheduled function blocks the main loop. If computation takes more than a few seconds, consider pre-computing results in an earlier time slot.
- Test timing with paper trading: Schedule functions execute based on the system clock. Always verify timing with a paper trading account first.
- All times are Eastern: IBridgePy uses US Eastern timezone for all time rules. Adjust accordingly if you trade international markets.
For the complete API reference, visit our documentation page. For more strategy patterns, check our tutorials.
