bbgo_origin/pkg/strategy/shakegrid/grid.go

70 lines
1.7 KiB
Go
Raw Normal View History

2021-10-29 05:27:12 +00:00
package shakegrid
2021-10-29 06:00:55 +00:00
import (
"github.com/c9s/bbgo/pkg/fixedpoint"
)
2021-10-29 05:27:12 +00:00
type Grid struct {
UpperPrice fixedpoint.Value `json:"upperPrice"`
LowerPrice fixedpoint.Value `json:"lowerPrice"`
2021-10-29 06:00:55 +00:00
// Spread is the spread of each grid
Spread fixedpoint.Value `json:"spread"`
2021-10-29 05:27:12 +00:00
2021-10-29 06:00:55 +00:00
// Size is the number of total grids
Size fixedpoint.Value `json:"size"`
2021-10-29 05:27:12 +00:00
// Pins are the pinned grid prices, from low to high
Pins []fixedpoint.Value `json:"pins"`
}
func NewGrid(lower, upper, density fixedpoint.Value) *Grid {
var height = upper - lower
var size = height.Div(density)
var pins []fixedpoint.Value
2021-10-29 06:00:55 +00:00
for p := lower; p <= upper; p += size {
2021-10-29 05:27:12 +00:00
pins = append(pins, p)
}
return &Grid{
UpperPrice: upper,
LowerPrice: lower,
2021-10-29 06:00:55 +00:00
Size: density,
Spread: size,
Pins: pins,
2021-10-29 05:27:12 +00:00
}
}
2021-10-29 06:00:55 +00:00
func (g *Grid) ExtendUpperPrice(upper fixedpoint.Value) (newPins []fixedpoint.Value) {
g.UpperPrice = upper
2021-10-29 05:27:12 +00:00
2021-10-29 06:00:55 +00:00
// since the grid is extended, the size should be updated as well
g.Size = (g.UpperPrice - g.LowerPrice).Div(g.Spread).Ceil()
lastPin := g.Pins[ len(g.Pins) - 1 ]
for p := lastPin + g.Spread; p <= g.UpperPrice; p += g.Spread {
newPins = append(newPins, p)
}
g.Pins = append(g.Pins, newPins...)
return newPins
2021-10-29 05:27:12 +00:00
}
2021-10-29 06:00:55 +00:00
func (g *Grid) ExtendLowerPrice(lower fixedpoint.Value) (newPins []fixedpoint.Value) {
g.LowerPrice = lower
// since the grid is extended, the size should be updated as well
g.Size = (g.UpperPrice - g.LowerPrice).Div(g.Spread).Ceil()
firstPin := g.Pins[0]
numToAdd := (firstPin - g.LowerPrice).Div(g.Spread).Ceil()
for p := firstPin - g.Spread.Mul(numToAdd); p < firstPin; p += g.Spread {
newPins = append(newPins, p)
}
2021-10-29 05:27:12 +00:00
2021-10-29 06:00:55 +00:00
g.Pins = append(newPins, g.Pins...)
return newPins
2021-10-29 05:27:12 +00:00
}