Skip to content

Commit

Permalink
FIX: fix memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
kbearXD committed Sep 5, 2024
1 parent 1b40118 commit c60fc51
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 3 deletions.
9 changes: 7 additions & 2 deletions pkg/bbgo/marketdatastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import "github.com/c9s/bbgo/pkg/types"
const MaxNumOfKLines = 5_000
const MaxNumOfKLinesTruncate = 100

const CapacityOfKLineWindowLimit = 5_000

// MarketDataStore receives and maintain the public market data of a single symbol
//go:generate callbackgen -type MarketDataStore
type MarketDataStore struct {
Expand Down Expand Up @@ -57,8 +59,11 @@ func (store *MarketDataStore) AddKLine(k types.KLine) {
}
window.Add(k)

if len(*window) > MaxNumOfKLines {
*window = (*window)[MaxNumOfKLinesTruncate-1:]
lenOfWindow := len(*window)
capOfWindow := cap(*window)

if lenOfWindow == capOfWindow && capOfWindow > CapacityOfKLineWindowLimit {
window.TruncateByCopy(CapacityOfKLineWindowLimit / 2)
}

store.EmitKLineClosed(k)
Expand Down
11 changes: 11 additions & 0 deletions pkg/types/kline.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,17 @@ func (k *KLineWindow) Truncate(size int) {
*k = kn
}

// Remain remove the old kline to remain only size klines in the window
func (k *KLineWindow) TruncateByCopy(size int) {
start := len(*k) - size
if start <= 0 {
return
}

copy(*k, (*k)[start:])
*k = (*k)[:size]
}

func (k KLineWindow) GetBody() fixedpoint.Value {
return k.GetChange()
}
Expand Down
45 changes: 44 additions & 1 deletion pkg/types/kline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package types

import (
"encoding/json"
"github.com/stretchr/testify/assert"
"testing"

"github.com/stretchr/testify/assert"
)

func TestKLineWindow_Tail(t *testing.T) {
Expand Down Expand Up @@ -56,3 +57,45 @@ func TestKLineWindow_Truncate(t *testing.T) {
assert.Len(t, win, 1)
assert.Equal(t, 11603.0, win.Last().Open.Float64())
}

func TestKLineWindow_TruncateByCopy(t *testing.T) {
window := KLineWindow{
{GID: 0},
{GID: 1},
{GID: 2},
{GID: 3},
{GID: 4},
{GID: 5},
{GID: 6},
{GID: 7},
{GID: 8},
{GID: 9},
}

assert.Equal(t, 10, len(window))
assert.Equal(t, 10, cap(window))

window.TruncateByCopy(4)

assert.Equal(t, 4, len(window))
assert.Equal(t, 10, cap(window))

var startGID uint64 = 6
for i := range window {
assert.Equal(t, startGID, window[i].GID)
startGID++
}

window.Add(KLine{GID: 10})
window.Add(KLine{GID: 11})
window.Add(KLine{GID: 12})

assert.Equal(t, 7, len(window))
assert.Equal(t, 10, cap(window))

startGID = 6
for i := range window {
assert.Equal(t, startGID, window[i].GID)
startGID++
}
}

0 comments on commit c60fc51

Please sign in to comment.