refactor calculateArithmeticPins

This commit is contained in:
c9s 2022-11-07 13:51:44 +08:00
parent 725c624281
commit 75c088eb9c
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54

View File

@ -14,6 +14,9 @@ type Grid struct {
// Size is the number of total grids // Size is the number of total grids
Size fixedpoint.Value `json:"size"` Size fixedpoint.Value `json:"size"`
// TickSize is the price tick size, this is used for truncating price
TickSize fixedpoint.Value `json:"tickSize"`
// Pins are the pinned grid prices, from low to high // Pins are the pinned grid prices, from low to high
Pins []Pin `json:"pins"` Pins []Pin `json:"pins"`
@ -22,10 +25,7 @@ type Grid struct {
type Pin fixedpoint.Value type Pin fixedpoint.Value
func calculateArithmeticPins(lower, upper, size, tickSize fixedpoint.Value) []Pin { func calculateArithmeticPins(lower, upper, spread, tickSize fixedpoint.Value) []Pin {
var height = upper.Sub(lower)
var spread = height.Div(size)
var pins []Pin var pins []Pin
for p := lower; p.Compare(upper) <= 0; p = p.Add(spread) { for p := lower; p.Compare(upper) <= 0; p = p.Add(spread) {
// tickSize here = 0.01 // tickSize here = 0.01
@ -46,16 +46,16 @@ func buildPinCache(pins []Pin) map[Pin]struct{} {
} }
func NewGrid(lower, upper, size, tickSize fixedpoint.Value) *Grid { func NewGrid(lower, upper, size, tickSize fixedpoint.Value) *Grid {
var pins = calculateArithmeticPins(lower, upper, size, tickSize)
grid := &Grid{ grid := &Grid{
UpperPrice: upper, UpperPrice: upper,
LowerPrice: lower, LowerPrice: lower,
Size: size, Size: size,
Pins: pins, TickSize: tickSize,
pinsCache: buildPinCache(pins),
} }
var spread = grid.Spread()
var pins = calculateArithmeticPins(lower, upper, spread, tickSize)
grid.addPins(pins)
return grid return grid
} }
@ -80,10 +80,6 @@ func (g *Grid) OutOfRange(price fixedpoint.Value) bool {
return price.Compare(g.LowerPrice) < 0 || price.Compare(g.UpperPrice) > 0 return price.Compare(g.LowerPrice) < 0 || price.Compare(g.UpperPrice) > 0
} }
func (g *Grid) updatePinsCache() {
g.pinsCache = buildPinCache(g.Pins)
}
func (g *Grid) HasPin(pin Pin) (ok bool) { func (g *Grid) HasPin(pin Pin) (ok bool) {
_, ok = g.pinsCache[pin] _, ok = g.pinsCache[pin]
return ok return ok
@ -126,3 +122,7 @@ func (g *Grid) addPins(pins []Pin) {
g.updatePinsCache() g.updatePinsCache()
} }
func (g *Grid) updatePinsCache() {
g.pinsCache = buildPinCache(g.Pins)
}