-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
339 lines (296 loc) · 6.86 KB
/
db.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package kstreamdb
import (
"bytes"
"compress/zlib"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/vmihailenco/msgpack"
)
// DepthItem represents a single market depth entry.
type DepthItem struct {
Price float32
Quantity uint32
Orders uint32
}
// TickData into .tck. symstr +16 len bytes
type TickData struct {
TradingSymbol string
IsTradable bool
Timestamp time.Time
LastTradeTime time.Time
LastPrice float32
LastTradedQuantity uint32
AverageTradePrice float32
VolumeTraded uint32
TotalBuyQuantity uint32
TotalSellQuantity uint32
DayOpen float32
DayHighPrice float32
DayLowPrice float32
LastDayClose float32
OI uint32
OIDayHigh uint32
OIDayLow uint32
Bid [5]DepthItem
Ask [5]DepthItem
}
//DB Database
type DB struct {
DataPath string
}
// fileExists checks if a file exists and is not a directory before we
// try using it to prevent further errors.
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func createDirForFile(filepath string) {
dir := path.Dir(filepath)
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
}
}
func writeMsgpackFile(filePath string, object interface{}) error {
file, err := os.Create(filePath)
if err == nil {
b, err := encodeTicks(object, true)
if err == nil {
file.Write(b)
}
file.Close()
}
return err
}
func encodeTicks(object interface{}, bCompress bool) ([]byte, error) {
b, err := msgpack.Marshal(object)
if err != nil {
return nil, err
}
if bCompress {
var zb bytes.Buffer
zw := zlib.NewWriter(&zb)
zw.Write(b)
zw.Close()
return zb.Bytes(), nil
}
return b, nil
}
func decodeTicks(b io.Reader, object interface{}, bCompress bool) error {
var out bytes.Buffer
if bCompress {
reader, err := zlib.NewReader(b)
if err != nil {
return err
}
io.Copy(&out, reader)
reader.Close()
} else {
io.Copy(&out, b)
}
return msgpack.Unmarshal(out.Bytes(), object)
}
func decodeTicksFromBytes(b []byte, object interface{}, bCompress bool) error {
reader := bytes.NewReader(b)
return decodeTicks(reader, object, bCompress)
}
func readMsgpackFile(filePath string, object interface{}) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
err = decodeTicks(file, object, true)
file.Close()
return err
}
// SetupDatabase func
func SetupDatabase(DataPath string) DB {
if DataPath == "" {
DataPath, _ = ioutil.TempDir("", "kstreamdb")
os.MkdirAll(DataPath, 0755)
}
db := DB{DataPath: DataPath}
return db
}
func (r *DB) generateTickFilePath(dt time.Time) string {
filePath := path.Join(r.DataPath, dt.Format("20060102/150405"))
createDirForFile(filePath)
suffixID := int64(0)
for {
fpath := filePath + fmt.Sprintf("_%03d", suffixID) + ".mpz"
if fileExists(fpath) {
suffixID++
continue
}
return fpath
}
}
// Insert method
func (r *DB) Insert(ticks []TickData) error {
if len(ticks) == 0 {
return nil
}
fpath := r.generateTickFilePath(ticks[0].Timestamp)
writeMsgpackFile(fpath, ticks)
return nil
}
//GetDates returns dates
func (r *DB) GetDates() ([]time.Time, error) {
dates := make([]time.Time, 0)
files, err := ioutil.ReadDir(r.DataPath)
if err == nil {
for _, f := range files {
if f.IsDir() {
dt, err := time.Parse("20060102", f.Name())
if err == nil {
dates = append(dates, dt)
}
}
}
}
return dates, nil
}
//compressFolder compresses all files in a folder into a single file
func (r *DB) compressFolder(dpath string) {
filesByMinute := make(map[string][]string)
keys := make([]string, 0)
var w filepath.WalkFunc
w = func(path string, info os.FileInfo, err error) error {
if (err == nil) && (!info.IsDir()) {
key := info.Name()[0:4]
if _, ok := filesByMinute[key]; !ok {
filesByMinute[key] = make([]string, 0)
keys = append(keys, key)
}
filesByMinute[key] = append(filesByMinute[key], path)
}
return err
}
filepath.Walk(dpath, w)
for _, key := range keys {
if len(filesByMinute[key]) > 1 {
data := loadDataFromFilesList(filesByMinute[key])
for _, fName := range filesByMinute[key] {
os.Remove(fName)
}
r.Insert(data)
}
}
}
//Compress function compresses data from each date into a single file
func (r *DB) Compress() {
files, err := ioutil.ReadDir(r.DataPath)
if err == nil {
for _, f := range files {
if f.IsDir() {
dayPath := path.Join(r.DataPath, f.Name())
r.compressFolder(dayPath)
}
}
}
}
//PlaybackFunc callback
type PlaybackFunc func(TickData)
func playbackFolder(dpath string, fn PlaybackFunc) error {
var w filepath.WalkFunc
w = func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
ticks := new([]TickData)
readMsgpackFile(path, ticks)
for _, t := range *ticks {
fn(t)
}
return nil
}
return filepath.Walk(dpath, w)
}
func loadDataFromFilesList(files []string) []TickData {
data := make([]TickData, 0)
maxworkers := runtime.NumCPU()
jobs := make(chan string, maxworkers)
results := make(chan int, 1)
mapData := make(map[string]*[]TickData)
mutex := &sync.Mutex{}
for w := 0; w < maxworkers; w++ {
go func(fpath <-chan string, result chan<- int) {
for fp := range fpath {
ticks := new([]TickData)
readMsgpackFile(fp, ticks)
if len(*ticks) > 0 {
mutex.Lock()
mapData[fp] = ticks
mutex.Unlock()
}
result <- len(*ticks)
}
}(jobs, results)
}
i := 0
processed := 0
for processed < len(files) {
if (i < len(files)) && (len(jobs) < cap(jobs)) {
jobs <- files[i]
i++
continue
}
<-results
processed++
}
close(jobs)
for _, fp := range files {
if val, ok := mapData[fp]; ok {
data = append(data, *val...)
}
}
return data
}
func loadDataFromFolder(dpath string) ([]TickData, error) {
files := make([]string, 0)
err := filepath.Walk(dpath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
files = append(files, path)
}
return nil
})
data := loadDataFromFilesList(files)
return data, err
}
// LoadDataForDate loads ticks from the date
func (r *DB) LoadDataForDate(dt time.Time) ([]TickData, error) {
dayPath := path.Join(r.DataPath, dt.Format("20060102"))
return loadDataFromFolder(dayPath)
}
// LoadAllData loads all ticks from db
func (r *DB) LoadAllData() ([]TickData, error) {
return loadDataFromFolder(r.DataPath)
}
// PlaybackDate ticks from the date
func (r *DB) PlaybackDate(dt time.Time, fn PlaybackFunc) error {
dayPath := path.Join(r.DataPath, dt.Format("20060102"))
return playbackFolder(dayPath, fn)
}
// PlaybackAll all ticks from db
func (r *DB) PlaybackAll(fn PlaybackFunc) error {
return playbackFolder(r.DataPath, fn)
}
// PlaybackToday all ticks from db
func (r *DB) PlaybackToday(fn PlaybackFunc) error {
return r.PlaybackDate(time.Now(), fn)
}