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