options-automation/iron_condor_scheduler.py

55 lines
1.5 KiB
Python

import schedule
import time
from backtesting import best_entry_times
from datetime import datetime
from dotenv import load_dotenv
from ibkr import Client
from iron_condor import enter_iron_condor
from multiprocessing import Process
from os import getenv
from pytz import timezone
load_dotenv()
eastern_timezone = 'America/New_York'
def enter_trade():
job_process = Process(target = enter_iron_condor)
job_process.start()
def connection_successful():
try:
ibkr_host = getenv('IBKR_HOST')
ibkr_port = getenv('IBKR_PORT')
Client(host = ibkr_host, port = ibkr_port)
return True
except:
return False
if __name__ == '__main__':
if connection_successful():
print('Connected to IBKR.')
now = datetime.now(timezone(eastern_timezone))
entry_times = sorted(best_entry_times())
print(entry_times)
for entry_time in entry_times:
schedule_time = datetime.strptime(entry_time, '%H:%M:%S').replace(
year = now.year,
month = now.month,
day = now.day,
tzinfo = now.tzinfo
)
# Prevent scheduling for times that have already elapsed.
if schedule_time > now:
print(f'Scheduling for {entry_time}.')
schedule.every().day.at(entry_time, eastern_timezone).do(enter_trade)
while True:
schedule.run_pending()
time.sleep(1)
else:
print('ERROR: Cannot connect to IBKR. Ensure that TWS / Gateway is running.')