Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Close all current Positions and cancel their limit and stop orders (for one open position)

Hi guys!

I am new in coding algos in Python (I've started 3 weeks ago) and I want to use in my algo a function that closes all the positions and orders at a given get_datetime().hour . I need some help, please!

Here is my code:

the main position will be, at all times, a SHORT position (negative amount) --- that's the strategy
and the limit and stop orders (TakeProfit and StopLoss) for that position will be LONG with the same amount
I know how to cancel the remaing limit or stop order if the position has reached the other stop or limit order,
but I don't know how to close a position at market price at a given datetime
.....before executing the Open_New_Position(context,data) code

def CloseAll_Orders_and_Positions(context,data):

print ('Closing all orders and positions')  


def GetAmount_OpenPos(context,data):  # equals to the amount of shares in the Open Order  

    orders = get_open_orders()  

    for security, oo_for_sid in orders.iteritems():  
        for order_obj in oo_for_sid:  
            log.info("%s: A. Cancelling positions for %s of %s" %  
                    (get_order(order_obj), order_obj.amount,  
                     security.symbol))  

            print ('HEEEEY! Shares amount:', order_obj.amount)  
            xamount = order_obj.amount  
            return xamount                                   # return value in function



def CloseAllPositions(context,data):  

    positions = context.portfolio.positions  

    if positions:  

        GetAmount_OpenPos(context,data)  

        if GetAmount_OpenPos(context,data):  

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

            amnt = GetAmount_OpenPos(context,data)  

            print ('amnt:', amnt)  


            def sec_sym(context,data):  

                for security in positions:  

                    sym = security.symbol  

                    return sym  

            if sec_sym(context,data):  

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

                order(symbol(sec_sym(context,data)),amnt)    # here is the main error  

                # !!! OrderNonSecurity: 0035 Attempt to order [TZOO], which is not a security. You must place orders with a Security object. You can construct a Security by calling sid(123).  


def CloseAllOrders(context,data):  

    orders = get_open_orders()  

    if orders:  

        for security, oo_for_sid in orders.iteritems():  
           for order_obj in oo_for_sid:  
               log.info("%s: B. Cancelling orders for %s of %s created on %s" %  
                   (get_order(order_obj), order_obj.amount,  
                    security.symbol, order_obj.created))  
               cancel_order(order_obj)  


CloseAllPositions(context,data)   # it this part it could get also ugly if will execute CloseAllOrders(context,data)  
                                                # before the new LONG order for closing the old SHORT position is not yet filled  
CloseAllOrders(context,data)      # but I can choose another datetime or someting to execute the second one

def handle_data(context, data):

if get_datetime().hour == 19 and get_datetime().minute == 12:  
    CloseAll_Orders_and_Positions(context,data)  

if get_datetime().hour == 19 and get_datetime().minute == 15:  
    print ('Current open positions value: ', context.portfolio.positions_value)  
1 response

@Adrian B. You recall you can use schedule_function to run any code at any time of day. You might be able to use such a function to serialize your entries, cancellations and flattening processes.

Here's a quick algo that does some of what you're asking for. This was assembled from pieces of a few posts that were submitted here some weeks ago.