Hey everyone,
I have a weekly trading strategy that buys 5 stocks Monday morning, and tries to sell all 5 of them about 15 minutes before market close on every Friday. I'm running into issues with the orders not getting filled at the 15 minute mark, and the orders get cancelled until my next close_orders type function tries again on Monday morning. I'm trying to alleviate holding positions over the weekend. Is there a way that one might be able to try and sell all currently open buy orders 15 minutes prior to Friday's close, and if any of them don't get filled, try again the next minute, and the next minute, until the market is closed?
This is the code I'm currently using:
def initialize(context):
context.minutes_before_close = 15
# SCHEDULE FUNCTIONS
# Close all positions at the end of the week, 15 minutes (default above) prior to the close
schedule_function(close_all_positions,
date_rule=date_rules.week_end(),
time_rule=time_rules.market_close(minutes=context.minutes_before_close)
)
def close_all_positions(context, data):
"""Close all positions."""
# Cancel orders first
cancel_open_orders()
if PRINT_EXITS:
log.info('Closing all positions for the end of the trading period.')
for asset, position in context.portfolio.positions.items():
if PRINT_EXITS:
log.info(' Close position for {} shares of {}'.format(
position.amount, asset.symbol))
order_target_value(asset, 0.0)
def cancel_open_orders():
"""Cancel all open orders."""
for asset, orders in get_open_orders().items():
for order in orders:
cancel_order(order)
I'm wondering if there's some kind of loop that would go in the "def close_all_positions(context, data):" function, something along the lines of:
for every_minute_left_in_the_day, try to close_the_order?
Thanks in advance.