-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
v2_cross.go
59 lines (49 loc) · 998 Bytes
/
v2_cross.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
package indicator
import (
"github.com/c9s/bbgo/pkg/datatype/floats"
)
type CrossType float64
const (
CrossOver CrossType = 1.0
CrossUnder CrossType = -1.0
)
// CrossStream subscribes 2 upstreams, and calculate the cross signal
type CrossStream struct {
*Float64Series
a, b floats.Slice
}
// Cross creates the CrossStream object:
//
// cross := Cross(fastEWMA, slowEWMA)
func Cross(a, b Float64Source) *CrossStream {
s := &CrossStream{
Float64Series: NewFloat64Series(),
}
a.OnUpdate(func(v float64) {
s.a.Push(v)
s.calculate()
})
b.OnUpdate(func(v float64) {
s.b.Push(v)
s.calculate()
})
return s
}
func (s *CrossStream) calculate() {
if s.a.Length() != s.b.Length() {
return
}
current := s.a.Last(0) - s.b.Last(0)
previous := s.a.Last(1) - s.b.Last(1)
if previous == 0.0 {
return
}
// cross over or cross under
if current*previous < 0 {
if current > 0 {
s.PushAndEmit(float64(CrossOver))
} else {
s.PushAndEmit(float64(CrossUnder))
}
}
}