How do I calculate Profit&Loss for the User Account? HELP

Hi guys, I am trying to figure out the formula for calculating the Realized and Unrealized P&L, on the account level. Based on average price I guess…
I am working on an investment app - e.g. user buys 3 AMZN at $3.000, than buys 2.8 AMZN at $2.900 and than sells 1.4 AMZN at $3.005, it is all calculated and written into the same ledger. No positions.

The approach I am investigating is by calculating the average price for buy and sell orders. Once the quantity of a certain asset increases by the buy order I can figure it out, but when it comes to the new order that is decreasing or flattening the quantity I get lost.

Can anyone assist?

Hi @Milos did you ever figure this out? I am looking for help with the getting the same metric.