Cancel old limit orders?


#1

Hi there,

Is there an easy way to automatically cancel a buy limit order that’s been placed, if it hasn’t triggered after a specified amount of time?

thanks,
Jack


#2

Hi Jack,

You can have a look at this one example (there are others as well) in which open orders are being canceled: https://github.com/enigmampc/catalyst/blob/master/catalyst/examples/buy_and_hodl.py
Please let me know if you were referring to something else.

Lena


#3

That example would cancel the order after a minute or so.

If you wanted to have it cancel after a specific amount of time (say, 5 minutes), I’d do the following:

def initialize(context):

context.time_limit = 5
context.limit_percent = 0.99
context.whatever = 1
context.buy_percent = 0.5

def handle_data(context, data):

orders = context.blotter.open_orders
price = data.current(context.market, 'price')
    
if len(orders) > 0:
    context.open_order_timer = context.open_order_timer + 1
    if context.open_order_timer > context.time_limit:
        for order in orders:
            context.oo = context.order1
            cancel_order(context.oo)
            context.open_order_timer = 0

if len(orders) == 0 and price > context.whatever:
    limit_price = price * context.limit_percent
    context.order1 = order_target_percent(context.coin, context.buy_percent, limit_price = limit_price)
    context.open_order_timer = 0

I’m going off of memory (I didn’t save/use this in live trading, but I know it worked in backtesting), but if it doesn’t work, it’s at least 99% there. There might be some sort of formatting issues that you’ll have to adjust.


#4

Thanks for the response Lena


#5

Perfect, this is exactly what I was looking for, thanks @SOG35