Problem
In the vwap method in MarketStats, we currently calculate the vwap incorrectly. vwapTotalAmount is a reducer that multiplies each trade's counterAmount by baseAmount.
return acc.plus(Big(event.counterAmount).times(event.baseAmount))
This should be updated to multiply the price (calculated as counter / base) by baseAmount.
return acc.plus((Big(event.counterAmount).div(Big(event.baseAmount)).times(event.baseAmount))
vwapTotalShares should be updated to calculate the total volume of trades across events.
return acc.plus(Big(event.baseAmount).times(event.baseAmount))
should be updated to
return acc.plus(Big(event.baseAmount))
Definition of VWAP
Volume weighted average price is calculated using the following method:
Assume the following data of transaction history for BTC/USD
| Price | Amount |
|-------|--------|
| 3000 | 10 |
| 3100 | 20 |
| 3200 | 30 |
In order to calculate the VWAP, we multiply each trade price by the amount traded, take the sum of this variable across all trades, then divide by the total amount traded.
| Price | Amount | Price * Amount |
|-------|--------|----------------|
| 3000 | 10 | 30000 |
| 3100 | 20 | 62000 |
| 3200 | 30 | 96000 |
Here, we would sum up the Price * Amount column, which is 188,000, then divide by the total volume, 60.
This results in a VWAP of 3,133.33.