-
-
Notifications
You must be signed in to change notification settings - Fork 273
/
marketdatastore.go
66 lines (51 loc) · 1.85 KB
/
marketdatastore.go
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
package bbgo
import "github.com/c9s/bbgo/pkg/types"
const MaxNumOfKLines = 5_000
const MaxNumOfKLinesTruncate = 100
// MarketDataStore receives and maintain the public market data of a single symbol
//go:generate callbackgen -type MarketDataStore
type MarketDataStore struct {
Symbol string
// KLineWindows stores all loaded klines per interval
KLineWindows map[types.Interval]*types.KLineWindow `json:"-"`
kLineWindowUpdateCallbacks []func(interval types.Interval, klines types.KLineWindow)
kLineClosedCallbacks []func(k types.KLine)
}
func NewMarketDataStore(symbol string) *MarketDataStore {
return &MarketDataStore{
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
}
}
func (store *MarketDataStore) SetKLineWindows(windows map[types.Interval]*types.KLineWindow) {
store.KLineWindows = windows
}
// 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) {
stream.OnKLineClosed(store.handleKLineClosed)
}
func (store *MarketDataStore) handleKLineClosed(kline types.KLine) {
if kline.Symbol != store.Symbol {
return
}
store.AddKLine(kline)
}
func (store *MarketDataStore) AddKLine(k types.KLine) {
window, ok := store.KLineWindows[k.Interval]
if !ok {
var tmp = make(types.KLineWindow, 0, 1000)
store.KLineWindows[k.Interval] = &tmp
window = &tmp
}
window.Add(k)
if len(*window) > MaxNumOfKLines {
*window = (*window)[MaxNumOfKLinesTruncate-1:]
}
store.EmitKLineClosed(k)
store.EmitKLineWindowUpdate(k.Interval, *window)
}