2023-05-26 06:31:06 +00:00
|
|
|
package indicator
|
|
|
|
|
|
|
|
import "github.com/c9s/bbgo/pkg/types"
|
|
|
|
|
|
|
|
const MaxNumOfKLines = 4_000
|
|
|
|
|
|
|
|
//go:generate callbackgen -type KLineStream
|
|
|
|
type KLineStream struct {
|
|
|
|
updateCallbacks []func(k types.KLine)
|
|
|
|
|
|
|
|
kLines []types.KLine
|
|
|
|
}
|
|
|
|
|
2023-06-01 03:43:37 +00:00
|
|
|
func (s *KLineStream) Length() int {
|
|
|
|
return len(s.kLines)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *KLineStream) Last(i int) *types.KLine {
|
|
|
|
l := len(s.kLines)
|
|
|
|
if i < 0 || l-1-i < 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return &s.kLines[l-1-i]
|
|
|
|
}
|
|
|
|
|
2023-05-26 07:18:43 +00:00
|
|
|
// AddSubscriber adds the subscriber function and push historical data to the subscriber
|
2023-05-26 06:31:06 +00:00
|
|
|
func (s *KLineStream) AddSubscriber(f func(k types.KLine)) {
|
2023-06-01 03:43:37 +00:00
|
|
|
s.OnUpdate(f)
|
|
|
|
|
2023-06-30 02:58:07 +00:00
|
|
|
if len(s.kLines) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// push historical klines to the subscriber
|
|
|
|
for _, k := range s.kLines {
|
|
|
|
f(k)
|
2023-05-26 06:31:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-30 02:38:38 +00:00
|
|
|
func (s *KLineStream) BackFill(kLines []types.KLine) {
|
2023-06-30 02:58:07 +00:00
|
|
|
for _, k := range kLines {
|
|
|
|
s.kLines = append(s.kLines, k)
|
|
|
|
s.EmitUpdate(k)
|
|
|
|
}
|
2023-06-29 09:44:36 +00:00
|
|
|
}
|
|
|
|
|
2023-05-26 06:31:06 +00:00
|
|
|
// KLines creates a KLine stream that pushes the klines to the subscribers
|
2023-06-01 03:43:37 +00:00
|
|
|
func KLines(source types.Stream, symbol string, interval types.Interval) *KLineStream {
|
2023-05-26 06:31:06 +00:00
|
|
|
s := &KLineStream{}
|
|
|
|
|
2023-06-01 03:43:37 +00:00
|
|
|
source.OnKLineClosed(types.KLineWith(symbol, interval, func(k types.KLine) {
|
2023-05-26 06:31:06 +00:00
|
|
|
s.kLines = append(s.kLines, k)
|
2023-06-01 03:43:37 +00:00
|
|
|
s.EmitUpdate(k)
|
2023-05-26 06:31:06 +00:00
|
|
|
|
|
|
|
if len(s.kLines) > MaxNumOfKLines {
|
|
|
|
s.kLines = s.kLines[len(s.kLines)-1-MaxNumOfKLines:]
|
|
|
|
}
|
2023-06-01 03:43:37 +00:00
|
|
|
}))
|
2023-05-26 06:31:06 +00:00
|
|
|
|
|
|
|
return s
|
|
|
|
}
|