Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to fix my for-loop to order one stock at a time?

Am new to python so bare with me if this question is too simple. Am trying to use a "for loop" to go through each security and if it fits my first condition in the "if" statement it should order the stock and then sell when it fits the "elif-esle if" statement. But am trying to order one security from the list and wait until I sell it before I order another, the problem is I don't really know how to phrase it on my for loop correctly it's buying every security that fits the 'if' statement and going way over the capitol.

2 responses

So when you say :

order one security from the list and wait until I sell it before I order another

Your portfolio will essentially only hold one asset at a time? If so, there's multiple ways to do this that quickly come to mind. I would create a binary variable (or a switch), like so:

def initialize(context):  
       context.switch = 0

def trade(context, data):  
        # when buying:  
        if context.switch == 0:  
               order_percent(stock, .50)  
               context.switch = 1

        # when selling:  
        order_percent(stock,0)  
        context.switch = 0  

You could also see if there are any positions in context.portfolio.positions before trading which should do the same trick. Just make sure you check your get_open_positions() to ensure you don't order another asset while you have another in an order que.

Hi Alexander! I'm having the same problems with trying to get my "for s in" code to only order one stock at a time. I've been looking for get_open_positions(), but can't find it. Is it deprecated? Or am I doing something wrong? I'm new!