How to square off and cancel all open positions and orders using angel one python API ?

Using the Angel One API users can square off and cancel all open orders and positions with just few lines of code.

Let’s see how you can do it.

Before starting you’ll need to login into your angel one account and create the class object.

obj=SmartConnect(api_key=login_ang.api)
data = obj.generateSession(login_ang.userid,login_ang.password)

First of all we need to find open orders using Orders API. This API will give you all the orders that were placed by you. We only need the orders with order status as “pending”, “open”, “trigger pending”.

After finding all the open we simply need to use order cancellation feature to cancel the open orders

def cancel_order(orderid, variety):
    can = obj.cancelOrder(orderid, variety = variety)

orderbook = obj.orderBook()

if orderbook['data'] != None : 
    for o in orderbook['data'] :
        if o['orderstatus'] == "open" or o['orderstatus'] == 'trigger pending' or o['orderstatus'] == 'validation pending' or o['orderstatus'] == 'open pending' or o['orderstatus'] == 'AMO SUBMITTED' : 
             cancel_order(o['orderid'], variety = o['variety']) 
             time.sleep(0.2)

Now, we’ll see how to square off all positions.

For this we first need to find all the open positions using the net positions API. In this API we need to filter out only positions where net quantity is not equal to 0.

After filtering out we need to find if the transaction type is buy or sell. If it is buy, we need to place sell order with same quantity to completely square off the trade and wise-versa.

def place_order( tradingsymbol, symboltoken, transactiontype, exc, producttype, quantity): 
    try: 
        orderparams = {
            "variety": "NORMAL",
            "tradingsymbol": tradingsymbol,
            "symboltoken": symboltoken,
            "transactiontype": transactiontype,
            "exchange": exc,
            "ordertype": "MARKET",
            "producttype": producttype,
            "duration": "DAY",
            "price": "0",
            "squareoff": "0",
            "stoploss": "0",
            "quantity": quantity
            }
        orderId=obj.placeOrder(orderparams)
        
    except Exception as e :
        print(e)

netpos = obj.position()

if netpos['data'] != None : 
    for o in netpos['data'] :
        if int(o['netqty']) != 0 : 
            transactiontype = "SELL" if int(o['netqty']) > 0 else "BUY"
            place_order(o["tradingsymbol"],o['symboltoken'], transactiontype,o['exchange'],o['producttype'], abs(int(o['netqty'])))
            time.sleep(0.2)

This is how you can completely Square Off all the open positions.

Refer to the below YOUTUBE video if you have any doubts.

Scroll to Top