-
Notifications
You must be signed in to change notification settings - Fork 126
/
tradesBlockService.go
375 lines (344 loc) · 11.8 KB
/
tradesBlockService.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
package tradesBlockService
import (
"errors"
"math"
"sort"
"strconv"
"sync"
"time"
"github.com/cnf/structhash"
"github.com/diadata-org/diadata/pkg/dia"
models "github.com/diadata-org/diadata/pkg/model"
"github.com/diadata-org/diadata/pkg/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/sirupsen/logrus"
)
type nothing struct{}
func init() {
log = logrus.New()
batchTimeString = utils.Getenv("BATCH_TIME_SECONDS", "30")
var err error
batchTimeSeconds, err = strconv.Atoi(batchTimeString)
if err != nil {
log.Error("parse batchTimeString: ", err)
}
}
var (
stablecoins = map[string]interface{}{
"USDC": "",
"USDT": "",
"TUSD": "",
"DAI": "",
"PAX": "",
"BUSD": "",
}
tol = float64(0.04)
log *logrus.Logger
batchTimeString string
batchTimeSeconds int
)
type TradesBlockService struct {
shutdown chan nothing
shutdownDone chan nothing
chanTrades chan *dia.Trade
chanTradesBlock chan *dia.TradesBlock
errorLock sync.RWMutex
error error
closed bool
started bool
BlockDuration int64
currentBlock *dia.TradesBlock
priceCache map[dia.Asset]float64
datastore models.Datastore
historical bool
writeMeasurement string
batchTicker *time.Ticker
}
func NewTradesBlockService(datastore models.Datastore, blockDuration int64, historical bool) *TradesBlockService {
s := &TradesBlockService{
shutdown: make(chan nothing),
shutdownDone: make(chan nothing),
chanTrades: make(chan *dia.Trade),
chanTradesBlock: make(chan *dia.TradesBlock),
error: nil,
started: false,
currentBlock: nil,
BlockDuration: blockDuration,
priceCache: make(map[dia.Asset]float64),
datastore: datastore,
historical: historical,
batchTicker: time.NewTicker(time.Duration(batchTimeSeconds) * time.Second),
}
if historical {
s.writeMeasurement = utils.Getenv("INFLUX_MEASUREMENT_WRITE", "tradesTmp")
}
log.Info("write measurement: ", s.writeMeasurement)
log.Info("historical: ", s.historical)
log.Info("batch ticker time: ", batchTimeSeconds)
go s.mainLoop()
return s
}
// runs in a goroutine until s is closed
func (s *TradesBlockService) mainLoop() {
for {
select {
case <-s.shutdown:
log.Println("TradesBlockService shutting down")
s.cleanup(nil)
return
case t := <-s.chanTrades:
s.process(*t)
case <-s.batchTicker.C:
err := s.datastore.Flush()
if err != nil {
log.Error("flush influx batch: ", err)
}
}
}
}
func (s *TradesBlockService) process(t dia.Trade) {
var verifiedTrade bool
// Price estimation can only be done for verified pairs.
// Trades with unverified pairs are still saved, but not sent to the filtersBlockService.
if t.VerifiedPair {
if t.BaseToken.Address == "840" && t.BaseToken.Blockchain == dia.FIAT {
// All prices are measured in US-Dollar, so just price for base token == USD
t.EstimatedUSDPrice = t.Price
verifiedTrade = true
} else {
// Get price of base token.
// This can be switched to GetAssetPriceUSD(asset, timestamp) when switching to historical scrapers.
// val, err := s.datastore.GetAssetPriceUSDCache(t.BaseToken)
var quotation *models.AssetQuotation
var price float64
var ok bool
var err error
if !s.historical {
// Get latest price from cache.
// price, err = s.datastore.GetAssetPriceUSDLatest(t.BaseToken)
basetoken := t.BaseToken
// Tmp solution for prices on Solana, Metis, Fantom and Telos:------
if basetoken.Blockchain == dia.SOLANA && t.Source == dia.SerumExchange && basetoken.Address == "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" {
basetoken = dia.Asset{
Symbol: "USDC",
Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
Blockchain: dia.ETHEREUM,
}
}
if basetoken.Blockchain == dia.METIS && (t.Source == dia.NetswapExchange || t.Source == dia.TethysExchange || t.Source == dia.HermesExchange) && basetoken.Address == "0xEA32A96608495e54156Ae48931A7c20f0dcc1a21" {
basetoken = dia.Asset{
Symbol: "USDC",
Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
Blockchain: dia.ETHEREUM,
}
}
if basetoken.Blockchain == dia.FANTOM && (t.Source == dia.SpookyswapExchange || t.Source == dia.SpiritswapExchange || t.Source == dia.BeetsExchange) {
if basetoken.Address == "0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83" {
basetoken = dia.Asset{
Symbol: "FTM",
Address: "0x0000000000000000000000000000000000000000",
Blockchain: dia.FANTOM,
}
}
if basetoken.Address == "0x04068DA6C83AFCFA0e13ba15A6696662335D5B75" {
basetoken = dia.Asset{
Symbol: "USDC",
Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
Blockchain: dia.ETHEREUM,
}
}
}
if basetoken.Blockchain == dia.TELOS && (t.Source == dia.OmniDexExchange) && basetoken.Address == common.HexToAddress("0xd102ce6a4db07d247fcc28f366a623df0938ca9e").Hex() {
basetoken = dia.Asset{
Symbol: "TLOS",
Address: "0x0000000000000000000000000000000000000000",
Blockchain: dia.TELOS,
}
}
if basetoken.Blockchain == dia.EVMOS && t.Source == dia.DiffusionExchange && basetoken.Address == common.HexToAddress("0x51e44FfaD5C2B122C8b635671FCC8139dc636E82").Hex() {
basetoken = dia.Asset{
Symbol: "USDC",
Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
Blockchain: dia.ETHEREUM,
}
}
if t.Source == dia.StellaswapExchange && basetoken.Blockchain == dia.MOONBEAM && basetoken.Address == common.HexToAddress("0xAcc15dC74880C9944775448304B263D191c6077F").Hex() {
basetoken = dia.Asset{
Symbol: "GLMR",
Address: "0x0000000000000000000000000000000000000000",
Blockchain: dia.MOONBEAM,
}
}
if (t.Source == dia.UniswapExchangeV3Polygon || t.Source == dia.QuickswapExchange || t.Source == dia.SushiSwapExchangePolygon || t.Source == dia.DfynNetwork) && basetoken.Blockchain == dia.POLYGON {
if basetoken.Address == common.HexToAddress("0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174").Hex() {
basetoken = dia.Asset{
Symbol: "USDC",
Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
Blockchain: dia.ETHEREUM,
}
}
if basetoken.Address == common.HexToAddress("0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270").Hex() {
basetoken = dia.Asset{
Symbol: "MATIC",
Address: "0x0000000000000000000000000000000000001010",
Blockchain: dia.POLYGON,
}
}
}
if t.Source == dia.ArthswapExchange && basetoken.Blockchain == dia.ASTAR {
if basetoken.Address == common.HexToAddress("0x6a2d262D56735DbA19Dd70682B39F6bE9a931D98").Hex() {
basetoken = dia.Asset{
Symbol: "USDC",
Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
Blockchain: dia.ETHEREUM,
}
}
if basetoken.Address == common.HexToAddress("0xAeaaf0e2c81Af264101B9129C00F4440cCF0F720").Hex() {
basetoken = dia.Asset{
Symbol: "ASTR",
Address: "0x0000000000000000000000000000000000000000",
Blockchain: dia.ASTAR,
}
}
}
if basetoken.Blockchain == dia.AVALANCHE && (t.Source == dia.TraderJoeExchange || t.Source == dia.PangolinExchange) {
if basetoken.Address == common.HexToAddress("0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7").Hex() {
basetoken = dia.Asset{
Symbol: "AVAX",
Address: "0x0000000000000000000000000000000000000000",
Blockchain: dia.AVALANCHE,
}
}
}
if _, ok = s.priceCache[basetoken]; ok {
price = s.priceCache[basetoken]
} else {
quotation, err = s.datastore.GetAssetQuotationCache(basetoken)
price = quotation.Price
s.priceCache[basetoken] = price
log.Infof("quotation for %s from redis cache: %v", basetoken.Symbol, price)
}
} else {
// Look for historic price of base token at trade time.
if _, ok = s.priceCache[t.BaseToken]; ok {
price = s.priceCache[t.BaseToken]
} else {
price, err = s.datastore.GetAssetPriceUSD(t.BaseToken, t.Time)
s.priceCache[t.BaseToken] = price
if t.BaseToken.Address == "0x0000000000000000000000000000000000000000" {
if t.BaseToken.Blockchain == "Bitcoin" {
log.Infof("quotation for BTC from influx: %v", price)
}
if t.BaseToken.Blockchain == "Ethereum" {
log.Infof("quotation for ETH from influx: %v", price)
}
}
}
}
if err != nil {
log.Errorf("Can't find quotation for base token in trade %s: %v.\n Basetoken address -- blockchain: %s --- %s",
t.Pair,
err,
t.BaseToken.Address,
t.BaseToken.Blockchain,
)
} else {
if price > 0.0 {
t.EstimatedUSDPrice = t.Price * price
if t.EstimatedUSDPrice > 0 {
verifiedTrade = true
}
}
}
}
}
// // If estimated price for stablecoin diverges too much ignore trade
if _, ok := stablecoins[t.Symbol]; ok {
if math.Abs(t.EstimatedUSDPrice-1) > tol {
log.Errorf("price for stablecoin %s diverges by %v", t.Symbol, math.Abs(t.EstimatedUSDPrice-1))
verifiedTrade = false
}
}
// Comment Philipp: We could make another check here. Store CG and/or CMC quotation in redis cache
// and compare with estimatedUSDPrice. If deviation is too large ignore trade.
var err error
if !s.historical {
err = s.datastore.SaveTradeInflux(&t)
if err != nil {
log.Error(err)
}
} else {
err = s.datastore.SaveTradeInfluxToTable(&t, s.writeMeasurement)
if err != nil {
log.Error(err)
}
}
if s.currentBlock != nil && s.currentBlock.TradesBlockData.BeginTime.After(t.Time) {
log.Debugf("ignore trade should be in previous block %v", t)
verifiedTrade = false
}
// Only verified trades of verified pairs with nonzero price are added to the tradesBlock
if verifiedTrade && t.EstimatedUSDPrice > 0 {
if s.currentBlock == nil || s.currentBlock.TradesBlockData.EndTime.Before(t.Time) {
if s.currentBlock != nil {
s.finaliseCurrentBlock()
s.priceCache = make(map[dia.Asset]float64)
}
b := &dia.TradesBlock{
TradesBlockData: dia.TradesBlockData{
Trades: []dia.Trade{},
EndTime: time.Unix((t.Time.Unix()/s.BlockDuration)*s.BlockDuration+s.BlockDuration, 0),
BeginTime: time.Unix((t.Time.Unix()/s.BlockDuration)*s.BlockDuration, 0),
},
}
if s.currentBlock != nil {
log.Info("created new block beginTime:", b.TradesBlockData.BeginTime, "previous block nb trades:", len(s.currentBlock.TradesBlockData.Trades))
}
s.currentBlock = b
err = s.datastore.Flush()
if err != nil {
log.Error(err)
}
}
s.currentBlock.TradesBlockData.Trades = append(s.currentBlock.TradesBlockData.Trades, t)
} else {
log.Debugf("ignore trade %v", t)
}
}
func (s *TradesBlockService) finaliseCurrentBlock() {
sort.Slice(s.currentBlock.TradesBlockData.Trades, func(i, j int) bool {
return s.currentBlock.TradesBlockData.Trades[i].Time.Before(s.currentBlock.TradesBlockData.Trades[j].Time)
})
hash, err := structhash.Hash(s.currentBlock.TradesBlockData, 1)
if err != nil {
log.Printf("error on hash")
hash = "hashError"
}
s.currentBlock.BlockHash = hash
s.currentBlock.TradesBlockData.TradesNumber = len(s.currentBlock.TradesBlockData.Trades)
s.chanTradesBlock <- s.currentBlock
}
func (s *TradesBlockService) ProcessTrade(trade *dia.Trade) {
s.chanTrades <- trade
}
func (s *TradesBlockService) Close() error {
if s.closed {
return errors.New("TradesBlockService: Already closed")
}
close(s.shutdown)
<-s.shutdownDone
return s.error
}
// must only be called from mainLoop
func (s *TradesBlockService) cleanup(err error) {
s.errorLock.Lock()
defer s.errorLock.Unlock()
if err != nil {
s.error = err
}
s.closed = true
close(s.shutdownDone) // signal that shutdown is complete
}
func (s *TradesBlockService) Channel() chan *dia.TradesBlock {
return s.chanTradesBlock
}