In real-time energy management of a converter-based microgrid, it is difficult to determine optimal operating points of a storage system in order to save costs and minimise energy waste. The complexity arises due to time-varying electricity prices, stochastic energy sources and power demand. Many countries have imposed real-time electricity pricing to efficiently control demand side management. This paper presents a particle swarm optimisation (PSO) for the application of real-time energy management to find optimal battery controls of a community microgrid. The modification of the PSO consists in altering the cost function to better model the battery charging/discharging operations. As optimal control is performed by formulating a cost function, it is suitably analysed and then a dynamic penalty function is proposed in order to obtain the best cost function. Several case studies with different scenarios are conducted to determine the effectiveness of the proposed cost function. The proposed cost function can reduce operational cost by 12% as compared to the original cost function over a time horizon of 96 h. Simulation results reveal the suitability of applying the regularised PSO algorithm with the proposed cost function, which can be adjusted according to the need of the community, for real-time energy management.