-
Notifications
You must be signed in to change notification settings - Fork 4
/
orm.go
1507 lines (1262 loc) · 41.1 KB
/
orm.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package orm
import (
"fmt"
"os"
"path/filepath"
"runtime/debug"
"sort"
"strings"
"sync"
"time"
"github.com/shopspring/decimal"
zenchaincfg "github.com/cosmos/cosmos-sdk/server/config"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/zenchainprotocol/zenchain-node/x/backend/types"
"github.com/zenchainprotocol/zenchain-node/x/token"
"github.com/pkg/errors"
"github.com/tendermint/tendermint/libs/log"
)
// nolint
const (
EngineTypeSqlite = zenchaincfg.BackendOrmEngineTypeSqlite
EngineTypeMysql = zenchaincfg.BackendOrmEngineTypeMysql
)
// nolint
type OrmEngineInfo = zenchaincfg.BackendOrmEngineInfo
// ORM is designed for deal with database by orm
// http://gorm.io/docs/query.html
type ORM struct {
db *gorm.DB
logger *log.Logger
bufferLock sync.Locker
singleEntryLock sync.Locker
lastK15Timestamp int64
klineM15sBuffer map[string][]types.KlineM15
lastK1Timestamp int64
klineM1sBuffer map[string][]types.KlineM1
maxBlockTimestampMutex *sync.RWMutex
maxBlockTimestamp int64
}
func (o *ORM) SetMaxBlockTimestamp(maxBlockTimestamp int64) {
o.maxBlockTimestampMutex.Lock()
defer o.maxBlockTimestampMutex.Unlock()
o.maxBlockTimestamp = maxBlockTimestamp
}
func (o *ORM) GetMaxBlockTimestamp() int64 {
o.maxBlockTimestampMutex.RLock()
defer o.maxBlockTimestampMutex.RUnlock()
return o.maxBlockTimestamp
}
// New return pointer to ORM to deal with database,called at NewKeeper
func New(enableLog bool, engineInfo *OrmEngineInfo, logger *log.Logger) (m *ORM, err error) {
orm := ORM{}
var db *gorm.DB
switch engineInfo.EngineType {
case EngineTypeSqlite:
_, e := os.Stat(engineInfo.ConnectStr)
if e != nil && !os.IsExist(e) {
dbDir := filepath.Dir(engineInfo.ConnectStr)
if _, err := os.Stat(dbDir); err != nil {
if err := os.MkdirAll(dbDir, os.ModePerm); err != nil {
panic(err)
}
orm.Debug(fmt.Sprintf("%s created", dbDir))
}
}
case EngineTypeMysql:
default:
}
if db, err = gorm.Open(engineInfo.EngineType, engineInfo.ConnectStr); err != nil {
e := fmt.Errorf(fmt.Sprintf("ConnectStr: %s, error: %+v", engineInfo.ConnectStr, err))
panic(e)
}
orm.logger = logger
orm.db = db
orm.lastK1Timestamp = -1
orm.lastK15Timestamp = -1
orm.bufferLock = new(sync.Mutex)
orm.singleEntryLock = new(sync.Mutex)
orm.maxBlockTimestampMutex = new(sync.RWMutex)
orm.db.LogMode(enableLog)
orm.db.AutoMigrate(&types.MatchResult{})
orm.db.AutoMigrate(&types.Deal{})
orm.db.AutoMigrate(&token.FeeDetail{})
orm.db.AutoMigrate(&types.Order{})
orm.db.AutoMigrate(&types.Transaction{})
orm.db.AutoMigrate(&types.SwapInfo{})
orm.db.AutoMigrate(&types.SwapWhitelist{})
orm.db.AutoMigrate(&types.ClaimInfo{})
allKlinesMap := types.GetAllKlineMap()
for _, v := range allKlinesMap {
k := types.MustNewKlineFactory(v, nil)
orm.db.AutoMigrate(k)
}
return &orm, nil
}
// Debug log debug info when use orm
func (orm *ORM) Debug(msg string) {
if orm.logger != nil {
(*orm.logger).Debug(msg)
}
}
// Error log occurred error when use orm
func (orm *ORM) Error(msg string) {
if orm.logger != nil {
(*orm.logger).Error(msg)
}
}
func (orm *ORM) deferRollbackTx(trx *gorm.DB, returnErr error) {
e := recover()
if e != nil {
orm.Error(fmt.Sprintf("ORM Panic : %+v", e))
debug.PrintStack()
}
if e != nil || returnErr != nil {
trx.Rollback()
}
}
// Close close the database by orm
func (orm *ORM) Close() error {
return orm.db.Close()
}
// nolint
func (orm *ORM) AddMatchResults(results []*types.MatchResult) (addedCnt int, err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
cnt := 0
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
for _, result := range results {
if result != nil {
ret := tx.Create(result)
if ret.Error != nil {
return cnt, ret.Error
} else {
cnt++
}
}
}
tx.Commit()
return cnt, nil
}
// nolint
func (orm *ORM) GetMatchResults(product string, startTime, endTime int64,
offset, limit int) ([]types.MatchResult, int) {
var matchResults []types.MatchResult
query := orm.db.Model(types.MatchResult{})
if startTime == 0 && endTime == 0 {
endTime = time.Now().Unix()
}
if product != "" {
query = query.Where("product = ?", product)
}
if startTime > 0 {
query = query.Where("timestamp >= ?", startTime)
}
if endTime > 0 {
query = query.Where("timestamp < ?", endTime)
}
var total int
query.Count(&total)
if offset >= total {
return matchResults, total
}
query.Order("timestamp desc").Offset(offset).Limit(limit).Find(&matchResults)
return matchResults, total
}
func (orm *ORM) deleteMatchResultBefore(timestamp int64) (err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
r := tx.Delete(&types.MatchResult{}, " Timestamp < ? ", timestamp)
if r.Error == nil {
tx.Commit()
} else {
return r.Error
}
return nil
}
func (orm *ORM) getMatchResultsByTimeRange(product string, startTime, endTime int64) ([]types.MatchResult, error) {
var matchResults []types.MatchResult
r := orm.db.Model(types.MatchResult{}).Where("Product = ? and Timestamp >= ? and Timestamp < ?",
product, startTime, endTime).Order("Timestamp desc").Find(&matchResults)
if r.Error == nil {
return matchResults, nil
}
return matchResults, r.Error
}
func (orm *ORM) getLatestMatchResults(product string, limit int) ([]types.MatchResult, error) {
var matchResults []types.MatchResult
r := orm.db.Where("Product = ?", product).Order("Timestamp desc").Limit(limit).Find(&matchResults)
if r.Error != nil {
return matchResults, r.Error
}
return matchResults, r.Error
}
// nolint
func (orm *ORM) AddDeals(deals []*types.Deal) (addedCnt int, err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
cnt := 0
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
for _, deal := range deals {
if deal != nil {
ret := tx.Create(deal)
if ret.Error != nil {
return cnt, ret.Error
} else {
cnt++
}
}
}
tx.Commit()
return cnt, nil
}
func (orm *ORM) deleteDealBefore(timestamp int64) (err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
r := tx.Delete(&types.Deal{}, " Timestamp < ? ", timestamp)
if r.Error == nil {
tx.Commit()
} else {
return r.Error
}
return nil
}
func (orm *ORM) getLatestDeals(product string, limit int) ([]types.Deal, error) {
var deals []types.Deal
r := orm.db.Where("Product = ?", product).Order("Timestamp desc").Limit(limit).Find(&deals)
if r.Error != nil {
return nil, r.Error
}
return deals, r.Error
}
// nolint
func (orm *ORM) GetDeals(address, product, side string, startTime, endTime int64, offset, limit int) ([]types.Deal, int) {
var deals []types.Deal
query := orm.db.Model(types.Deal{})
if startTime == 0 && endTime == 0 {
endTime = time.Now().Unix()
}
if address != "" {
query = query.Where("sender = ?", address)
}
if product != "" {
query = query.Where("product = ?", product)
}
if side != "" {
query = query.Where("side = ?", side)
}
if startTime > 0 {
query = query.Where("timestamp >= ?", startTime)
}
if endTime > 0 {
query = query.Where("timestamp < ?", endTime)
}
var total int
query.Count(&total)
if offset >= total {
return deals, total
}
query.Order("timestamp desc").Offset(offset).Limit(limit).Find(&deals)
return deals, total
}
// nolint
func (orm *ORM) GetDexFees(dexHandlingAddr, product string, offset, limit int) ([]types.DexFees, int) {
var deals []types.Deal
query := orm.db.Model(types.Deal{})
if dexHandlingAddr != "" {
query = query.Where("fee_receiver = ?", dexHandlingAddr)
}
if product != "" {
query = query.Where("product = ?", product)
}
var total int
query.Count(&total)
if offset >= total {
return nil, total
}
query.Order("timestamp desc").Offset(offset).Limit(limit).Find(&deals)
if len(deals) == 0 {
return nil, 0
}
var dexFees []types.DexFees
for _, deal := range deals {
dexFees = append(dexFees, types.DexFees{
Timestamp: deal.Timestamp,
OrderID: deal.OrderID,
Product: deal.Product,
Fee: deal.Fee,
HandlingFeeAddr: deal.FeeReceiver,
})
}
return dexFees, total
}
func (orm *ORM) getDealsByTimestampRange(product string, startTS, endTS int64) ([]types.Deal, error) {
var deals []types.Deal
r := orm.db.Model(types.Deal{}).Where(
"Product = ? and Timestamp >= ? and Timestamp < ?", product, startTS, endTS).Order("Timestamp desc").Find(&deals)
if r.Error == nil {
return deals, nil
}
return nil, r.Error
}
func (orm *ORM) getOpenCloseDeals(startTS, endTS int64, product string) (open *types.Deal, close *types.Deal) {
var openDeal, closeDeal types.Deal
orm.db.Model(types.Deal{}).Where("Timestamp >= ? and Timestamp < ? and Product = ?", startTS, endTS, product).Order("Timestamp desc").Limit(1).First(&closeDeal)
orm.db.Model(types.Deal{}).Where("Timestamp >= ? and Timestamp < ? and Product = ?", startTS, endTS, product).Order("Timestamp asc").Limit(1).First(&openDeal)
if startTS <= openDeal.Timestamp && openDeal.Timestamp < endTS {
return &openDeal, &closeDeal
}
return nil, nil
}
func (orm *ORM) getOpenCloseKline(startTS, endTS int64, product string, firstK interface{}, lastK interface{}) error {
defer types.PrintStackIfPanic()
orm.db.Where("Timestamp >= ? and Timestamp < ? and Product = ?", startTS, endTS, product).Order("Timestamp desc").Limit(1).First(lastK)
orm.db.Where("Timestamp >= ? and Timestamp < ? and Product = ?", startTS, endTS, product).Order("Timestamp asc").Limit(1).First(firstK)
return nil
}
func (orm *ORM) getMinTimestamp(tbName string) int64 {
sql := fmt.Sprintf("select min(Timestamp) as ts from %s", tbName)
ts := int64(-1)
count := 0
raw := orm.db.Raw(sql)
raw.Count(&count)
if count == 0 {
return ts
}
if err := raw.Row().Scan(&ts); err != nil {
orm.Error("failed to execute scan result, error:" + err.Error())
}
return ts
}
func (orm *ORM) getMaxTimestamp(tbName string) int64 {
sql := fmt.Sprintf("select max(Timestamp) as ts from %s", tbName)
ts := int64(-1)
count := 0
raw := orm.db.Raw(sql)
raw.Count(&count)
if count == 0 {
return ts
}
if err := raw.Row().Scan(&ts); err != nil {
orm.Error("failed to execute scan result, error:" + err.Error())
}
return ts
}
func (orm *ORM) getMergingKlineTimestamp(tbName string, timestamp int64) int64 {
sql := fmt.Sprintf("select max(Timestamp) as ts from %s where Timestamp <=%d", tbName, timestamp)
ts := int64(-1)
count := 0
raw := orm.db.Raw(sql)
raw.Count(&count)
if count == 0 {
return ts
}
if err := raw.Row().Scan(&ts); err != nil {
orm.Error("failed to execute scan result, error:" + err.Error())
}
return ts
}
func (orm *ORM) getDealsMinTimestamp() int64 {
return orm.getMinTimestamp("deals")
}
func (orm *ORM) getDealsMaxTimestamp() int64 {
return orm.getMaxTimestamp("deals")
}
func (orm *ORM) getKlineMaxTimestamp(k types.IKline) int64 {
return orm.getMaxTimestamp(k.GetTableName())
}
func (orm *ORM) getKlineMinTimestamp(k types.IKline) int64 {
return orm.getMinTimestamp(k.GetTableName())
}
func (orm *ORM) getMergeResultMinTimestamp() int64 {
return orm.getMinTimestamp("match_results")
}
func (orm *ORM) getMergeResultMaxTimestamp() int64 {
return orm.getMaxTimestamp("match_results")
}
// nolint
type IKline1MDataSource interface {
getDataSourceMinTimestamp() int64
getMaxMinSumByGroupSQL(startTS, endTS int64) string
getOpenClosePrice(startTS, endTS int64, product string) (float64, float64)
}
// nolint
type DealDataSource struct {
orm *ORM
}
func (dm *DealDataSource) getDataSourceMinTimestamp() int64 {
return dm.orm.getDealsMinTimestamp()
}
func (dm *DealDataSource) getMaxMinSumByGroupSQL(startTS, endTS int64) string {
sql := fmt.Sprintf("select product, sum(Quantity) as quantity, max(Price) as high, min(Price) as low, count(price) as cnt from deals "+
"where Timestamp >= %d and Timestamp < %d and Side = 'BUY' group by product", startTS, endTS)
return sql
}
func (dm *DealDataSource) getOpenClosePrice(startTS, endTS int64, product string) (float64, float64) {
openDeal, closeDeal := dm.orm.getOpenCloseDeals(startTS, endTS, product)
return openDeal.Price, closeDeal.Price
}
// nolint
type MergeResultDataSource struct {
Orm *ORM
}
func (dm *MergeResultDataSource) getDataSourceMinTimestamp() int64 {
return dm.Orm.getMergeResultMinTimestamp()
}
func (dm *MergeResultDataSource) getMaxMinSumByGroupSQL(startTS, endTS int64) string {
sql := fmt.Sprintf("select product, sum(Quantity) as quantity, max(Price) as high, min(Price) as low, count(price) as cnt from match_results "+
"where Timestamp >= %d and Timestamp < %d group by product", startTS, endTS)
return sql
}
func (dm *MergeResultDataSource) getOpenClosePrice(startTS, endTS int64, product string) (float64, float64) {
openDeal, closeDeal := dm.Orm.getOpenCloseDeals(startTS, endTS, product)
return openDeal.Price, closeDeal.Price
}
// CreateKline1M batch insert into Kline1M
func (orm *ORM) CreateKline1M(startTS, endTS int64, dataSource IKline1MDataSource) (
anchorEndTS int64, newProductCnt int, newKlineInfo map[string][]types.KlineM1, err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
// 1. Get anchor start time.
if endTS <= startTS {
return -1, 0, nil, fmt.Errorf("EndTimestamp %d <= StartTimestamp %d, somewhere goes wrong", endTS, startTS)
}
acTS := startTS
maxTSPersistent := orm.getKlineMaxTimestamp(&types.KlineM1{})
if maxTSPersistent > 0 && maxTSPersistent > startTS {
acTS = maxTSPersistent + 60
}
if acTS == 0 {
minDataSourceTS := dataSource.getDataSourceMinTimestamp()
// No Deals to handle if minDataSourceTS == -1, anchorEndTS <-- startTS
if minDataSourceTS == -1 {
return startTS, 0, nil, errors.New("No Deals to handled, return without converting job.")
} else {
acTS = minDataSourceTS
}
}
anchorTime := time.Unix(acTS, 0).UTC()
anchorStartTime := time.Date(
anchorTime.Year(), anchorTime.Month(), anchorTime.Day(), anchorTime.Hour(), anchorTime.Minute(), 0, 0, time.UTC)
// 2. Collect product's kline by deals
productKlines := map[string][]types.KlineM1{}
nextTime := anchorStartTime.Add(time.Minute)
nextTimeStamp := nextTime.Unix()
for nextTimeStamp <= endTS {
sql := dataSource.getMaxMinSumByGroupSQL(anchorStartTime.Unix(), nextTime.Unix())
orm.Debug(fmt.Sprintf("CreateKline1M sql:%s", sql))
rows, err := orm.db.Raw(sql).Rows()
if rows != nil && err == nil {
for rows.Next() {
var product string
var quantity, high, low float64
var cnt int
if err = rows.Scan(&product, &quantity, &high, &low, &cnt); err != nil {
orm.Error(fmt.Sprintf("CreateKline1M failed to execute scan result, error:%s sql:%s", err.Error(), sql))
}
if cnt > 0 {
openPrice, closePrice := dataSource.getOpenClosePrice(anchorStartTime.Unix(), nextTime.Unix(), product)
b := types.BaseKline{
Product: product, High: high, Low: low, Volume: quantity,
Timestamp: anchorStartTime.Unix(), Open: openPrice, Close: closePrice}
k1min := types.NewKlineM1(&b)
klines := productKlines[product]
if klines == nil {
klines = []types.KlineM1{*k1min}
} else {
klines = append(klines, *k1min)
}
productKlines[product] = klines
}
}
if err = rows.Close(); err != nil {
orm.Error(fmt.Sprintf("CreateKline1M failed to execute close rows, error:%s", err.Error()))
}
}
anchorStartTime = nextTime
nextTime = anchorStartTime.Add(time.Minute)
nextTimeStamp = nextTime.Unix()
}
// 3. Batch insert into Kline1Min
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
for _, klines := range productKlines {
for _, kline := range klines {
// TODO: it should be a replacement here.
ret := tx.Create(&kline)
if ret.Error != nil {
orm.Error(fmt.Sprintf("CreateKline1M failed to create kline Error: %+v, kline: %s", ret.Error, kline.PrettyTimeString()))
} else {
orm.Debug(fmt.Sprintf("CreateKline1M success to create in %s, %s %s", kline.GetTableName(), types.TimeString(kline.Timestamp), kline.PrettyTimeString()))
}
}
}
tx.Commit()
anchorEndTS = anchorStartTime.Unix()
orm.Debug(fmt.Sprintf("CreateKline1M return klinesMap: %+v", productKlines))
return anchorEndTS, len(productKlines), productKlines, nil
}
func (orm *ORM) deleteKlinesBefore(unixTS int64, kline interface{}) (err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
r := tx.Delete(kline, " Timestamp < ? ", unixTS)
if r.Error == nil {
tx.Commit()
} else {
return r.Error
}
return nil
}
func (orm *ORM) deleteKlinesAfter(unixTS int64, product string, kline interface{}) (err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
r := tx.Delete(kline, " Timestamp >= ? and Product = ?", unixTS, product)
if r.Error == nil {
tx.Commit()
} else {
return r.Error
}
return nil
}
// DeleteKlineBefore delete from kline
func (orm *ORM) DeleteKlineBefore(unixTS int64, kline interface{}) error {
return orm.deleteKlinesBefore(unixTS, kline)
}
func (orm *ORM) deleteKlineM1Before(unixTS int64) error {
return orm.DeleteKlineBefore(unixTS, &types.KlineM1{})
}
func (orm *ORM) getAllUpdatedProducts(anchorStartTS, anchorEndTS int64) ([]string, error) {
midTS := anchorEndTS - int64(16*60)
p1, e1 := orm.getAllUpdatedProductsFromTable(anchorStartTS, midTS, "kline_m15")
if e1 != nil {
return nil, e1
}
p2, e2 := orm.getAllUpdatedProductsFromTable(midTS, anchorEndTS, "match_results")
if e2 != nil {
return nil, e1
}
tmpMap := map[string]bool{}
for _, p := range p1 {
tmpMap[p] = true
}
for _, p := range p2 {
tmpMap[p] = true
}
mergedKline := []string{}
for k := range tmpMap {
mergedKline = append(mergedKline, k)
}
return mergedKline, nil
}
func (orm *ORM) getAllUpdatedProductsFromTable(anchorStartTS, anchorEndTS int64, tb string) ([]string, error) {
sql := fmt.Sprintf("select distinct(Product) from %s where Timestamp >= %d and Timestamp < %d",
tb, anchorStartTS, anchorEndTS)
rows, err := orm.db.Raw(sql).Rows()
if err == nil {
products := []string{}
for rows.Next() {
var product string
if err := rows.Scan(&product); err != nil {
orm.Error("failed to execute scan result, error:" + err.Error())
}
products = append(products, product)
}
if err = rows.Close(); err != nil {
orm.Error("failed to execute close rows, error:" + err.Error())
}
return products, nil
} else {
return nil, err
}
}
// nolint
func (orm *ORM) GetLatestKlinesByProduct(product string, limit int, anchorTS int64, klines interface{}) error {
var r *gorm.DB
if anchorTS > 0 {
r = orm.db.Where("Timestamp < ? and Product = ?", anchorTS, product).Order("Timestamp desc").Limit(limit).Find(klines)
} else {
r = orm.db.Where("Product = ?", product).Order("Timestamp desc").Limit(limit).Find(klines)
}
return r.Error
}
func (orm *ORM) getKlinesByTimeRange(product string, startTS, endTS int64, klines interface{}) error {
r := orm.db.Where("Timestamp >= ? and Timestamp < ? and Product = ?", startTS, endTS, product).
Order("Timestamp desc").Find(klines)
return r.Error
}
func (orm *ORM) getLatestKlineM1ByProduct(product string, limit int) (*[]types.KlineM1, error) {
klines := []types.KlineM1{}
if err := orm.GetLatestKlinesByProduct(product, limit, -1, &klines); err != nil {
return nil, err
} else {
return &klines, nil
}
}
// MergeKlineM1 merge KlineM1 data to KlineM*
func (orm *ORM) MergeKlineM1(startTS, endTS int64, destKline types.IKline) (
anchorEndTS int64, newKlineTypeCnt int, newKlines map[string][]interface{}, err error) {
orm.singleEntryLock.Lock()
defer orm.singleEntryLock.Unlock()
klineM1 := types.MustNewKlineFactory("kline_m1", nil)
// 0. destKline should not be KlineM1 & endTS should be greater than startTS
if destKline.GetFreqInSecond() <= klineM1.(types.IKline).GetFreqInSecond() {
return startTS, 0, nil, fmt.Errorf("destKline's updating Freq #%d# should be greater than 60", destKline.GetFreqInSecond())
}
if endTS <= startTS {
return -1, 0, nil, fmt.Errorf("EndTimestamp %d <= StartTimestamp %d, somewhere goes wrong", endTS, startTS)
}
// 1. Get anchor start time.
acTS := startTS
maxTSPersistent := orm.getMergingKlineTimestamp(destKline.GetTableName(), startTS)
if maxTSPersistent > 0 {
acTS = maxTSPersistent
}
if acTS == 0 {
minTS := orm.getKlineMinTimestamp(klineM1.(types.IKline))
// No Deals to handle if minDealTS == -1, anchorEndTS <-- startTS
if minTS == -1 {
return startTS, 0, nil, errors.New("DestKline:" + destKline.GetTableName() + ". No KlineM1 to handled, return without converting job.")
} else {
acTS = minTS
}
}
var anchorStartTime time.Time
if maxTSPersistent > 0 {
anchorTime := time.Unix(acTS, 0).UTC()
anchorStartTime = time.Date(
anchorTime.Year(), anchorTime.Month(), anchorTime.Day(), anchorTime.Hour(), anchorTime.Minute(), anchorTime.Second(), 0, time.UTC)
} else {
anchorStartTime = time.Unix(destKline.GetAnchorTimeTS(acTS), 0).UTC()
}
// 2. Get anchor end time.
anchorEndTime := endTS
orm.Debug(fmt.Sprintf("[backend] MergeKlineM1 KlinesMX-#%d# [%s, %s]",
destKline.GetFreqInSecond(), types.TimeString(anchorStartTime.Unix()), types.TimeString(anchorEndTime)))
// 3. Collect product's kline by deals
productKlines := map[string][]interface{}{}
interval := time.Duration(int(time.Second) * destKline.GetFreqInSecond())
nextTime := anchorStartTime.Add(interval)
for nextTime.Unix() <= anchorEndTime {
sql := fmt.Sprintf("select %d, product, sum(volume) as volume, max(high) as high, min(low) as low, count(*) as cnt from %s "+
"where Timestamp >= %d and Timestamp < %d group by product", anchorStartTime.Unix(), klineM1.(types.IKline).GetTableName(), anchorStartTime.Unix(), nextTime.Unix())
orm.Debug(fmt.Sprintf("[backend] MergeKlineM1 KlinesMX-#%d# sql=%s",
destKline.GetFreqInSecond(), sql))
rows, err := orm.db.Raw(sql).Rows()
if rows != nil && err == nil {
for rows.Next() {
var product string
var quantity, high, low float64
var cnt int
var ts int64
if err = rows.Scan(&ts, &product, &quantity, &high, &low, &cnt); err != nil {
orm.Error("failed to execute scan result, error:" + err.Error())
}
if cnt > 0 {
openKline := types.MustNewKlineFactory(klineM1.(types.IKline).GetTableName(), nil)
closeKline := types.MustNewKlineFactory(klineM1.(types.IKline).GetTableName(), nil)
err = orm.getOpenCloseKline(anchorStartTime.Unix(), nextTime.Unix(), product, openKline, closeKline)
if err != nil {
orm.Error(fmt.Sprintf("failed to get open and close kline, error: %s", err.Error()))
}
b := types.BaseKline{
Product: product, High: high, Low: low, Volume: quantity, Timestamp: anchorStartTime.Unix(),
Open: openKline.(types.IKline).GetOpen(), Close: closeKline.(types.IKline).GetClose()}
newDestK := types.MustNewKlineFactory(destKline.GetTableName(), &b)
klines := productKlines[product]
if klines == nil {
klines = []interface{}{newDestK}
} else {
klines = append(klines, newDestK)
}
productKlines[product] = klines
}
}
if err = rows.Close(); err != nil {
orm.Error("failed to execute close rows, error:" + err.Error())
}
}
anchorStartTime = nextTime
nextTime = anchorStartTime.Add(interval)
}
// 4. Batch insert into Kline1Min
tx := orm.db.Begin()
defer orm.deferRollbackTx(tx, err)
for _, klines := range productKlines {
for _, kline := range klines {
ret := tx.Delete(kline).Create(kline)
if ret.Error != nil {
orm.Error(fmt.Sprintf("Error: %+v, kline: %s", ret.Error, kline.(types.IKline).PrettyTimeString()))
} else {
orm.Debug(fmt.Sprintf("%s %s", types.TimeString(kline.(types.IKline).GetTimestamp()), kline.(types.IKline).PrettyTimeString()))
}
}
}
tx.Commit()
anchorEndTS = anchorStartTime.Unix()
return anchorEndTS, len(productKlines), productKlines, nil
}
// RefreshTickers Latest 24H KlineM1 to Ticker
func (orm *ORM) RefreshTickers(startTS, endTS int64, productList []string) (m map[string]*types.Ticker, err error) {
orm.Debug(fmt.Sprintf("[backend] entering RefreshTickers, expected TickerTimeRange: [%d, %d)=[%s, %s), expectedProducts: %+v",
startTS, endTS, types.TimeString(startTS), types.TimeString(endTS), productList))
orm.bufferLock.Lock()
defer orm.bufferLock.Unlock()
// 1. Get updated product by Deals & KlineM15 in latest 120 seconds
km1 := types.MustNewKlineFactory("kline_m1", nil)
km15 := types.MustNewKlineFactory("kline_m15", nil)
if len(productList) == 0 {
productList, err = orm.getAllUpdatedProducts(endTS-types.SecondsInADay*14, endTS)
if err != nil {
return nil, err
}
}
if len(productList) == 0 {
return nil, nil
}
// 2. Update Buffer.
// 2.1 For each product, get latest [anchorKM15TS-types.SECONDS_IN_A_DAY, anchorKM15TS) KlineM15 list
anchorKM15TS := km15.(types.IKline).GetAnchorTimeTS(endTS-types.KlinexGoRoutineWaitInSecond) - 60*15
if anchorKM15TS != orm.lastK15Timestamp {
orm.lastK15Timestamp = anchorKM15TS
orm.klineM15sBuffer = map[string][]types.KlineM15{}
}
finalStartTS := km15.(types.IKline).GetAnchorTimeTS(endTS) - types.SecondsInADay
for _, p := range productList {
existsKM15 := orm.klineM15sBuffer[p]
if len(existsKM15) > 0 {
continue
}
klineM15s := []types.KlineM15{}
if err = orm.getKlinesByTimeRange(p, finalStartTS, anchorKM15TS, &klineM15s); err != nil {
orm.Error(fmt.Sprintf("failed to get kline between %d and %d, error: %s", finalStartTS, anchorKM15TS, err.Error()))
}
if len(klineM15s) > 0 {
orm.klineM15sBuffer[p] = klineM15s
}
}
// 2.2 For each product, get latest [anchorKM15TS, anchorKM1TS) KlineM1 list
anchorKM1TS := (km1).(types.IKline).GetAnchorTimeTS(endTS-types.Kline1GoRoutineWaitInSecond) - 60
if anchorKM1TS != orm.lastK1Timestamp {
orm.lastK1Timestamp = anchorKM1TS
orm.klineM1sBuffer = map[string][]types.KlineM1{}
}
for _, p := range productList {
existsKM1 := orm.klineM1sBuffer[p]
if len(existsKM1) > 0 {
continue
}
klineM1s := []types.KlineM1{}
if anchorKM1TS < anchorKM15TS {
anchorKM1TS = anchorKM15TS
}
if err = orm.getKlinesByTimeRange(p, anchorKM15TS, anchorKM1TS, &klineM1s); err != nil {
orm.Error(fmt.Sprintf("failed to get kline between %d and %d, error: %s", finalStartTS, anchorKM15TS, err.Error()))
}
if len(klineM1s) > 0 {
orm.klineM1sBuffer[p] = klineM1s
}
}
// 2.3 For each product, get latest [anchorKM1TS, endTS) MatchResult list
matchResultMap := make(map[string][]types.MatchResult)
for _, product := range productList {
matchResults, err := orm.getMatchResultsByTimeRange(product, anchorKM1TS, endTS)
if err != nil {
orm.Error(fmt.Sprintf("failed to GetMatchResultsByTimeRange, error: %s", err.Error()))
continue
}
if len(matchResults) > 0 {
matchResultMap[product] = matchResults
}
}
// 3. For each updated product, generate new ticker by KlineM15 & KlineM1 & Deals in 24 Hours
orm.Debug(fmt.Sprintf("RefreshTickers: Cache KlineM15[%s, %s), KlineM1[%s, %s), Deals[%s, %s)",
types.TimeString(finalStartTS), types.TimeString(anchorKM15TS), types.TimeString(anchorKM15TS),
types.TimeString(anchorKM1TS), types.TimeString(anchorKM1TS), types.TimeString(endTS)))
orm.Debug(fmt.Sprintf("KlineM15: %+v\n KlineM1: %+v\n MatchResults: %+v\n", orm.klineM15sBuffer,
orm.klineM1sBuffer, matchResultMap))
tickerMap := map[string]*types.Ticker{}
orm.Debug(fmt.Sprintf("RefreshTickers's final productList %+v", productList))
for _, p := range productList {
klinesM1 := orm.klineM1sBuffer[p]
klinesM15 := orm.klineM15sBuffer[p]
iklines := types.IKlinesDsc{}
for idx := range klinesM1[:] {
iklines = append(iklines, &klinesM1[idx])
}
for idx := range klinesM15[:] {
iklines = append(iklines, &klinesM15[idx])
}
// [X] 3.1 No klinesM1 & klinesM15 found, continue
// FLT. 20190411. Go ahead even if there's no klines.
// 3.2 Do iklines sort desc by timestamp.
allVolume, lowest, highest := 0.0, 0.0, 0.0
matchResults := matchResultMap[p]
if len(iklines) > 0 {
sort.Sort(iklines)
allVolume, lowest, highest = 0.0, iklines[0].GetLow(), iklines[0].GetHigh()
for _, k := range iklines {
orm.Debug(fmt.Sprintf("RefreshTickers, Handled Kline(%s): %s", k.GetTableName(), k.PrettyTimeString()))
allVolume += k.GetVolume()
if k.GetHigh() > highest {
highest = k.GetHigh()
}
if k.GetLow() < lowest {
lowest = k.GetLow()
}
}
} else {
if len(matchResults) > 0 {
allVolume, lowest, highest = 0.0, matchResults[0].Price, matchResults[0].Price
}
}
for _, match := range matchResults {
allVolume += match.Quantity
if match.Price > highest {
highest = match.Price
}
if match.Price < lowest {
lowest = match.Price
}
}