bbgo_origin/pkg/bbgo/marketdatastore.go

64 lines
1.7 KiB
Go
Raw Normal View History

package bbgo
2020-09-05 08:22:46 +00:00
import "github.com/c9s/bbgo/pkg/types"
2020-09-05 08:22:46 +00:00
2021-06-28 06:31:22 +00:00
const MaxNumOfKLines = 5_000
2021-11-21 14:18:07 +00:00
const MaxNumOfKLinesTruncate = 100
2021-06-28 06:31:22 +00:00
// MarketDataStore receives and maintain the public market data
//go:generate callbackgen -type MarketDataStore
type MarketDataStore struct {
2020-10-17 16:06:08 +00:00
Symbol string
// KLineWindows stores all loaded klines per interval
2020-10-18 04:23:00 +00:00
KLineWindows map[types.Interval]types.KLineWindow `json:"-"`
kLineWindowUpdateCallbacks []func(interval types.Interval, kline types.KLineWindow)
2020-09-05 08:22:46 +00:00
}
func NewMarketDataStore(symbol string) *MarketDataStore {
return &MarketDataStore{
2020-10-17 16:06:08 +00:00
Symbol: symbol,
// KLineWindows stores all loaded klines per interval
KLineWindows: make(map[types.Interval]types.KLineWindow, len(types.SupportedIntervals)), // 12 interval, 1m,5m,15m,30m,1h,2h,4h,6h,12h,1d,3d,1w
2020-09-05 08:22:46 +00:00
}
}
2020-10-19 13:58:50 +00:00
func (store *MarketDataStore) SetKLineWindows(windows map[types.Interval]types.KLineWindow) {
store.KLineWindows = windows
}
2020-10-18 12:43:37 +00:00
// KLinesOfInterval returns the kline window of the given interval
func (store *MarketDataStore) KLinesOfInterval(interval types.Interval) (kLines types.KLineWindow, ok bool) {
kLines, ok = store.KLineWindows[interval]
return kLines, ok
}
func (store *MarketDataStore) BindStream(stream types.Stream) {
2020-09-05 08:22:46 +00:00
stream.OnKLineClosed(store.handleKLineClosed)
}
func (store *MarketDataStore) handleKLineClosed(kline types.KLine) {
if kline.Symbol != store.Symbol {
return
2020-10-17 16:06:08 +00:00
}
store.AddKLine(kline)
2020-09-05 08:22:46 +00:00
}
func (store *MarketDataStore) AddKLine(kline types.KLine) {
window, ok := store.KLineWindows[kline.Interval]
if !ok {
2021-11-21 14:33:57 +00:00
window = make(types.KLineWindow, 0, 1000)
}
2021-11-21 14:33:57 +00:00
window.Add(kline)
2021-06-28 06:31:22 +00:00
if len(window) > MaxNumOfKLines {
2021-11-21 14:18:07 +00:00
window = window[MaxNumOfKLinesTruncate-1:]
2021-06-28 06:31:22 +00:00
}
2020-10-28 01:43:19 +00:00
store.KLineWindows[kline.Interval] = window
store.EmitKLineWindowUpdate(kline.Interval, window)
2020-09-05 08:22:46 +00:00
}