Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
order to close

Looking to programme a function to close all buy or sell positions after a signal but I'm struggling to find how to do this. any help?

3 responses

To close all open positions simply iterate over the 'context.portfolio.positions' dictionary and place an order for a target number of shares of 0. Including the 'data.can_trade' check will keep the algorithm from throwing an error (and stopping) if trying to close a delisted stock.

def close_all_positions(context, data):  
    # This will place market orders to close all current positions  
    for stock in context.portfolio.positions:  
        if data.can_trade(stock):  
            order_target(stock,0)

You may also want to cancel any open orders which may be out there. This can be done in a similar fashion by iterating over the open orders and placing a cancel order request for each order. If one does cancel all the orders, just make certain this is done BEFORE trying to close all positions. Otherwise the orders to close positions may be canceled. Also, in live trading, the cancel order method may not go through before an order is executed. Another reason to cancel orders then wait a bit and close positions.


def cancel_all_orders(context, data):  
    # This will try and cancel all open orders  
        for security, orders in get_open_orders().items():  
            # iterate over the orders for each security  
            for order in orders:  
                cancel_order(order)

thanks for the reply Dan, I am attempting to close positions during trading when I have a signal from my SMA's. sorry if this is a basic request but I am learning and have never written code before.

I attempted to put the above in but it didn't change my outcome as I believe all positions close atomaticaly at the end of the day anyway?

Yes, you are correct. The default behavior in Quantopian is all orders are closed (even partially filled orders) at the end of the day.

Good luck.