/
historic_price.go
261 lines (227 loc) · 6.67 KB
/
historic_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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package keeper
import (
"fmt"
"sort"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/tessornetwork/nebula/v3/util"
"github.com/tessornetwork/nebula/v3/x/oracle/types"
)
// median returns the median of a list of historic prices.
func median(prices []sdk.Dec) sdk.Dec {
lenPrices := len(prices)
if lenPrices == 0 {
return sdk.ZeroDec()
}
sort.Slice(prices, func(i, j int) bool {
return prices[i].BigInt().
Cmp(prices[j].BigInt()) > 0
})
if lenPrices%2 == 0 {
return prices[lenPrices/2-1].
Add(prices[lenPrices/2]).
QuoInt64(2)
}
return prices[lenPrices/2]
}
// medianDeviation returns the standard deviation around the
// median of a list of prices.
// medianDeviation = ∑((price - median)^2 / len(prices))
func medianDeviation(median sdk.Dec, prices []sdk.Dec) sdk.Dec {
lenPrices := len(prices)
medianDeviation := sdk.ZeroDec()
for _, price := range prices {
medianDeviation = medianDeviation.Add(price.
Sub(median).Abs().Power(2).
QuoInt64(int64(lenPrices)))
}
return medianDeviation
}
// GetMedian returns a given denom's median price in the last prune
// period since a given block.
func (k Keeper) GetMedian(
ctx sdk.Context,
denom string,
) (sdk.Dec, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.KeyMedian(denom))
if bz == nil {
return sdk.ZeroDec(), sdkerrors.Wrap(types.ErrNoMedian, fmt.Sprintf("denom: %s", denom))
}
median := sdk.DecProto{}
k.cdc.MustUnmarshal(bz, &median)
return median.Dec, nil
}
// SetMedian uses all the historic prices of a given denom to calculate
// its median price in the last prune period since the current block and
// set it to the store. It will also call setMedianDeviation with the
// calculated median.
func (k Keeper) CalcAndSetMedian(
ctx sdk.Context,
denom string,
) {
historicPrices := k.getHistoricPrices(ctx, denom)
median := median(historicPrices)
k.SetMedian(ctx, denom, median)
k.calcAndSetMedianDeviation(ctx, denom, median, historicPrices)
}
func (k Keeper) SetMedian(
ctx sdk.Context,
denom string,
median sdk.Dec,
) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: median})
store.Set(types.KeyMedian(denom), bz)
}
// GetMedianDeviation returns a given denom's standard deviation around
// its median price in the last prune period since a given block.
func (k Keeper) GetMedianDeviation(
ctx sdk.Context,
denom string,
) (sdk.Dec, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.KeyMedianDeviation(denom))
if bz == nil {
return sdk.ZeroDec(), sdkerrors.Wrap(types.ErrNoMedianDeviation, fmt.Sprintf("denom: %s", denom))
}
decProto := sdk.DecProto{}
k.cdc.MustUnmarshal(bz, &decProto)
return decProto.Dec, nil
}
// WithinMedianDeviation returns whether or not a given price of a given
// denom is within the Standard Deviation around the Median.
func (k Keeper) WithinMedianDeviation(
ctx sdk.Context,
denom string,
price sdk.Dec,
) (bool, error) {
median, err := k.GetMedian(ctx, denom)
if err != nil {
return false, err
}
medianDeviation, err := k.GetMedianDeviation(ctx, denom)
if err != nil {
return false, err
}
return price.Sub(median).Abs().LTE(medianDeviation), nil
}
// setMedianDeviation sets a given denom's standard deviation around
// its median price in the last prune period since the current block.
func (k Keeper) calcAndSetMedianDeviation(
ctx sdk.Context,
denom string,
median sdk.Dec,
prices []sdk.Dec,
) {
medianDeviation := medianDeviation(median, prices)
k.SetMedianDeviation(ctx, denom, medianDeviation)
}
func (k Keeper) SetMedianDeviation(
ctx sdk.Context,
denom string,
medianDeviation sdk.Dec,
) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: medianDeviation})
store.Set(types.KeyMedianDeviation(denom), bz)
}
// getHistoricPrices returns all the historic prices of a given denom.
func (k Keeper) getHistoricPrices(
ctx sdk.Context,
denom string,
) []sdk.Dec {
historicPrices := []sdk.Dec{}
k.IterateHistoricPrices(ctx, denom, func(exchangeRate sdk.Dec) bool {
historicPrices = append(historicPrices, exchangeRate)
return false
})
return historicPrices
}
// IterateHistoricPrices iterates over historic prices of a given
// denom in the store.
// Iterator stops when exhausting the source, or when the handler returns `true`.
func (k Keeper) IterateHistoricPrices(
ctx sdk.Context,
denom string,
handler func(sdk.Dec) bool,
) {
store := ctx.KVStore(k.storeKey)
// make sure we have one zero byte to correctly separate denoms
prefix := util.ConcatBytes(1, types.KeyPrefixHistoricPrice, []byte(denom))
iter := sdk.KVStorePrefixIterator(store, prefix)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
decProto := sdk.DecProto{}
k.cdc.MustUnmarshal(iter.Value(), &decProto)
if handler(decProto.Dec) {
break
}
}
}
// AddHistoricPrice adds the historic price of a denom at the current
// block height.
func (k Keeper) AddHistoricPrice(
ctx sdk.Context,
denom string,
exchangeRate sdk.Dec,
) {
block := uint64(ctx.BlockHeight())
k.SetHistoricPrice(ctx, denom, block, exchangeRate)
}
func (k Keeper) SetHistoricPrice(
ctx sdk.Context,
denom string,
blockNum uint64,
exchangeRate sdk.Dec,
) {
store := ctx.KVStore(k.storeKey)
bz := k.cdc.MustMarshal(&sdk.DecProto{Dec: exchangeRate})
store.Set(types.KeyHistoricPrice(denom, blockNum), bz)
}
// DeleteHistoricPrice deletes the historic price of a denom at a
// given block.
func (k Keeper) DeleteHistoricPrice(
ctx sdk.Context,
denom string,
blockNum uint64,
) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.KeyHistoricPrice(denom, blockNum))
}
// DeleteMedian deletes a given denom's median price.
func (k Keeper) DeleteMedian(
ctx sdk.Context,
denom string,
) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.KeyMedian(denom))
}
// DeleteMedianDeviation deletes a given denom's standard deviation around
// its median price.
func (k Keeper) DeleteMedianDeviation(
ctx sdk.Context,
denom string,
) {
store := ctx.KVStore(k.storeKey)
store.Delete(types.KeyMedianDeviation(denom))
}
// ClearMedians iterates through all medians in the store and deletes them.
func (k Keeper) ClearMedians(ctx sdk.Context) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, types.KeyPrefixMedian)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
store.Delete(iter.Key())
}
}
// ClearMedianDeviations iterates through all median deviations in the store
// and deletes them.
func (k Keeper) ClearMedianDeviations(ctx sdk.Context) {
store := ctx.KVStore(k.storeKey)
iter := sdk.KVStorePrefixIterator(store, types.KeyPrefixMedianDeviation)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
store.Delete(iter.Key())
}
}