Here is the explanation with example:

01-06-2010 – Buy – Infosys 100 @ 2500 = 2,50,000

15-10-2011 – Buy – Infosys 300 @ 3000 = 9,00,000

15-12-2013 – Sell – Infosys 200 @ 3200 = 6,40,000

The sale qty of 200 will be adjusted first from 100 qty bought on 01-06-2010

The remaining sale qty of 100 will be adjusted from the qty bought on 15-10-2011. So, the balance qty will be 200 of buy transaction of 15-10-2011, which has cost price of Rs.3000.

So, the balance qty of 200 will have closing balance of 6,00,000.

This is the way all the closing balances are calculated for stocks and mutual funds.