-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
282 lines (251 loc) · 6.79 KB
/
main.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
// This package implements the sentinel-tick application. Once launched, it
// request price information for the configured pairs from the configured
// exchanges.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"sync"
"time"
"github.com/blang/semver/v4"
"github.com/filecoin-project/sentinel-tick/quotetracker"
"github.com/go-pg/pg/v10"
"github.com/urfave/cli/v2"
)
// to be set at build time.
var tag string
var version string = "unset"
func init() {
if v, err := semver.ParseTolerant(tag); err == nil {
version = v.String()
}
}
func main() {
app := &cli.App{
Name: "tick",
Usage: "Filecoin Price Monitoring Utility",
Version: version,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "db",
EnvVars: []string{"SENTINEL_TICK_DB"},
Value: "postgres://postgres:password@localhost:5432/postgres?sslmode=disable",
},
&cli.IntFlag{
Name: "db-pool-size",
EnvVars: []string{"SENTINEL_TICK_DB_POOL_SIZE"},
Value: 75,
},
&cli.StringFlag{
Name: "pairs",
Usage: "Comma-separated list of pairs",
EnvVars: []string{"SENTINEL_TICK_PAIRS"},
Value: "FIL-USD",
},
&cli.DurationFlag{
Name: "timeout",
Usage: "Timeout before aborting a request to a provider",
EnvVars: []string{"SENTINEL_TICK_TIMEOUT"},
Value: 10 * time.Second,
},
&cli.StringFlag{
Name: "metrics",
Usage: "Prometheus metrics listening endpoint",
EnvVars: []string{"SENTINEL_TICK_METRICS"},
Value: "127.0.0.1:2111",
},
&cli.IntFlag{
Name: "coinmarketcap",
Aliases: []string{"cmc"},
Usage: "Minimum interval between requests to coinmarketcap. Default: source disabled.",
Value: 0,
EnvVars: []string{"SENTINEL_TICK_COINMARKETCAP"},
},
&cli.StringFlag{
Name: "coinmarketcap-token",
Aliases: []string{"cmc-token"},
Usage: "API token for CoinMarketCap.com",
EnvVars: []string{"SENTINEL_TICK_COINMARKETCAP_TOKEN"},
},
&cli.BoolFlag{
Name: "kraken",
Usage: "Enable kraken",
EnvVars: []string{"SENTINEL_TICK_KRAKEN"},
Value: true,
},
&cli.BoolFlag{
Name: "coinbasepro",
Usage: "Enable Coinbase Pro",
EnvVars: []string{"SENTINEL_TICK_COINBASEPRO"},
Value: true,
},
&cli.BoolFlag{
Name: "coinlistpro",
Usage: "Enable Coinlist Pro",
EnvVars: []string{"SENTINEL_TICK_COINLISTPRO"},
Value: true,
},
&cli.BoolFlag{
Name: "huobi",
Usage: "Enable huobi",
EnvVars: []string{"SENTINEL_TICK_HUOBI"},
Value: true,
},
&cli.BoolFlag{
Name: "gemini",
Usage: "Enable gemini",
EnvVars: []string{"SENTINEL_TICK_GEMINI"},
Value: true,
},
},
Action: func(cctx *cli.Context) error {
enableMetrics(cctx)
db, err := setupDB(
cctx.Context,
cctx.String("db"),
cctx.Int("db-pool-size"),
"sentinel-tick",
)
if err != nil {
return err
}
defer teardownDB(cctx.Context, db)
if err := createSchema(db); err != nil {
return err
}
exchanges, err := setupExchanges(cctx)
if err != nil {
return err
}
pairs, err := setupPairs(cctx)
if err != nil {
return err
}
for {
select {
case <-cctx.Context.Done():
return nil
default:
}
err := fetchQuotes(cctx, db, exchanges, pairs)
if err != nil {
return err
}
time.Sleep(30 * time.Second)
}
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
// Parse flags related to exchanges and initialize them.
func setupExchanges(cctx *cli.Context) ([]quotetracker.Exchange, error) {
var exchanges []quotetracker.Exchange
if cmkInterval := cctx.Int("cmc"); cmkInterval > 0 {
cmc := "etracker.CoinMarketCap{
Token: cctx.String("cmc-token"),
TTL: time.Second * time.Duration(cmkInterval),
}
exchanges = append(exchanges, cmc)
fmt.Println("Initialized", cmc)
}
if krakenEnabled := cctx.Bool("kraken"); krakenEnabled {
kraken := "etracker.Kraken{}
exchanges = append(exchanges, kraken)
fmt.Println("Initialized", kraken)
}
if coinbaseproEnabled := cctx.Bool("coinbasepro"); coinbaseproEnabled {
cbp := "etracker.Coinbasepro{}
exchanges = append(exchanges, cbp)
fmt.Println("Initialized", cbp)
}
if coinlistproEnabled := cctx.Bool("coinlistpro"); coinlistproEnabled {
clp := "etracker.Coinlistpro{}
exchanges = append(exchanges, clp)
fmt.Println("Initialized", clp)
}
if huobiEnabled := cctx.Bool("huobi"); huobiEnabled {
h := "etracker.Huobi{}
exchanges = append(exchanges, h)
fmt.Println("Initialized", h)
}
if geminiEnabled := cctx.Bool("huobi"); geminiEnabled {
g := "etracker.Gemini{}
exchanges = append(exchanges, g)
fmt.Println("Initialized", g)
}
return exchanges, nil
}
// Parse the --pairs flag.
func setupPairs(cctx *cli.Context) ([]quotetracker.Pair, error) {
pairsArr := strings.Split(cctx.String("pairs"), ",")
pairs := make([]quotetracker.Pair, 0, len(pairsArr))
for _, pairStr := range pairsArr {
pairSymbols := strings.Split(pairStr, "-")
if len(pairSymbols) != 2 {
return nil, fmt.Errorf("wrong pair: %s", pairStr)
}
sell, err := quotetracker.CurrencyFromSymbol(pairSymbols[0])
if err != nil {
return nil, fmt.Errorf("%s: %w", pairSymbols[0], err)
}
buy, err := quotetracker.CurrencyFromSymbol(pairSymbols[1])
if err != nil {
return nil, fmt.Errorf("%s: %w", pairSymbols[1], err)
}
pair := quotetracker.Pair{Sell: sell, Buy: buy}
pairs = append(pairs, pair)
fmt.Println("Tracking", pair.String())
}
return pairs, nil
}
// For each exchange, for each given pair, fetch quotes and add them to the DB (in a single transaction).
func fetchQuotes(cctx *cli.Context, db *pg.DB, exchanges []quotetracker.Exchange, pairs []quotetracker.Pair) error {
quotes := make(Quotes, 0, len(exchanges))
quotesCh := make(chan Quote, len(exchanges)*len(pairs))
epoch := filEpoch(time.Now())
// Ensure requests take no longer than some seconds.
ctx, cancel := context.WithTimeout(cctx.Context, cctx.Duration("timeout"))
defer cancel()
var wg sync.WaitGroup
fmt.Println("-- Epoch ", epoch)
for _, ex := range exchanges {
for _, pair := range pairs {
wg.Add(1)
go func(ex quotetracker.Exchange, pair quotetracker.Pair) {
defer wg.Done()
q, err := ex.Price(ctx, pair)
if err != nil {
log.Println(ex, err)
return
}
// Only add if the quote is for the epoch we wanted.
if filEpoch(q.Timestamp) == epoch {
fmt.Println(ex, q)
quotesCh <- NewQuote(
epoch,
ex.String(),
q,
)
}
}(ex, pair)
}
}
wg.Wait()
close(quotesCh)
for q := range quotesCh {
quotes = append(quotes, q)
}
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Close()
return db.RunInTransaction(cctx.Context, func(tx *pg.Tx) error {
return quotes.Persist(cctx.Context, tx)
})
}