Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Controlling Leverage and Not Buying Multiple Times

Hello,

I'm working on an intraday scalper, but my algorithm seems to continuously purchase the same stock even if its already in an open order. My leverage is way out of control because of this.

Can someone take a look at my algorithm and give me a pointer on controlling the orders?

I tried looking at len(get_open_order(stock)) > 0, but that didn't have the desired effect.

Thank you very much!

7 responses

I know you said you already tried it, but you definitely need to use get_open_orders before placing any buy or sell order to make sure you're not double ordering anyways, so start by puting it back in and see if the problem persists.

Here it is with the get_open_orders, but it has no effect.

Any ideas?

Seemed to be in the right direction

Further changes went off the rails, I'll leave it to you

Looks like order_target_percent(stock, 1.0/numstock) is ordering 10% of portfolio value for each stock no matter how many stocks are returned by pipeline, since numstock is simply set to 10. Another thing to be careful about is a situation where you get 10 stocks from pipeline, give each 10% weight, then the next day you get 10 more stocks from pipeline and give each of those 10% weight... since not all the stocks from the day before have sold, you are now over 100% total leverage.

Thanks for working on this guys. It was super helpful. Even if the algorithm didn't work exactly as I had planned, it is still a huge help!

Cool. Meanwhile now that it's no longer 3 AM and I'm more awake, maybe the ... '1m').ffill(axis=1).bfill(axis=1) isn't doing anything as I understand prices are forward filled. Might want to use 'close', not forward filled and count nans to skip any stock currently above some threshold percentage of nans. If that route, then they do need ffill afterward and before ema and bbands calcs. Since the history call has been moved outside of the loop and is operating on the entire list of stocks instead of one at a time, if it were 'close' instead of 'price', the axis=1 may be required to prevent action on all stocks whenever one stock needs the fill. I would test in the debugger with just a few stocks and small window to find out for sure.

@VHawk, right on. And I'm trying to imagine a way to avoid closing where take profit and stop loss would rule the closings, a universal function that could adopt incoming stocks with new weights and adjust everybody else in some sensible way based on their current weights maybe. Complicated.

Here since numstock in order_target_percent(stock, 1.0/numstock) is just an integer with equal weights, it could be replaced with len(set(list(c.stocks) + c.portfolio.positions.keys()))where c is context, and set makes unique, toward being able to keep on adding positions.