Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Try to Close All Open Orders Every Minute X Amount of Minutes Prior to Close?

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.

3 responses

I guess I sort of just adapted my code to use a market order to close the positions, and I'm playing with limit orders as well. Seems to work ok, but if anyone still had an idea for the above mentioned loop, that would be cool too. Thanks!

I'm not sure there is a way to get the function to loop for 15 minutes. You could call the function every minute left in the day with something like:

for i in range(1, 15):
offset = i
schedule_function(close_all_positions,date_rules.week_end(),time_rules.market_close(offset=i))

That would be exactly what I'm after. Thanks for the help, I'll work with that.