Back to Community
How can I access/call 'amount' from get_open_orders.

The short and sweet, I start with creating a variable

open_orders = get_open_orders()

Then I use a for loop through a list of equities, with the intention of pulling the amount of shares to order within an open order. I check that the equity does have an open order

for stock in context.portfolio.positions:
if stock in open_orders:
print open_orders.amount

I've tried many variations, including print open_orders(amount) or ('amount') but always get an issue that it can't be called, or something along those lines.

I use context.portfolio.positions().amount all the time with no issues.

How can I access the dictionary items within open_orders? I'd also like to access 'limit', but the solution should be the same.

Thank you,

6 responses

This is a random snippet from an old algo that might be of interest:

def cancel_open_buy_orders(context, data):  
    oo = get_open_orders()  
    if len(oo) == 0:  
    for stock, orders in oo.iteritems():  
        for order in orders:  
            #message = 'Canceling order of {amount} shares in {stock}'  
  , stock=stock))  
            if 0<order.amount: #it is a buy order  

Hi Luke,

Thank you very much! I got it to work! I swear I thought I had tried everything, in fact I swear I tried .amount

For anyone interested in the application for this code, I currently use Robinhood and need to code my own OCO (order cancels order). I need to clean up my code so I can post a snipped to be useful for others interested. But here dirty code:

    for stocks in stock_list:  
        open_order = get_open_orders()  
        if stocks in open_order:  
            open_order = get_open_orders(stocks)   #like I said, dirty code  
            orderr = open_order[0].amount  
            print "Order Amount %s" % orderr  

So this is the code I came up with to manage OCO, but I am now having issues and may start a new post. For some reason, when running a backtest a majority of equities are not registering of being under 'open_order' so every minute it is triggering "print "%s open order not found. Currently >= 0. Limit Sell Order placed" % stock" My only assumption is that the stock is hitting the target amount, selling, and not removing from mypositions list. I have it coded to sync context.mypositions with context.portfolio.positions in 'def before_trading_starts' - I am testing now and will report back.

def initialize(context): = .005  
    context.stop = .05

def handle_data(context,data):  

    for stock in context.mypositions:  
        avg_price = context.portfolio.positions[stock].cost_basis  
        shares_qty = context.portfolio.positions[stock].amount  
        total_cost = avg_price * shares_qty  
        curr_price = data.current(stock, "price")  
        curr_value = curr_price * shares_qty  
        open_orders = get_open_orders()  
        if stock in open_orders:  
            open_order = get_open_orders(stock)  
            order_limit = open_order[0].limit  
            #print order_limit  
            if (curr_value < (total_cost * (1 - (context.stop/1.5)))) and order_limit > 0:  
                print "Approaching Loss Stop for %s, Cancelled Limit Sell" % stock  
        elif stock not in open_orders:  
            if curr_value >= total_cost:  
                order_target_percent(stock, 0, style=LimitOrder(avg_price*(

                print "%s open order not found. Currently >= 0. Limit Sell Order placed" % stock

            elif (curr_value < (total_cost * (1 - context.stop))):  
                order_target_percent(stock, 0)  
                print "Stop Loss Hit -Sold %s %s" % (stock, curr_price)  


I was able to confirm that the multiple triggers of "open order not found. Currently >= 0. Limit Sell Order placed" % stock"

was because the stock was sold at the limit price. I implemented my list balance code to run every 5 minutes

2013-01-04 09:53 PRINT Equity(1335 [C]) open order not found. Currently >= 0. Limit Sell Order placed
2013-01-04 09:54 PRINT Equity(1335 [C]) open order not found. Currently >= 0. Limit Sell Order placed
2013-01-04 09:55 PRINT Equity(1335 [C]) open order not found. Currently >= 0. Limit Sell Order placed
2013-01-04 09:55 PRINT Equity(1335 [C]) not in positions. Removed from list

Ah so that's what you're doing. I have similar code but I've broken it down into separate functions instead of trying to do it all at once.

First, have your stop function checking your positions gain/loss every minute using handle_data()

Second, when your stop function detects the stop trigger write an If statement like this with get_open_orders()

Third, when there are no open orders for a stock you write the new market order that closes the position.

def process_stop(context, data):  
    for stock in context.portfolio.positions:  
        if not data.can_trade(stock): continue  
        gain = get_gain(context,stock)  
        if gain < (-1*context.stoppct):  
            if get_open_orders(stock):  
                cancel_open_order(context, stock)  
            amount = context.portfolio.positions[stock].amount  
            if not amount == 0:  
                log.warn("Sell Order " + str(stock) + " @ " + str(data.current(stock,'price')) + " STOP ORDER.")  

def cancel_open_order(context, sec):  
    oo = get_open_orders(sec)  
    if len(oo) == 0:  
    for order in oo:  
        if order.sid == sec:  
            if context.bug:  
                log.debug("Cancelling " + str(order.sid.symbol))  

def get_gain(context, s):  
    if s in context.portfolio.positions:  
        cost =   context.portfolio.positions[s].cost_basis  
        amount = context.portfolio.positions[s].amount  
        price =  context.portfolio.positions[s].last_sale_price  
        if amount > 0:  
            gain = price/cost - 1  
        if amount < 0:  
            gain = 1 - price/cost  
        gain = 0  
    return gain  

notice how there is a continue after cancel_open_order(context, stock), it's so the logic skips that one until the next calling of process_stop() in handle_data(). quantopian only refreshes data from robinhood once per minute so if you cancel an order than immediately try and write a new one I'm not sure it would work correctly. By doing this you don't really have to check for amounts you just close the position based on the amount you hold in your portfolio (easy). Canceling the order cancels everything under that stock no need to specify an amount.

If you want to close your position with a limit order it gets trickier because you will always have a new open order that will be getting canceled. In this case you'd want to .append(stock) to a list and check against that list before executing the stop.

get_open_orders(stock) is a quantopian built in function that is very useful when you want to check if any orders exist for one single stock.
.iteritems() is some fancy python code that I don't really understand but it lets you iterate over a dictionary in a more loopable format, to get key/value pairs or something. I didn't write it but it works and you can use breakpoints to understand it fully, or google.

Hi Luke,

Thank you for your last post. Your code looks fascinating. I didn't want to be rude and not acknowledge your input, but I haven't had a chance to fully look it over to grasp it. It seems it should be fairly simple to implement thought. I did want to mention, that I've been calculating my gain based on the total value of my position. - I ran a backtest once and had an issue with a stock stuck in my portfolio due to what I think was a split. I didn't have a stop-loss on this algo, so because the cost per share was cut in half, my position never reached my 'target'... From my understanding, the IDE is supposed to handle splits and such, but after experiencing that issue once, I figure its best to have that fail-safe.