-
Notifications
You must be signed in to change notification settings - Fork 126
/
STEXScraper.go
434 lines (387 loc) · 11.8 KB
/
STEXScraper.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
package scrapers
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"sync"
"time"
"github.com/diadata-org/diadata/pkg/dia"
"github.com/diadata-org/diadata/pkg/dia/helpers"
models "github.com/diadata-org/diadata/pkg/model"
utils "github.com/diadata-org/diadata/pkg/utils"
gosocketio "github.com/graarh/golang-socketio"
"github.com/graarh/golang-socketio/transport"
)
var _socketURL string = "socket.stex.com"
const (
apiBaseURL = "https://api3.stex.com/public"
)
type Trade struct {
Amount string `json:"amount"`
Amount2 float64 `json:"amount2"`
BuyOrderID int64 `json:"buy_order_id"`
CurrencyPairID int64 `json:"currency_pair_id"`
Date string `json:"date"`
ID int64 `json:"id"`
OrderType string `json:"order_type"`
Price string `json:"price"`
SellOrderID int64 `json:"sell_order_id"`
Socket interface{} `json:"socket"`
Timestamp int64 `json:"timestamp"`
}
type STEXTickerData struct {
Success bool `json:"success"`
Data []STEXAsset `json:"data"`
}
type STEXAsset struct {
ID int `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Active bool `json:"active"`
Delisted bool `json:"delisted"`
Precision int `json:"precision"`
}
type STEXTrade struct {
ID int `json:"id"`
Price *big.Float `json:"price"`
Amount *big.Float `json:"amount"`
Type string `json:"type"`
TimeStamp string `json:"timestamp"`
}
type Channel struct {
Channel string `json:"channel"`
}
type STEXScraper struct {
c *gosocketio.Client
// signaling channels for session initialization and finishing
shutdown chan nothing
shutdownDone chan nothing
// error handling; to read error or closed, first acquire read lock
// only cleanup method should hold write lock
errorLock sync.RWMutex
error error
closed bool
// used to keep track of trading pairs that we subscribed to
pairScrapers map[string]*STEXPairScraper
pairSymbolToID map[string]int
pairLastTimeStamp map[string]time.Time
pairIDToSymbol map[int]string
exchangeName string
chanTrades chan *dia.Trade
currencySymbolName map[string]string
isTickerMapInitialised bool
db *models.RelDB
}
// NewSTEXScraper returns a new STEXScraper for the given pair
func NewSTEXScraper(exchange dia.Exchange, scrape bool, relDB *models.RelDB) *STEXScraper {
s := &STEXScraper{
shutdown: make(chan nothing),
shutdownDone: make(chan nothing),
pairScrapers: make(map[string]*STEXPairScraper),
pairSymbolToID: make(map[string]int),
pairIDToSymbol: make(map[int]string),
pairLastTimeStamp: make(map[string]time.Time),
exchangeName: exchange.Name,
error: nil,
chanTrades: make(chan *dia.Trade),
currencySymbolName: make(map[string]string),
isTickerMapInitialised: false,
db: relDB,
}
c, err := gosocketio.Dial(
gosocketio.GetUrl(_socketURL, 443, true),
transport.GetDefaultWebsocketTransport())
if err != nil {
log.Printf("dial: %v", err)
}
s.c = c
if scrape {
go s.mainLoop()
}
return s
}
// // Reconnect to socketIO when the connection is down.
// func (s *STEXScraper) reconnectToSocketIO() {
// c, err := gosocketio.Dial(
// gosocketio.GetUrl(_socketURL, 443, true),
// transport.GetDefaultWebsocketTransport())
// if err != nil {
// log.Printf("dial: %v", err)
// } else {
// log.Info("successfully reconnected.")
// }
// s.c = c
// }
type StexTradeResponse struct {
SETXTrades []STEXTrade `json:"data"`
Success bool `json:"success"`
}
// runs in a goroutine until s is closed
func (s *STEXScraper) mainLoop() {
log.Info("mainLoop() waiting for pairs to be added...")
time.Sleep(10 * time.Second)
for {
s.scrapeTrades()
}
}
func (s *STEXScraper) scrapeTrades() {
var numRequests int
_, err := s.FetchAvailablePairs()
if err != nil {
log.Error(err)
}
for _, pairScraper := range s.pairScrapers {
if numRequests > 180 {
// API limit is 180 requests per min.
log.Info("sleep for a minute due to STEX API rate limit")
time.Sleep(1 * time.Minute)
numRequests = 0
} else {
s.scrapePair(pairScraper.pair)
numRequests++
}
}
// Sleep after getting trades for all pairs
log.Info("Scraped all pairs. Wait for next iteration.")
time.Sleep(4 * time.Second)
}
// scrapePair scrapes the @pair associated to s.pairScraper
func (s *STEXScraper) scrapePair(pair dia.ExchangePair) {
if (s.pairLastTimeStamp[pair.ForeignName] == time.Time{}) {
// Set last trade time to 10 mins ago for initial run
s.pairLastTimeStamp[pair.ForeignName] = time.Now().Add(-10 * time.Minute)
}
trades, _ := s.GetNewTrades(strconv.Itoa(s.pairSymbolToID[pair.ForeignName]), s.pairLastTimeStamp[pair.ForeignName])
for _, trade := range trades {
f64Price, _ := trade.Price.Float64()
f64Volume, _ := trade.Amount.Float64()
timeStamp, _ := strconv.ParseInt(trade.TimeStamp, 10, 32)
if trade.Type == "SELL" {
f64Volume = -f64Volume
}
exchangepair, err := s.db.GetExchangePairCache(s.exchangeName, pair.ForeignName)
if err != nil {
log.Error(err)
}
t := &dia.Trade{
Symbol: strings.Split(pair.Symbol, "-")[0],
Pair: pair.ForeignName,
Price: f64Price,
Volume: f64Volume,
Time: time.Unix(timeStamp, 0),
ForeignTradeID: strconv.Itoa(trade.ID),
Source: s.exchangeName,
VerifiedPair: exchangepair.Verified,
BaseToken: exchangepair.UnderlyingPair.BaseToken,
QuoteToken: exchangepair.UnderlyingPair.QuoteToken,
}
if exchangepair.Verified {
log.Infoln("Got verified trade", t)
}
s.chanTrades <- t
}
}
// FillSymbolData collects all available information on an asset traded on STEX
func (s *STEXScraper) FillSymbolData(symbol string) (dia.Asset, error) {
// Fetch Data
// if !s.isTickerMapInitialised {
// var (
// response STEXTickerData
// data []byte
// )
// data, _, err = utils.GetRequest("https://api3.stex.com/public/currencies")
// if err != nil {
// return
// }
// err = json.Unmarshal(data, &response)
// if err != nil {
// return
// }
// for _, asset := range response.Data {
// s.currencySymbolName[asset.Code] = asset.Name
// }
// s.isTickerMapInitialised = true
// }
// asset.Symbol = symbol
// asset.Name = s.currencySymbolName[symbol]
// fmt.Printf("name for symbol %s on exchange STEX: %s\n", symbol, asset.Name)
return dia.Asset{Symbol: symbol}, nil
}
// GetNewTrades fetches new trades from the STEX restAPI dating back until @fromTimestamp
func (s *STEXScraper) GetNewTrades(pairID string, fromTimestamp time.Time) ([]STEXTrade, error) {
var (
response StexTradeResponse
err error
bytes []byte
url string
)
if (fromTimestamp == time.Time{}) {
url = apiBaseURL + "/trades/" + pairID + "?sort=DESC&limit=100"
} else {
unixTime := strconv.Itoa(int(fromTimestamp.Unix()))
url = apiBaseURL + "/trades/" + pairID + "?sort=DESC&from=" + unixTime + "&limit=100"
}
bytes, _, err = utils.GetRequest(url)
if err != nil {
return nil, err
}
err = json.Unmarshal(bytes, &response)
if err != nil {
return []STEXTrade{}, err
}
// Update timestamp
pairIDInt, _ := strconv.ParseInt(pairID, 10, 32)
symbol := s.pairIDToSymbol[int(pairIDInt)]
if len(response.SETXTrades) > 0 {
var lastTimestamp int64
lastTimestamp, err = strconv.ParseInt(response.SETXTrades[0].TimeStamp, 10, 64)
if err != nil {
log.Error("error parsing trade's timestamp")
}
s.pairLastTimeStamp[symbol] = time.Unix(lastTimestamp+1, 0)
}
return response.SETXTrades, nil
}
/*
func (s *STEXScraper) cleanup(err error) {
s.errorLock.Lock()
defer s.errorLock.Unlock()
if err != nil {
s.error = err
}
s.closed = true
close(s.shutdownDone)
}
*/
// Close closes any existing API connections, as well as channels of
// PairScrapers from calls to ScrapePair
func (s *STEXScraper) Close() error {
if s.closed {
return errors.New("STEXScraper: Already closed")
}
close(s.shutdown)
s.c.Close()
<-s.shutdownDone
s.errorLock.RLock()
defer s.errorLock.RUnlock()
return s.error
}
// ScrapePair returns a PairScraper that can be used to get trades for a single pair from
// this APIScraper
func (s *STEXScraper) ScrapePair(pair dia.ExchangePair) (PairScraper, error) {
s.errorLock.RLock()
defer s.errorLock.RUnlock()
if s.error != nil {
return nil, s.error
}
if s.closed {
return nil, errors.New("STEXScraper: Call ScrapePair on closed scraper")
}
ps := &STEXPairScraper{
parent: s,
pair: pair,
}
s.pairScrapers[pair.ForeignName] = ps
a := &Channel{
Channel: fmt.Sprintf("trade_c%s", pair.ForeignName),
}
if err := s.c.Emit("subscribe", a); err != nil {
fmt.Println(err.Error())
}
return ps, nil
}
func (s *STEXScraper) NormalizePair(pair dia.ExchangePair) (dia.ExchangePair, error) {
symbol := strings.ToUpper(pair.Symbol)
pair.Symbol = symbol
if helpers.SymbolIsBlackListed(symbol) {
return pair, errors.New("Symbol is black listed:" + symbol)
}
return pair, nil
}
// FetchAvailablePairs returns a list with all available trade pairs
func (s *STEXScraper) FetchAvailablePairs() (pairs []dia.ExchangePair, err error) {
type CurrencyPairs struct {
Success bool `json:"success"`
Data []struct {
ID int `json:"id"`
CurrencyID int `json:"currency_id"`
CurrencyCode string `json:"currency_code"`
CurrencyName string `json:"currency_name"`
MarketCurrencyID int `json:"market_currency_id"`
MarketCode string `json:"market_code"`
MarketName string `json:"market_name"`
MinOrderAmount string `json:"min_order_amount"`
MinBuyPrice string `json:"min_buy_price"`
MinSellPrice string `json:"min_sell_price"`
BuyFeePercent string `json:"buy_fee_percent"`
SellFeePercent string `json:"sell_fee_percent"`
Active bool `json:"active"`
Delisted bool `json:"delisted"`
PairMessage string `json:"pair_message"`
CurrencyPrecision int `json:"currency_precision"`
MarketPrecision int `json:"market_precision"`
Symbol string `json:"symbol"`
GroupName string `json:"group_name"`
GroupID int `json:"group_id"`
AmountMultiplier int `json:"amount_multiplier"`
} `json:"data"`
}
data, _, err := utils.GetRequest("https://api3.stex.com/public/currency_pairs/list/ALL")
if err != nil {
return
}
var response CurrencyPairs
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
if !response.Success {
return nil, errors.New("unsuccessful attempt to get currency pairs on STEX exchange")
}
for _, p := range response.Data {
pairToNormalize := dia.ExchangePair{
Symbol: p.CurrencyCode,
ForeignName: p.Symbol,
Exchange: s.exchangeName,
}
pair, serr := s.NormalizePair(pairToNormalize)
if serr == nil {
pairs = append(pairs, pair)
s.pairSymbolToID[p.Symbol] = p.ID
s.pairIDToSymbol[p.ID] = p.Symbol
} else {
log.Println(serr)
}
}
return
}
// STEXPairScraper implements PairScraper for STEX
type STEXPairScraper struct {
parent *STEXScraper
pair dia.ExchangePair
closed bool
}
// Close stops listening for trades of the pair associated with s
func (ps *STEXPairScraper) Close() error {
ps.closed = true
return nil
}
// Channel returns a channel that can be used to receive trades
func (ps *STEXScraper) Channel() chan *dia.Trade {
return ps.chanTrades
}
// Error returns an error when the channel Channel() is closed
// and nil otherwise
func (ps *STEXPairScraper) Error() error {
s := ps.parent
s.errorLock.RLock()
defer s.errorLock.RUnlock()
return s.error
}
// Pair returns the pair this scraper is subscribed to
func (ps *STEXPairScraper) Pair() dia.ExchangePair {
return ps.pair
}