Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Unexpected behavior with order_target_percent method

Debugging an algorithm I notice an unexpected behavior with order_target_percent. I cannot said it is a bug, but it is something I didn't expect. The case is simple. It happens if I open a position and then I execute order_target_percent(sid, 0) twice. instead of being 100% sold, I am 100% short on it.
In my opinion, it seems like order_target_percent is internally calling to order. So when I call order_target_percent(sid, 0) twice, it is in fact executing two sells, reason why I finish 100% short in the asset.

I attach an example to illustrate this behavior.
I just want to clarify that I don't write two order_target_percent(sid, 0) consecutive intentionally. I was working in an algorithm with several rules, and there are several rules that sell my position. When I debug, I realized I was short in the position instead of being out of it.

2 responses

Order_target_percent's limitation is that it does not take into account orders already placed. You will have to account for that with something like:

if get_open_orders(): continue

This is one of the reasons why I recommend writing your own ordering logic using order() and not using the target functions in any sort of live trading. The other reason being unrestricted use of leverage by the target functions.

Or order_value(). A route I use often:

cancel_open_orders(context, data) and then in loop ...

order_value(stock, weight * context.portfolio.cash)