Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Not able to recall stock sid or symbol from context.portfolio.positions for closing current position

Hi!

I am trying to close the current open position if, after a while, hasn't reached the limit or stop orders. The algo has a strategy of one open position at a time. So, if I don't close the "zombie" position that is sitting and doing nothing (not making or losing money), the system is losing opportunities of opening potential winning positions.

*working with multiple stocks, so I can't write order_target(sid(24),0) or something similar

def CloseAllPositions(context,data):  

    positions = context.portfolio.positions  

    if positions:  

        print ('There are open pos.')  

        GetAmount_OpenPos(context,data)          # amount of the shares in the current position  

        amnt = GetAmount_OpenPos(context,data)  

        if amnt:  

            print ('GetAmount_OpenPos:', GetAmount_OpenPos(context,data))  

            print ('amnt:', amnt)  


            def sec_symbl(context,data):  

                for security in positions:  

                    symbl = security.symbol                  # the symbol of the security:  ( exemple: 'AAPL' )  

                    return symbl  

            stock_symbol = sec_symbl(context,data)  

            if sec_symbl(context,data):  

                print ('Closing position in', sec_symbl(context,data), 'of', amnt, 'shares')  

                order(stock_symbol, amnt)               # it doesn't work

I have also tried with order(symbol(stock_symbol), amnt)
order(sid(stock_sid), amnt) *........ stock_sid = security.sid
and many other

I have a plan B, but it's a little bit retarded: 200 times for each stock:
if security.sid = 24:
order(sid(24),amnt) ...or... order_target(sid(24),0) ...I don't know if the second one works

Any suggestions? Anything.
I will post the final function with all the details if I succeed in finding the right code for closing the current positions without any execution risk.

Thanks a lot!

1 response