The Alice Blue Positions API

Note – Always remember that Broker API payloads are constantly changing. So, the article will not be valid unless it’s timely updated. 

Aliceblue gives three types of positions –

  • Cash Positions – This gives data of all holdings. (equities)
  • Daywise Positions – This is something like Zerodha’s Day’s History. It shows the positions derived from the orders placed on that day only.
  • Netwise Positions – This is what we are seeking!

Assuming, You have got the Alice object from the last article, The command for getting the netwise positions is easy –

print(alice.get_netwise_positions())

The output is huge JSON data which will look something like this –

Formatting the JSON List to Pandas Dataframe

It is hard to visualize JSON from the raw data. It is better to visualize from some JSON visualizer websites like https://jsonformatter.curiousconcept.com or https://jsonformatter.org/json-viewer

All the positions are being stored into the [‘data’][‘positions’] here as a list. So, Let’s convert them to a table. We shall use Pandas Dataframe. You should refer to this article for more overview – Converting the JSON List to Pandas DataFrame 

Getting the MTM

We can see the MTM is given in the column. So it lessens our burden but data like 3,450.45 will be interpreted as a string by default because of the comma.

So, We need to replace all the commas to blank as shown below. Then, We also need to convert the entire data type to Float. 

Getting the PL

This is where it gets complicated. There are many ways to calculate the PL from the data given there. The PL is not given by default in a straightforward manner like M2M. 

It says “close_price” as the average price. So, We are just calculating our profit and loss straight from the (average price – last traded price ) * net quantity.

But the prices get messed up if the position is closed (i.e. net quantity is 0.). Now, there is already a column that shows the correct pl of a closed position. So, We are taking that – 

Jupyter Notebook / Google Collab Version

The Final Jupyter version of the python code is made in Google Collab as following. It will show you both the input and output. Feel free to make a copy of it and tinker with it –