Work out the average price and total cost of a position built from several buys. Give it a target average and it tells you how many more shares to buy; give it the current price and you get profit, return, the break-even price and the sell price for any target return.
Buy fees increase your cost basis; sell fees and taxes reduce what you receive. Merging them into one number would give a wrong break-even price, so they are entered separately.
Averaging down can never pull your average below the price you pay. As the target approaches that buy price, the required share count grows without bound.
Broker discounts, minimum commissions, dividends, FX costs and local tax rules are not modelled — treat the output as a reference.
Total cost ÷ total shares. It is share-weighted, so it drifts toward the price you bought most at — 1 share at 100 and 99 at 10 averages 10.9, not 55.
shares = held × (current average − target) ÷ (target − buy price). A solution exists only when the target sits above the buy price and below your current average.
Because sell fees and taxes come out of the proceeds, so you need a bit more to land at zero. Set the sell fee to 0 and break-even equals your average.