-
Notifications
You must be signed in to change notification settings - Fork 181
/
market_keeper.go
97 lines (81 loc) · 2.32 KB
/
market_keeper.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
package stream
import (
"encoding/json"
"fmt"
"github.com/okex/exchain/x/backend/types"
"sort"
"strconv"
"strings"
"time"
"github.com/tendermint/tendermint/libs/log"
"github.com/okex/exchain/x/backend"
"github.com/okex/exchain/x/stream/pushservice/conn"
)
type MarketKeeper backend.MarketKeeper
type BaseMarketKeeper struct {
}
type RedisMarketKeeper struct {
*BaseMarketKeeper
client *conn.Client
logger log.Logger
}
func NewRedisMarketKeeper(client *conn.Client, logger log.Logger) *RedisMarketKeeper {
k := RedisMarketKeeper{}
k.BaseMarketKeeper = &BaseMarketKeeper{}
k.client = client
k.logger = logger
return &k
}
func (k *RedisMarketKeeper) GetKlineByProductID(productID uint64, granularity, size int) ([][]string, error) {
key := fmt.Sprintf("%d_%d", productID, granularity)
k.logger.Debug("GetKlineByInstrument", "productID", productID, "key", key)
r, err := k.client.HGetAll(key)
k.logger.Debug("GetKlineByInstrument", "values", r, "error", err)
klines := make([][]string, 0, len(r))
if len(r) == 0 {
return klines, nil
}
fieldList := make([]string, 0, len(r))
for k := range r {
fieldList = append(fieldList, k)
}
// sorts fieldList in increasing order.
sort.Strings(fieldList)
for _, field := range fieldList {
timeInt, err := strconv.ParseInt(field, 10, 64)
if err != nil {
return nil, types.ErrGetInvalidateGranularity(err.Error(), key, field)
}
values := strings.Split(r[field], "|")
// timeInt is millisecond
values = append([]string{time.Unix(timeInt/1000, 0).UTC().Format("2006-01-02T15:04:05.000Z")}, values...)
klines = append(klines, values)
}
end := len(klines)
if end > size {
return klines[end-size : end], nil
}
return klines, nil
}
func (k *RedisMarketKeeper) GetTickerByProducts(products []string) ([]map[string]string, error) {
var tickers []map[string]string
k.logger.Debug("GetTickerByInstruments", "instruments", products)
for _, product := range products {
key := product
k.logger.Debug("GetTickerByInstruments", "key", key)
r, err := k.client.Get(key)
if err != nil {
return tickers, err
}
ticker := map[string]string{}
if len(r) > 0 {
err := json.Unmarshal([]byte(r), &ticker)
if err == nil {
tickers = append(tickers, ticker)
} else {
return tickers, types.ErrGetInvalidTickerByProducts(key)
}
}
}
return tickers, nil
}