Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to record the quantity of various open orders?

def open_orders(context, data):
open_orders = get_open_orders()
if open_orders:
for security, orders in open_orders.iteritems():
for oo in orders:
message = 'Open order for {amount} shares in {stock}'
message = message.format(amount=oo.amount, stock=security)
log.info(message)

In this case, I have 2 securities: AAPL and AMZN and I want the number of open orders to be recorded, eg.
open_orders_AAPL = .........
open_orders_AMZN = .........

Anyone can assist?

Thank you.

11 responses

The 'orders' variable in the above code is a list of order ids for each security. To length of this list will be the quantity of orders open at a given time for a given security. So to log the the number of open orders for each security one could do something like this.

def open_orders(context, data):

    open_orders = get_open_orders()  
    if open_orders:  
        for security, orders in open_orders.iteritems():  
            order_qty_message = 'open orders {stock} = {orders}'  
            order_qty_message = order_qty_message.format(stock = security.symbol, orders = len(orders))  
            log.info(order_qty_message)  

            for oo in orders:  
                message = 'Open order for {amount} shares in {stock}'  
                message = message.format(amount=oo.amount, stock=security)

                log.info(message)

I have some code that I use sometimes to log the details of what is happening minute by minute in my portfolio (mostly debugging my live trading algorithms when that was an option). There are two functions, track_orders and track_positions:

2017-08-14 16:35 track_positions: H x  234 profit -1 (cost 57.10 close 57.10 open 57.06 high 57.10 low 57.05 vol 6410)  
2017-08-14 16:35 track_positions: DY x  16 profit -4 (cost 85.19 close 84.94 open 84.94 high 84.94 low 84.94 vol 100)  
2017-08-14 16:35 track_positions: EGRX x 70 profit -1 (cost 56.03 close 56.02 open 55.98 high 56.02 low 55.97 vol 1400)  
2017-08-14 16:35 track_positions: PLCE x 20 profit -15 (cost 106.17 close 105.4 open 105.4 high 105.4 low 105.40 vol 100)  
2017-08-14 16:35 track_positions:  XEC x -25 profit -1 (cost 96.98 close 97.03 open 97.03 high 97.03 low 97.03 vol 100)

2017-08-14 16:35 track_orders: Open order PLCE -25/-45 shares, limit None, commission 1.00  
2017-08-14 16:35 track_orders: Open order DY -25/-41 shares, limit None, commission 1.00  
2017-08-14 16:35 track_orders: Filled order H 234/234 shares, limit None, commission 1.17  
2017-08-14 16:35 track_orders: Filled order EGRX 70/70 shares, limit None, commission 1.00  
2017-08-14 16:35 track_orders: Cancelled order XEC -25/-123 shares, limit None, commission 1.00

2017-08-14 16:36 track_positions: H  x  234 profit -20 (cost 57.10 close 57.02 open 57.11 high 57.16 low 57.02 vol 16132)  
2017-08-14 16:36 track_positions: DY x 16 profit nan (cost 85.19 close nan open nan high nan low nan vol 0)  
2017-08-14 16:36 track_positions: EGRX x 70 profit 6 (cost 56.03 close 56.12 open 55.98 high 56.12 low 55.98 vol 1394)  
2017-08-14 16:36 track_positions: XEC x  -25 profit 1 (cost 96.98 close 96.94 open 97.06 high 97.06 low 96.94 vol 2006)

2017-08-14 16:36 track_orders: Open order DY -25/-41 shares, limit None, commission 1.00  
2017-08-14 16:36 track_orders: Filled order PLCE -45/-45 shares, limit None, commission 1.00  

Use the code like this:

def handle_data(context, data):  
    track_positions(context, data)  
    #  
    # Add your algorithm logic here  
    #  
    track_orders(context, data)  

Here is the code:


