When adding stock transactions (BUY, SELL, PRICE_CHANGE) we should recalculate the current result in StockBalance.
The formula for calculating the result is (current_price - average_price) / average_price.
To calculate the average price we need to implement the FIFO algorithm:
Imaging we have these transactions for a single stock:
quantity
price
type
10
11
BUY
20
12
BUY
15
13
SELL
5
14
BUY
The FIFO algorithm assumes that when we sell some amount of stocks, we first sell stocks that are the oldest. So for the example above, we sell 10 shares that we bought for 11 and 5 shares that we bought for 12. So the final result after FIFO algorithm will be this table:
quantity
price
0
11
15
12
5
14
And the average price for this example is ((0 11) + (15 12) + (5 * 14)) / 20 = 12,5
When adding stock transactions (BUY, SELL, PRICE_CHANGE) we should recalculate the current result in StockBalance.
The formula for calculating the result is (current_price - average_price) / average_price.
To calculate the average price we need to implement the FIFO algorithm:
And the average price for this example is ((0 11) + (15 12) + (5 * 14)) / 20 = 12,5
Waiting for:
31