Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Duplicate orders via order_target and order_target_percent

Hello,

I am experiencing a problem with the Quantopian backtester. My algo uses a long-short strategy that updates long or short position every daily bar, but for some reason for each order placed, 2 orders are getting filled. For example, I'm using order_target(sid, 200) and order_target(sid, -200) depending on some defined condition. Say on the first bar, the condition is met for the long order. The backtester places an order for +200, then another for +200 (net pos. +400). Now on the second bar, say the condition is met for the short order. Now it places an order for -600 (to reach the -200 target), and then ANOTHER order for -600 (now net -800). Say condition is met for long again. Long order placed for +1000 to reach +200 target, then a duplicate for +1000 (giving me a net pos. of +1200. As you can see, this duplication is causing my order size to approach infinity as t approaches infinity (obviously a big problem).
Now for the cause.
I don't want to share my code, but I'll do my best to describe what I'm doing. In def_initialize I set commissions and slippage to 0. In handle_data I define a few simple variables using the history function, as well as define Orders = get_open_orders, and Open = context.portfolio.positions[symbol('ABC')].amount. This way, in my if function, I can specify that Orders must == {} and Open (positions) can be >= or <= 0, depending on long or short position. So my if statement looks something like this:
for stock in context.stocks:
if (condition[symbol('XYZ')] < 1) and (Open <= 0) and Orders == {}:
order_target(symbol('ABC'),200)
else:
pass
if (return_ratio[symbol('XYZ')] >= 1) and (Open >= 0) and Orders == {}:
order_target(symbol('ABC'),-200)
else:
pass

This way, there must be no open orders to place a new one, and to open a long position there must either be a short position or no position (and vice versa for long position; short or none must exist). I'm still a python newbie, and I'm afraid that my syntax may be the cause of these duplicate orders. I know that it's not due to open orders, because I'm also printing Orders in handle_data and am seeing an empty dir for each event. I can't seem to fathom why this is occurring. I've tried using order_target_percent but I'm still getting duplicate orders that increase in size over time. Suggestions would be much appreciated.

Cheers.
Hershel

1 response

Nevermind folks. Problem solved.