Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Why is this selling and reselling and reselling despite order_target method

Hi guys,

I thought the order_target method was set up to avoid buying or selling more than a given percentage of stocks.
This application went absolutely berzerk after I changed the moving average to a shorter period, which should not have affected anything.

Both on buy and sell side it goes crazy, buying and selling way in excess of margin. But why?

Here's how I am measuring number of max shares to buy/sell
context.posValue = math.floor(context.portfolio.portfolio_value * context.longLeverage /len(context.assets) )
new_price = data[stock].price
sharesToTransact = math.floor(context.posValue/new_price)
order_target(stock,sharesToTransact, style=LimitOrder(limitPrice))

I am using a
if get_open_orders(stock) : ... continue

method to skip ordering several times until orders have filled.

So what gives?

Probably something simple, but I cannot find it.

Thanks

4 responses

It might not be not true that that's in knots from not having not. :>

if not get_open_orders(stock) # if there are no open orders, ok to order, note the not.

By the way, I think backtest vs live/real on unfilled orders are different. And something not often mentioned, when there are partial fills a whole new order with a new id is created for the remainder.

garyha,

Thanks, but I don't think that's the problem.
if get_open_orders(stock) :
I am skipping it
else :
i am ordering it

So the problem is elsewhere.
But I love the quote: "It might not be not true that that's in knots from not having not. :>"

The warning on the second is well-taken. For live trading I'm probably better off counting the shares held before placing any new orders, you think?
Anybody have problems with order_target or order_target_percent in live trading?

Without thinking too much (it is complex code), I added lines before each order to skip if there were open orders. And did not use not. =D

Looks like you have some good stuff there. Also, here's some good news: Because of the fact that you did not use all of the initial capital, your profit versus risk return is higher than the chart indicates, for one who is willing to consider risk to be what was actually exchanged for stocks rather than the amount in the account at the start.

Garyha,

Yep, that seems to do it. I'm new to Python, so not sure why "continue" does not work for me here but "return" does. I would have thought "return" would cause an exit from the whole "trade" method, thus invalidating any results for other stocks until the next time it is run.

I'll run it slowly in debugger in order to gain understanding.

I appreciate your input.