-
Notifications
You must be signed in to change notification settings - Fork 91
/
smoothed_price.go
54 lines (46 loc) · 1.57 KB
/
smoothed_price.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package keeper
import (
"errors"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/dydxprotocol/v4-chain/protocol/x/prices/types"
)
// UpdateSmoothedPrices updates the internal map of smoothed prices for all markets.
// The smoothing is calculated with Basic Exponential Smoothing, see
// https://en.wikipedia.org/wiki/Exponential_smoothing
// If there is no valid index price for a market at this time, the smoothed price does not change.
func (k Keeper) UpdateSmoothedPrices(
ctx sdk.Context,
linearInterpolateFunc func(v0 uint64, v1 uint64, ppm uint32) (uint64, error),
) error {
allMarketParams := k.GetAllMarketParams(ctx)
indexPrices := k.indexPriceCache.GetValidMedianPrices(allMarketParams, k.timeProvider.Now())
// Track errors for each market.
updateErrors := make([]error, 0)
// Iterate through allMarketParams instead of indexPrices to ensure that we generate deterministic error messages
// in the case of failed updates.
for _, marketParam := range allMarketParams {
indexPrice, exists := indexPrices[marketParam.Id]
if !exists {
continue
}
smoothedPrice, ok := k.marketToSmoothedPrices.GetSmoothedPrice(marketParam.Id)
if !ok {
smoothedPrice = indexPrice
}
update, err := linearInterpolateFunc(
smoothedPrice,
indexPrice,
types.PriceSmoothingPpm,
)
if err != nil {
updateErrors = append(
updateErrors,
fmt.Errorf("Error updating smoothed price for market %v: %w", marketParam.Id, err),
)
continue
}
k.marketToSmoothedPrices.PushSmoothedPrice(marketParam.Id, update)
}
return errors.Join(updateErrors...)
}