Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Cancel Unfilled Open Orders After A Specified Time

I am trying to cancel unfilled limit orders after a specified time (10 minutes). I used the code from "How do you Cancel All Open Orders (on a Friday afternoon) ?" which uses the scheduling function. I need a bit of help here to make it so the canceling is tied to the time the initial order is placed. I am really green here so please forgive my lack of knowledge.

David

3 responses

David,
Here is what I'm doing, which is very close to what you are doing...

All the below is lifted from elsewhere, but the point is to kill all open orders after 60 ticks (if a tick=1 minute, then that is 60 minutes.
The key is that handle_data gets called once per tick.

In initialize, I've got the code:

   context.oo = 0 # Init num of consecutive ticks with open orders(oo=open oprders)

in handle_data, I've got the code:

 # Do nothing if there are open orders:  
    if has_orders(context, data):  
        context.oo = context.oo + 1  
        #print('TicksOfOpenOrders= ', context.oo)  
        if context.oo > 60:  
            kill_open_orders(context, data)  
            print('WARN: KilledOO: TicksOfOpenOrders= ', context.oo)  
        return  
    else:  
        #print("NoOpenOrders at: ", context.oo, "  Reset open orders counter.")  
        context.oo = 0  

and kill_open_orders is:

def kill_open_orders(context, data):  
    for sec, orders in get_open_orders().iteritems():  
        for oo in orders:  
            log.info("X CANCELED {0:s} with {1:,d} / {2:,d} filled"\  
                .format(sec.symbol,  oo.filled, oo.amount))  
            cancel_order(oo)  
    return

Also, has_orders is:

def has_orders(context, data):  
    # Return true if there are pending orders.  
    has_orders = False  
    for sec in data:  
        orders = get_open_orders(sec)  
        if orders:  
            for oo in orders:  
                message = 'Open order for {amount} shares in {stock}'  
                message = message.format(amount=oo.amount, stock=sec)  
                ##log.info(message)

            has_orders = True  
    return has_orders            

alan

That is exactly what I needed.

Thanks Alan!

Glad to help!
alan