grid: add pin cache

This commit is contained in:
c9s 2021-10-29 14:08:56 +08:00 committed by c9s
parent b2f8abd56c
commit 47fbe3a3ed
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 31 additions and 2 deletions

View File

@ -16,6 +16,8 @@ type Grid struct {
// Pins are the pinned grid prices, from low to high
Pins []fixedpoint.Value `json:"pins"`
pinsCache map[fixedpoint.Value]struct{} `json:"-"`
}
func NewGrid(lower, upper, density fixedpoint.Value) *Grid {
@ -27,13 +29,27 @@ func NewGrid(lower, upper, density fixedpoint.Value) *Grid {
pins = append(pins, p)
}
return &Grid{
grid := &Grid{
UpperPrice: upper,
LowerPrice: lower,
Size: density,
Spread: size,
Pins: pins,
pinsCache: make(map[fixedpoint.Value]struct{}, len(pins)),
}
grid.updatePinsCache()
return grid
}
func (g *Grid) updatePinsCache() {
for _, pin := range g.Pins {
g.pinsCache[pin] = struct{}{}
}
}
func (g *Grid) HasPin(pin fixedpoint.Value) (ok bool) {
_, ok = g.pinsCache[pin]
return ok
}
func (g *Grid) ExtendUpperPrice(upper fixedpoint.Value) (newPins []fixedpoint.Value) {
@ -48,6 +64,7 @@ func (g *Grid) ExtendUpperPrice(upper fixedpoint.Value) (newPins []fixedpoint.Va
}
g.Pins = append(g.Pins, newPins...)
g.updatePinsCache()
return newPins
}
@ -68,5 +85,6 @@ func (g *Grid) ExtendLowerPrice(lower fixedpoint.Value) (newPins []fixedpoint.Va
}
g.Pins = append(newPins, g.Pins...)
g.updatePinsCache()
return newPins
}

View File

@ -20,6 +20,17 @@ func TestNewGrid(t *testing.T) {
}
}
func TestGrid_HasPin(t *testing.T) {
upper := fixedpoint.NewFromFloat(500.0)
lower := fixedpoint.NewFromFloat(100.0)
size := fixedpoint.NewFromFloat(100.0)
grid := NewGrid(lower, upper, size)
assert.True(t, grid.HasPin(fixedpoint.NewFromFloat(100.0)))
assert.True(t, grid.HasPin(fixedpoint.NewFromFloat(500.0)))
assert.False(t, grid.HasPin(fixedpoint.NewFromFloat(101.0)))
}
func TestGrid_ExtendUpperPrice(t *testing.T) {
upper := fixedpoint.NewFromFloat(500.0)
lower := fixedpoint.NewFromFloat(100.0)