diff --git a/bbgo/types/kline.go b/bbgo/types/kline.go index 1af945f5b..2470ef215 100644 --- a/bbgo/types/kline.go +++ b/bbgo/types/kline.go @@ -214,6 +214,10 @@ func (k KLineWindow) First() KLine { return k[0] } +func (k KLineWindow) Last() KLine { + return k[len(k)-1] +} + func (k KLineWindow) GetInterval() string { return k.First().Interval } @@ -330,17 +334,19 @@ func (k KLineWindow) Tail(size int) KLineWindow { return win } +// Truncate removes the old klines from the window func (k *KLineWindow) Truncate(size int) { if len(*k) <= size { return } - end := len(*k) - 1 + end := len(*k) start := end - size if start < 0 { start = 0 } - *k = (*k)[start:end] + kn := (*k)[start:] + *k = kn } func (k KLineWindow) GetBody() float64 { diff --git a/bbgo/types/kline_test.go b/bbgo/types/kline_test.go index b550d560b..5322b094d 100644 --- a/bbgo/types/kline_test.go +++ b/bbgo/types/kline_test.go @@ -20,3 +20,25 @@ func TestKLineWindow_Tail(t *testing.T) { var win4 = win.Tail(3) assert.Len(t, win4, 2) } + +func TestKLineWindow_Truncate(t *testing.T) { + var win = KLineWindow{ + { Open: "11600.0", Close: "11600.0", High: "11600.0", Low: "11600.0"}, + { Open: "11601.0", Close: "11600.0", High: "11600.0", Low: "11600.0"}, + { Open: "11602.0", Close: "11600.0", High: "11600.0", Low: "11600.0"}, + { Open: "11603.0", Close: "11600.0", High: "11600.0", Low: "11600.0"}, + } + + win.Truncate(5) + assert.Len(t, win, 4) + assert.Equal(t, "11603.0", win.Last().Open) + + win.Truncate(3) + assert.Len(t, win, 3) + assert.Equal(t, "11603.0", win.Last().Open) + + + win.Truncate(1) + assert.Len(t, win, 1) + assert.Equal(t, "11603.0", win.Last().Open) +}