-
Notifications
You must be signed in to change notification settings - Fork 223
/
aggtrigger.go
239 lines (216 loc) · 6.38 KB
/
aggtrigger.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// OnDiskAgg implements a trigger to downsample base timeframe data
// and write to disk. Underlying data schema is expected at least
// - Open:float32 or float64
// - High:float32 or float64
// - Low:float32 or float64
// - Close:float32 or float64
// optionally,
// - Volume:one of float32, float64, or int32
//
// Example:
// triggers:
// - module: ondiskagg.so
// on: */1Min/OHLCV
// config:
// filter: "nasdaq"
// destinations:
// - 5Min
// - 15Min
// - 1H
// - 1D
//
// destinations are downsample target time windows. Optionally, if filter
// is set to "nasdaq", it filters the scan data by NASDAQ market hours.
package aggtrigger
import (
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"github.com/golang/glog"
"github.com/alpacahq/marketstore/contrib/ondiskagg/calendar"
"github.com/alpacahq/marketstore/executor"
"github.com/alpacahq/marketstore/planner"
"github.com/alpacahq/marketstore/plugins/trigger"
"github.com/alpacahq/marketstore/utils"
"github.com/alpacahq/marketstore/utils/io"
)
// AggTriggerConfig is the configuration for OnDiskAggTrigger you can define in
// marketstore's config file under triggers extension.
type AggTriggerConfig struct {
Destinations []string `json:"destinations"`
Filter string `json:"filter"`
}
// OnDiskAggTrigger is the main trigger.
type OnDiskAggTrigger struct {
config map[string]interface{}
destinations []string
// filter by market hours if this is "nasdaq"
filter string
}
var _ trigger.Trigger = &OnDiskAggTrigger{}
var loadError = errors.New("plugin load error")
func recast(config map[string]interface{}) *AggTriggerConfig {
data, _ := json.Marshal(config)
ret := AggTriggerConfig{}
json.Unmarshal(data, &ret)
return &ret
}
// NewTrigger returns a new on-disk aggregate trigger based on the configuration.
func NewTrigger(conf map[string]interface{}) (trigger.Trigger, error) {
config := recast(conf)
if len(config.Destinations) == 0 {
glog.Errorf("no destinations are configured")
return nil, loadError
}
glog.Infof("%d destination(s) configured", len(config.Destinations))
filter := config.Filter
if filter != "" && filter != "nasdaq" {
glog.Infof("filter value \"%s\" is not recognized", filter)
filter = ""
}
return &OnDiskAggTrigger{
config: conf,
destinations: config.Destinations,
filter: filter,
}, nil
}
func minInt64(values []int64) int64 {
min := values[0]
for _, v := range values[1:] {
if v < min {
min = v
}
}
return min
}
func maxInt64(values []int64) int64 {
max := values[0]
for _, v := range values[1:] {
if v > max {
max = v
}
}
return max
}
// Fire implements trigger interface.
func (s *OnDiskAggTrigger) Fire(keyPath string, indexes []int64) {
headIndex := minInt64(indexes)
tailIndex := maxInt64(indexes)
for _, timeframe := range s.destinations {
s.processFor(timeframe, keyPath, headIndex, tailIndex)
}
}
func (s *OnDiskAggTrigger) processFor(timeframe, keyPath string, headIndex, tailIndex int64) {
theInstance := executor.ThisInstance
catalogDir := theInstance.CatalogDir
elements := strings.Split(keyPath, "/")
tbkString := strings.Join(elements[:len(elements)-1], "/")
tf := utils.NewTimeframe(elements[1])
fileName := elements[len(elements)-1]
year, _ := strconv.Atoi(strings.Replace(fileName, ".bin", "", 1))
tbk := io.NewTimeBucketKey(tbkString)
headTs := io.IndexToTime(headIndex, tf.Duration, int16(year))
tailTs := io.IndexToTime(tailIndex, tf.Duration, int16(year))
timeWindow := utils.CandleDurationFromString(timeframe)
start := timeWindow.Truncate(headTs)
end := timeWindow.Ceil(tailTs)
// TODO: this is not needed once we support "<" operator
end = end.Add(-time.Second)
targetTbkString := elements[0] + "/" + timeframe + "/" + elements[2]
targetTbk := io.NewTimeBucketKey(targetTbkString)
// Scan
q := planner.NewQuery(catalogDir)
q.AddTargetKey(tbk)
q.SetRange(start, end)
// decide whether to apply market-hour filter
applyingFilter := false
if s.filter == "nasdaq" && timeWindow.Duration() >= utils.Day {
calendarTz := calendar.Nasdaq.Tz()
if utils.InstanceConfig.Timezone.String() != calendarTz.String() {
glog.Errorf("misconfiguration... system must be configure in %s", calendarTz)
} else {
q.AddTimeQual(calendar.Nasdaq.EpochIsMarketOpen)
applyingFilter = true
}
}
parsed, err := q.Parse()
if err != nil {
glog.Errorf("%v", err)
return
}
scanner, err := executor.NewReader(parsed)
if err != nil {
glog.Errorf("%v", err)
return
}
csm, _, err := scanner.Read()
if err != nil {
glog.Errorf("%v", err)
return
}
cs := csm[*tbk]
if cs == nil || cs.Len() == 0 {
if !applyingFilter {
// Nothing in there... really?
glog.Errorf(
"result is empty for %s -> %s - query: %v - %v",
tbk,
targetTbk,
q.Range.Start,
q.Range.End,
)
}
return
}
// calculate aggregated values
outCs := aggregate(cs, targetTbk)
outCsm := io.NewColumnSeriesMap()
outCsm.AddColumnSeries(*targetTbk, outCs)
epoch := outCs.GetEpoch()
if err := executor.WriteCSM(outCsm, false); err != nil {
glog.Errorf(
"failed to write %v CSM from: %v to %v - Error: %v",
targetTbk.String(),
time.Unix(epoch[0], 0),
time.Unix(epoch[len(epoch)-1], 0),
err)
}
}
func aggregate(cs *io.ColumnSeries, tbk *io.TimeBucketKey) *io.ColumnSeries {
timeWindow := utils.CandleDurationFromString(tbk.GetItemInCategory("Timeframe"))
params := []accumParam{
accumParam{"Open", "first", "Open"},
accumParam{"High", "max", "High"},
accumParam{"Low", "min", "Low"},
accumParam{"Close", "last", "Close"},
}
if cs.Exists("Volume") {
params = append(params, accumParam{"Volume", "sum", "Volume"})
}
accumGroup := newAccumGroup(cs, params)
ts := cs.GetTime()
outEpoch := make([]int64, 0)
groupKey := timeWindow.Truncate(ts[0])
groupStart := 0
// accumulate inputs. Since the input is ordered by
// time, it is just to slice by correct boundaries
for i, t := range ts {
if !timeWindow.IsWithin(t, groupKey) {
// Emit new row and re-init aggState
outEpoch = append(outEpoch, groupKey.Unix())
accumGroup.apply(groupStart, i)
groupKey = timeWindow.Truncate(t)
groupStart = i
}
}
// accumulate any remaining values if not yet
outEpoch = append(outEpoch, groupKey.Unix())
accumGroup.apply(groupStart, len(ts))
// finalize output
outCs := io.NewColumnSeries()
outCs.AddColumn("Epoch", outEpoch)
accumGroup.addColumns(outCs)
return outCs
}