I have my bot set up and working. I implemented the bot turning itself on and off when the market is open and closed. The one problem I have is figuring out how to get the bot to liquidate all positions let’s say around 5 minutes before market close. Does anyone know the best way to implement this? Thanks!
Try following on your paper account:
I just wrote this in Python. Haven’t tested during market hours yet, but works with other times.
import datetime as dt import pytz import pandas as pd def close_all_positions_end_of_day(): # First, check if the market is currently open. No point in checking if closed. if api.get_clock().is_open: # Get the current time (New York time) time_now = dt.datetime.now(pytz.timezone('US/Eastern')) # Calculate the timestamp for 5 mins before close (15:55) today. five_mins_before_end_of_day = pd.Timestamp(year=time_now.year, month=time_now.month, day=time_now.day, hour=15, minute=55, second=00, tz='US/Eastern') # If the current time is the same as (or after) 15:55, close all positions. if time_now.isoformat() >= five_mins_before_end_of_day.isoformat(): print('Closing all positions...') api.close_all_positions() else: print('Not yet 3:55pm!') else: print('Market currently closed!')
Bear in mind that your bot would need to be regularly/frequently calling this function to check if the current time is at/after the timestamp.