-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.go
More file actions
68 lines (56 loc) · 2.22 KB
/
Copy pathgrid.go
File metadata and controls
68 lines (56 loc) · 2.22 KB
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
package main
import (
"math"
exchanges "github.com/QuantProcessing/exchanges"
"github.com/shopspring/decimal"
)
// LevelStatus represents the state of a grid level.
type LevelStatus int
const (
LevelEmpty LevelStatus = iota // No order
LevelOrderPending // Order placed, waiting for fill
)
// GridLevel represents a single grid level.
type GridLevel struct {
Index int // Grid level index (0 = lowest, N = highest)
Price decimal.Decimal // Price at this level
Side exchanges.OrderSide // BUY or SELL (determined by current price at init)
Status LevelStatus // Current status
OrderID string // Active order ID (empty = no order)
}
// CalculateGridPrices calculates all grid price levels.
// gridCount specifies the number of grids, generating gridCount+1 price points (including bounds).
func CalculateGridPrices(lowerPrice, upperPrice decimal.Decimal, gridCount int, gridType GridType, pricePrecision int32) []decimal.Decimal {
count := gridCount + 1 // N grids need N+1 price points
prices := make([]decimal.Decimal, count)
switch gridType {
case GridTypeGeometric:
// Geometric grid: prices[i] = lower * (upper/lower)^(i/N)
lowerF, _ := lowerPrice.Float64()
upperF, _ := upperPrice.Float64()
ratio := upperF / lowerF
for i := 0; i < count; i++ {
exp := float64(i) / float64(gridCount)
price := lowerF * math.Pow(ratio, exp)
prices[i] = decimal.NewFromFloat(price).Round(pricePrecision)
}
default: // arithmetic
// Arithmetic grid: step = (upper - lower) / N
step := upperPrice.Sub(lowerPrice).Div(decimal.NewFromInt(int64(gridCount)))
for i := 0; i < count; i++ {
prices[i] = lowerPrice.Add(step.Mul(decimal.NewFromInt(int64(i)))).Round(pricePrecision)
}
}
return prices
}
// FindCurrentPriceIndex finds the position of the current price in the grid.
// Returns the level index where prices[index] <= currentPrice < prices[index+1].
// Returns -1 if price is below the lowest level, len(prices)-1 if above the highest.
func FindCurrentPriceIndex(prices []decimal.Decimal, currentPrice decimal.Decimal) int {
for i := len(prices) - 1; i >= 0; i-- {
if currentPrice.GreaterThanOrEqual(prices[i]) {
return i
}
}
return -1
}