-
Notifications
You must be signed in to change notification settings - Fork 55
/
tick.go
60 lines (51 loc) · 1.38 KB
/
tick.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
package types
import (
"math"
"math/big"
sdk "github.com/cosmos/cosmos-sdk/types"
utils "github.com/crescent-network/crescent/v5/types"
)
const (
TickPrecision = 4
)
func ValidateTickPrice(price sdk.Dec) (tick int32, valid bool) {
if !price.IsPositive() {
panic("price must be positive")
}
b := price.BigInt()
c := int32(len(b.Text(10)) - 1) // characteristic of b
ten := big.NewInt(10)
q, r := b.QuoRem(b, ten.Exp(ten, big.NewInt(int64(c-TickPrecision)), nil), new(big.Int))
i := int32(q.Int64())
pow10 := int32(math.Pow10(TickPrecision))
tick = (i - pow10) + 9*pow10*(c-sdk.Precision)
if r.Sign() == 0 {
valid = true
}
return
}
func PriceAtTick(tick int32) sdk.Dec {
pow10 := int(math.Pow10(TickPrecision))
q, r := utils.DivMod(int(tick), 9*pow10)
//if q < prec-sdk.Precision {
// panic("price underflow")
//}
return sdk.NewDecFromIntWithPrec(
sdk.NewIntWithDecimal(int64(pow10+r), sdk.Precision+q-TickPrecision), sdk.Precision)
}
func TickAtPrice(price sdk.Dec) int32 {
tick, _ := ValidateTickPrice(price)
return tick
}
// RoundTick returns rounded tick using banker's rounding.
func RoundTick(tick int32) int32 {
return (tick + tick%2) / 2 * 2
}
// RoundPrice returns rounded tick price using banker's rounding.
func RoundPrice(price sdk.Dec) sdk.Dec {
tick, valid := ValidateTickPrice(price)
if valid {
return price
}
return PriceAtTick(RoundTick(tick))
}