-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindicator_cached.go
71 lines (64 loc) · 1.58 KB
/
indicator_cached.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
package talib
import (
"sync"
"github.com/shopspring/decimal"
)
var (
ONE = decimal.NewFromInt(1)
TWO = decimal.NewFromInt(2)
HUNDRED = decimal.NewFromInt(100)
)
type Loader func(Indicator, uint64) decimal.Decimal
type CachedIndicator struct {
series *TimeSeries
indicators sync.Map
results sync.Map
loader Loader
}
func NewCacheFrom(series *TimeSeries, loader Loader) *CachedIndicator {
return &CachedIndicator{
series: series,
loader: loader,
}
}
func NewCachedIndicator(indicator Indicator, loader Loader) *CachedIndicator {
return &CachedIndicator{
series: indicator.BarSeries(),
loader: loader,
}
}
func (series *CachedIndicator) LoadOrStore(key string, supplier func() Indicator) Indicator {
if value, ok := series.indicators.Load(key); ok {
return value.(Indicator)
}
indicator := supplier()
series.indicators.Store(key, indicator)
return indicator
}
func (s *CachedIndicator) OutOfBounds(offset uint64) bool {
return offset >= s.series.Size()
}
func (s *CachedIndicator) BarSeries() *TimeSeries {
return s.series
}
func (i *CachedIndicator) Offset(offset uint64) decimal.Decimal {
if offset == 0 || i.OutOfBounds(offset) {
return i.loader(i, offset)
}
cursor := i.series.Cursor(offset)
if res, ok := i.results.Load(cursor); ok {
return res.(decimal.Decimal)
}
res := i.loader(i, offset)
i.results.Store(cursor, res)
return res
}
func (i *CachedIndicator) Delete(times []uint64) {
for key := range times {
i.results.Delete(key)
}
i.indicators.Range(func(key, value interface{}) bool {
value.(Indicator).Delete(times)
return true
})
}