-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
series_float64.go
106 lines (86 loc) · 1.98 KB
/
series_float64.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package types
import (
"github.com/c9s/bbgo/pkg/datatype/floats"
)
type Float64Series struct {
SeriesBase
Float64Updater
Slice floats.Slice
}
func NewFloat64Series(v ...float64) *Float64Series {
s := &Float64Series{}
s.Slice = v
s.SeriesBase.Series = s.Slice
return s
}
func (f *Float64Series) Last(i int) float64 {
return f.Slice.Last(i)
}
func (f *Float64Series) Index(i int) float64 {
return f.Last(i)
}
func (f *Float64Series) Length() int {
return len(f.Slice)
}
func (f *Float64Series) Push(x float64) {
f.Slice.Push(x)
}
func (f *Float64Series) PushAndEmit(x float64) {
f.Slice.Push(x)
f.EmitUpdate(x)
}
func (f *Float64Series) Subscribe(source Float64Source, c func(x float64)) {
if sub, ok := source.(Float64Subscription); ok {
sub.AddSubscriber(c)
} else {
source.OnUpdate(c)
}
}
// AddSubscriber adds the subscriber function and push historical data to the subscriber
func (f *Float64Series) AddSubscriber(fn func(v float64)) {
f.OnUpdate(fn)
if f.Length() == 0 {
return
}
// push historical values to the subscriber
for _, vv := range f.Slice {
fn(vv)
}
}
// Bind binds the source event to the target (Float64Calculator)
// A Float64Calculator should be able to calculate the float64 result from a single float64 argument input
func (f *Float64Series) Bind(source Float64Source, target Float64Calculator) {
var c func(x float64)
// optimize the truncation check
trc, canTruncate := target.(Float64Truncator)
if canTruncate {
c = func(x float64) {
y := target.Calculate(x)
target.PushAndEmit(y)
trc.Truncate()
}
} else {
c = func(x float64) {
y := target.Calculate(x)
target.PushAndEmit(y)
}
}
if source != nil {
f.Subscribe(source, c)
}
}
type Float64Calculator interface {
Calculate(x float64) float64
PushAndEmit(x float64)
}
type Float64Source interface {
Series
OnUpdate(f func(v float64))
}
type Float64Subscription interface {
Series
AddSubscriber(f func(v float64))
}
type Float64Truncator interface {
Truncate()
}