Skip to content

Commit 36ccd2d

Browse files
committed
indicator/v2: add MAXStream
1 parent 18c3fcf commit 36ccd2d

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

pkg/indicator/v2/max.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package indicatorv2
2+
3+
import (
4+
"github.com/c9s/bbgo/pkg/types"
5+
)
6+
7+
// MAXStream calculates the maximum value in a window from a float number stream.
8+
type MAXStream struct {
9+
*types.Float64Series
10+
11+
window int
12+
rawValues *types.Queue
13+
}
14+
15+
func MAX(source types.Float64Source, window int) *MAXStream {
16+
s := &MAXStream{
17+
Float64Series: types.NewFloat64Series(),
18+
window: window,
19+
rawValues: types.NewQueue(window),
20+
}
21+
22+
s.Bind(source, s)
23+
return s
24+
}
25+
26+
func (s *MAXStream) Calculate(v float64) float64 {
27+
s.rawValues.Update(v)
28+
return types.Max(s.rawValues, s.window)
29+
}
30+
31+
func (s *MAXStream) Truncate() {
32+
s.Slice = types.ShrinkSlice(s.Slice, MaxSliceSize, TruncateSize)
33+
}

pkg/indicator/v2/max_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package indicatorv2
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
8+
"github.com/c9s/bbgo/pkg/types"
9+
)
10+
11+
func TestMAX(t *testing.T) {
12+
source := types.NewFloat64Series()
13+
maxIndicator := MAX(source, 3)
14+
15+
// Test case 1: Fill the window
16+
source.PushAndEmit(1.0)
17+
assert.Equal(t, 1.0, maxIndicator.Last(0))
18+
19+
source.PushAndEmit(3.0)
20+
assert.Equal(t, 3.0, maxIndicator.Last(0))
21+
22+
source.PushAndEmit(2.0)
23+
assert.Equal(t, 3.0, maxIndicator.Last(0))
24+
25+
// Test case 2: Sliding window
26+
source.PushAndEmit(1.0)
27+
// Window is [3.0, 2.0, 1.0], max is 3.0
28+
assert.Equal(t, 3.0, maxIndicator.Last(0))
29+
30+
source.PushAndEmit(0.5)
31+
// Window is [2.0, 1.0, 0.5], max is 2.0
32+
assert.Equal(t, 2.0, maxIndicator.Last(0))
33+
34+
source.PushAndEmit(4.0)
35+
// Window is [1.0, 0.5, 4.0], max is 4.0
36+
assert.Equal(t, 4.0, maxIndicator.Last(0))
37+
}

0 commit comments

Comments
 (0)