Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
error - UnboundLocalError: local variable 'order_id' referenced before assignment

Anyone have a clue why the code below generates the error "UnboundLocalError: local variable 'order_id' referenced before assignment" on the line:

filled = bool(get_order(order_id)['filled'])  

I'm running on minute data, if it matters.

def initialize(context):  
    context.first = True  
    context.stock = sid(24)  
def handle_data(context, data):  
    record(Price = data[context.stock].close_price)  
    record(OpenOrders = 1 if bool(get_open_orders(context.stock)) else 0)  
    record(Notional = context.portfolio.positions[context.stock].amount * data[context.stock].close_price)  
    if context.first:  
        order_id = order(context.stock, 100, limit_price= 450)  
        context.first = False  
    filled = bool(get_order(order_id)['filled'])  
    if filled:  
        order(context.stock, -100, stop_price = 400)  
5 responses

It is the second call of handle data. context.first is then false and the local variable is gone (order_id)

Run the below and the log file will show it is the second call that breaks.

def initialize(context):  
    context.first = True  
    context.stock = sid(24)  
def handle_data(context, data):  
    record(Price = data[context.stock].close_price)  
    record(OpenOrders = 1 if bool(get_open_orders(context.stock)) else 0)  
    record(Notional = context.portfolio.positions[context.stock].amount * data[context.stock].close_price)  
    log.debug(str(context.first))  
    if context.first:  
        order_id = order(context.stock, 100, limit_price= 450)  
        context.first = False  
    filled = bool(get_order(order_id)['filled'])  
    if filled:  
        order(context.stock, -100, stop_price = 400)  

Thanks...end of a long day. Yes, of course. --Grant

Modified it a bit, and got it running:

def initialize(context):  
    context.market = False  
    context.stop_loss = False  
    context.stock = sid(24)  
    context.order_ids = []  
def handle_data(context, data):  
    record(Price = data[context.stock].close_price)  
    record(OpenOrders = 1 if bool(get_open_orders(context.stock)) else 0)  
    record(Notional = context.portfolio.positions[context.stock].amount * data[context.stock].close_price)  
    if not context.market:  
        context.order_ids.append(order(context.stock, 100, limit_price= 450))  
        context.market = True  
    filled = bool(get_order(context.order_ids[0])['filled'])  
    if filled and not context.stop_loss:  
        context.order_ids.append(order(context.stock, -100, stop_price = 400))  
        context.stop_loss = True  

No worries...we've all been there.

Im having the same error, what exactly did you modify besides adding the line context.order_ids = [] ?