Assume if TSLA falls to a value less than this incorrect averaged “Price” of 472.18, like 460, then it will render “Result” as GBP equivalent of -12.18 USD, indicating that my portfolio is going in a loss, where as actually I would be running a profit of 13.63 USD (that is 460 - (446.5 + 497.87 - 498)) minus negligible conversion charges.
The correct way to calculate “Price” should be as follows:
Sum all purchase amounts of a given share till date (446.5 + 497.87 = 994.37)
Subtract sum of all sales of this share till date from the above amount (994.37 - 498 = 446.37)
Divide the resulting amount by number of shares currently held (446.37 / (1 + 1 - 1) = 446.37)
Then the “Result” can simply be rendered by computing “(Market Value - GBP equivalent of Price) * number of shares held” and it will reflect accurate portfolio growth.
I do understand that your current implementation lists “Profit” on sale of each share as the difference between market price and previously calculated averaged price, but that profit entry is only visible in “History” section of Android app, and the “Portfolio” section wrongly suggests “Return” value because of the missing sale information, which cannot even be checked on Desktop at all.
The way Trading 212 does it is consistent with UK tax rules for computing capital gains, except that they do not correctly take account of matching rules for trades taking place the same day or within 30 days.
If you were UK taxpayer your gain on sale 3 would be 498 - 487.87 because you are selling a share bought the same day.
It is pretty much impossible for a broker to show results that are correct by all different tax computation conventions applied by different governments. These vary a lot from country to country and can change year to year. Also, your taxable result can also depend on the cost of shares in the same company that you may have bought on other platforms since basis cost per share will be average over all shareholdings where ever held. Trading 212 cannot know about those.
Investors with taxable gains need to keep their own records.