Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Getting fill price of filled order?

Hi, I'm trying to figure out if there's a way to get the fill price, if I have the order status?

i.e:

Time 0 - context.orderId = order(sid(123), 100)

Time 1 - log.warn(get_order(context.orderId)) # The logs have a lot of info, but no fill price.

junbin

17 responses

Yes, I was looking at the same thing but it looks like there's no direct way of seeing the filled price of the order, I don't understand why. I'm guessing if you look at the portfolio.positions object for the sid in the current frame and compare it to the the previous frame, you might be able to indirectly find the fill price but that's very convoluted.

This may help:

context.portfolio.positions[symbol('AAPL')].cost_basis
Float: The volume-weighted average price paid (price and commission) per share in this position.

However this is per position, not per order?

Exactly. That's like the average price you paid for that position, potentially over multiple orders. I want to know the exact fill price for a single order.

Yes, it seems like some details are missing from the order object. Shouldn't it keep a time-stamped running tally of fills, commissions paid, etc.?

Seems like a feature request!

Getting the fill price for an order isn't the easiest process - I definitely think we can make that better. Take a look at Gus's workaround here to get the info:https://www.quantopian.com/posts/fill-price-of-market-orders

Does that help you?

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hello Alisa,

I took a look at https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter.py and just can't sort out how to interpret the commission key in an order object. Is it the cumulative total commission paid on the order? Or is it the most recent commission paid (i.e. for a partial fill, it would be the commission paid since the last partial fill)? Or something else?

Grant

Hi Grant,

I believe the commission key is cumulative commissions paid on the order. If you check out the logs from the backtest I've attached to this, you can see that the commission accumulates for the same order id, each with a partial fill (the slippage model separates the order into three orders).

Order 1 commission: .99
Order 2 commission: 1.98
Order 3 commission: 2.96

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hi everyone

Just wonering if there is now a way to get cost basis per order.... as Mete Atamel stated, cost basis on positions over multiple orders messes up the calculations if you want to get pnl per order.....

for stock in context.portfolio.positions:  
    log.info('{}  cb {}'.format(stock.symbol, context.portfolio.positions[stock].cost_basis))  

https://www.quantopian.com/posts/pnl-profit-and-loss-per-stock
https://www.quantopian.com/posts/track-orders (shows price one minute after each fill and partial fill)

Thanks but this doesnt give me the cost basis per order...

Consider rewriting your question with an example.

I'd suggest you try using the debugger in the first loop within track_orders() where you have access to order ids after they are ordered. You can store them all if you want to in your own dictionary within context for example the same way as in the ordrs object (not a typo) where the order ids are the keys. Your value can be the last known cost basis perhaps.
I'm suggesting that route because I think you'll find track_orders() to be also useful in ways that will surprise you and once you are used to it a little bit you might also think of other useful ways to modify it for your own benefit.

Each transaction on partial fills updates cost_basis for that stock. You can know fill price from a previous minute fill by setting commissions to zero however that only applies to the first partial fill if partial.

Another option: I suppose you can store order ids returned by all ordering functions in a dictionary, optionally along with each stock and any time you want the cost basis for an order id use get_order() supplying the order id in quotes.

Ill try to extract the piece of code pertinent to my question and get back to you but before, Ill give a shot at your recommendation especially with track_orders. I like the idea of storing the data I want.

Thanks for the input Blue, much appreciated !

hello again Blue, I tried using the get_order() function which, I believe would have been the easiest choice unfortunately, there's nothing in there that tells me how much I paid for a stock on a specific order:

Event({'stop_reached': False, 'limit': None, 'created': Timestamp('2012-01-05 21:00:00+0000', tz='UTC'), 'reason': None, 'sid': Equity(26, symbol='AAPL', asset_name='', exchange='YAHOO', start_date=Timestamp('2007-09-17 00:00:00+0000', tz='UTC'), end_date=Timestamp('2017-01-24 00:00:00+0000', tz='UTC'), first_traded=None, auto_close_date=Timestamp('2017-01-25 00:00:00+0000', tz='UTC'), exchange_full='YAHOO'), 'commission': 0, 'id': '554bec1ff3d74f618f2d06bc0c71b9df', 'limit_reached': False, 'filled': 0, 'dt': Timestamp('2012-01-05 21:00:00+0000', tz='UTC'), 'stop': None, 'amount': -267, 'status': 0})

My goal here is to buy a stock (multiple times a different point in time) and sell parts of my entire position once I make a certain profit on a specific trade. For example:

Day 1: Buy AAPL, 100 shares @ $500/share
Day 200: Buy AAPL, 100 shares @ $600/share

Day 300: Sell AAPL, 100 shares @ $700/share to secure my $200 profit on my order from day 1
Day 400: Sell AAPL, 100 shares @ $800/share to secure my $200 profit on my order from day 2

Of course, this example is over simplified but I think this gives you a good idea of what I want to accomplish.

P.S. I don't know if its because Im using zipline on my own machine but I would have been under the impression that I would get the same result in quantopian

Ah I see that more clearly now I think and will toss my first thought out there. A dictionary where the keys are the stock objects or just stock.symbol and values are also a dictionary with each key as an order id and the corresponding value the order cost basis. So get_order() isn't used and the order ids as keys are just a convenient way to keep orders separate (coming from like order_id = order_target_percent(...) as you already have handled). There's a point in track_orders where a partial fill becomes complete and you might want to update cost basis there.

cb_info = {  
    'AAPL': {  
        '7c31e599714d43fd8b69f5a734fc3357': 500.11,  
        'e17292d8e5ec4bb196ffec16c1d38756': 600.72,  
    },  
    'TSLA': {  
    }  
}
for sym in cb_info:  
    for oid in cb_info[sym]:  
        this_cb = cb_info[sym][oid]  

So if I get this straight, I would need to manually keep track of my cost basis by creating my own dictionary and then saving my cost basis as today's closing price for instance. Am I understanding this correctly ? If so, this looks like a dangerous / inefficient way of keeping my cost basis ...

Also, I couldn't find the track_orders function anywhere on the HELP section, am I missing something here too ?

Thanks again for the reply, always appreciated.

Unless you are talking about this code you wrote: https://www.quantopian.com/posts/track-orders