Whenever the quantity of a share reaches 0 (zero), the avg_cost variable for that specific share should be zeroed,
(avg_cost = 0.0;) so that when ALL shares are sold (qty = 0) and more are bought later, the avg_cost of the shares sold a month ago doesn't affect the average cost displayed of the new shares you are buying.
Each transaction of a specific share should contribute its weight to the avg cost, so if 50 are bought at R1 then 100 bought at R2 and 40 sold at R3: (the avg cost is R1*(50/150) + R2*(100/150) = R1.67)
Now when the 40 shares are sold, the total qty of shares are reduced, but the avg cost should remain unchanged because selling price doesn't affect the buying price, so now we have 110 shares bought at R1.67 each, and when we buy again, say 90 at R2.50, then avg cost = (R1.67*(110/200) + R2.5*(90/200)) = R2.04.
The transaction fees and tax on share profit can be calculated seperately as I beleive you are allready doing.