def track_positions(context, data):  
    """  
    Print information about current portfolio positions  
    """  
    for sec, position in context.portfolio.positions.iteritems():  
        if data.can_trade(sec):  
            amount = position.amount  
            cost_basis = position.cost_basis  
            open,close,high,low,volume = data.current(sec, ['open','close','high','low','volume'])  
            profit = amount*(close-cost_basis)  
            log.info('Pos %-6s x %4d profit %.0f (cost %.2f close %.2f open %.2f high %.2f low %.2f volume %d, port.ret %.3f)' %  
                     (sec.symbol,amount,profit,cost_basis,close,open,high,low,volume,context.portfolio.returns))


def track_orders(context, data):  
    """  
    Print information about orders since last call to this function  
    """  
    if 'orders' not in context:  
        context.orders = set()  
    for stock, orders in  get_open_orders().iteritems():  
        for o in orders:  
            context.orders.add(o.id)

    messages = []  
    to_delete = []  
    for id in context.orders:  
        if id is None:  
            to_delete.append(id)  
            continue  
        o = get_order(id)  
        m = 'order %s %d/%d shares, limit %s, commission %.2f' % (o.sid.symbol, o.filled, o.amount, str(o.limit), o.commission)  

        messages.append( (o.status,m) )  
        if o.status == 0:    # open  
            continue  
        elif o.status == 1:  # Filled  
            if o.amount != o.filled:  
                continue  
        elif o.status == 2:  # Cancelled  
            pass  
        elif o.status == 3:  # Rejected  
            pass  
        elif o.status == 4:  # Held  
            log.warn(m)  
            continue  
        else:  
            log.warn("Unknown order status %d" % (o.status))  
        to_delete.append(o.id)  
    for id in to_delete:  
        context.orders.remove(id)  
    for status, m in sorted(messages, key=lambda t: t[0]):  
        if status == 0:   m = 'Open '      + m  
        elif status == 1: m = 'Filled '    + m  
        elif status == 2: m = 'Cancelled ' + m  
        elif status == 3: m = 'Rejected '  + m  
        elif status == 4: m = 'Held '      + m  
        else:             m = ('Unknown (%d) ' % status)  + m  
        log.debug(m)  

Thank you all for your feedback and tips.
The main thing I want to do is to record the number of open orders to a variable, then use this variable to place an order the following day.
Basically, I want to ensure the open orders are purchased the next day.

Any tips on this?

Thank you.

] Basically, I want to ensure the open orders are purchased the next day.

See if this works for you.

Wow Blue Seahawk,

Thank you very much !!!

Glad I could help.

Now I realize the discrepancy mentioned in the code is because the order was stored so just a matter of replacing this line for its current state

        #o = context.open_orders[oid]  
        o = get_order(oid)  

One caution with carrying over orders is stock splits. Best to store the order value and NOT the order quantity. A 1:2 reverse split would have one ordering twice as many share as desired.

Hi Blue Seahawk,

Can you please explain what line 32, 33, 34 in your code does?

for s in oos:  
    for o in oos[s]:  
        context.open_orders[o.id] = o

Thank you.

s stands for stock or security, o for order. It loops through any orders for all stocks in open orders (oos) and stores them in a dictionary with the order id (o.id) as the key and the entire order as the value. Saving the entire order became unnecessary with the o = get_order(oid) change, could just be set to 1 or something. The order id's are going to be unique anyway but out of habit I resorted to a dictionary there, preference over a list.

The easiest way to see it clearly would be to click in the margin, say, on the line for o in oos[s] and when that breaks in, at the prompt that appears, type s and hit enter. Then click the down arrow to go to the next line, and type o and hit enter, that will show the order. And o.id will be the order id. Plus o.filled and o.amount.

By the way here's something I like to use with the debugger sometimes:

from pytz import timezone as tz  
def minut():           # Minute of trading day, neutralizing dst etc vs gmt  
    dt = get_datetime().astimezone(tz('US/Eastern'))  
    return (dt.hour * 60) + dt.minute - 570  # (-570 = 9:31a)  

You can click the watch window + sign and add minut(), it takes function calls. Whenever paused, that will show which of the 390 minutes of the trading day you're on.

Thanks for the explanation!! :D