Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Live and working IB trading system for Equities

Please post up your examples. Interested to see how people are handling things such stuck orders, unfilled shorts...

1 response
def cancel_all_stale(context, data):  
    now = get_now()  
    sids_cancelled = set()  
    fresh_orders = False  
    open_orders = get_open_orders()  
    for security, orders in open_orders.iteritems():  
        for oo in orders:  
            if ((get_datetime() - oo.dt) > context.order_cancel_working_time):  
                log.warn(str(now) + ": Cancelling order placed at " + str(oo.dt) +  " for " + str(oo.amount) + " shares of " + str(oo.sid.symbol) + "!")  
                sids_cancelled.add(oo.sid)  
                cancel_order(oo)  
            else:  
                fresh_orders = True  
                #log.info(str(now) + ": NOT CANCELLING order for " + str(oo.amount) + " shares of " + str(oo.sid.symbol) + " because it's fresh!")  
    return (sids_cancelled, fresh_orders)

That's something I wrote for stuck/unfilled shorts. I combined it with some code which inverts the usual weights->positions calculation so that if one leg of a hedged basket is partially filled after the above timeout, it calculates an "implied portfolio value" from the existing basket positions to rescale all the other legs downward, so that what you end up with is a hedged, but smaller, basket.