-
Notifications
You must be signed in to change notification settings - Fork 126
/
FuturesHuobiScraper.go
268 lines (242 loc) · 7.79 KB
/
FuturesHuobiScraper.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
package scrapers
import (
"bytes"
"compress/gzip"
"encoding/binary"
"fmt"
"github.com/diadata-org/diadata/internal/pkg/scraper-writers"
"io/ioutil"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
utils "github.com/diadata-org/diadata/pkg/utils"
zap "go.uber.org/zap"
"golang.org/x/net/websocket"
)
// --------------------------------- Config --------------------------------------------------
// Huobi API configuration
const (
scrapeDataSaveLocationHuobi string = "" // location in which to save. ensure that the folder exists.
// files will be created automatically
// API Endpoints
// marketURLHuobi string = "https://api.hbdm.com"
wsURLHuobi string = "wss://www.hbdm.com/ws"
pingMsgLengthHuobi int = 22
)
var (
allowedMarketsHuobi = []string{"BTC", "ETC", "ETH", "EOS", "LTC", "BCH", "XRP", "TRX", "BSV"}
allowedFrequenciesHuobi = []string{"CW", "NW", "CQ"}
// bufferHuobi bytes.Buffer
)
// ---------------
// HuobiFuturesScraper - scrapes huobi's futures markets
type HuobiFuturesScraper struct {
Markets []string // markets to scrape. To scrape all, call AllFuturesMarketsHuobi()
WaitGroup *sync.WaitGroup
Writer writers.Writer // an interface to write the messages
Logger *zap.SugaredLogger
}
// --------------------------------------------------------------------------------------------
// NewHuobiFuturesScraper - returns an instance of the Huobi scraper
func NewHuobiFuturesScraper(markets []string) FuturesScraper {
wg := sync.WaitGroup{}
writer := writers.FileWriter{}
logger := zap.NewExample().Sugar() // or NewProduction, or NewDevelopment
defer func() {
err := logger.Sync()
if err != nil {
log.Error(err)
}
}()
var scraper FuturesScraper = &HuobiFuturesScraper{
WaitGroup: &wg,
Markets: markets, // []string{"BNB-PERP", "ETH-PERP", "BTC-PERP", "EOS-PERP"}
Writer: &writer,
Logger: logger,
}
return scraper
}
// sends a byte message to huobi websocket
func (s *HuobiFuturesScraper) send(message []byte, market string, websocketConn *websocket.Conn) (int, error) {
n, err := websocketConn.Write(message)
s.Logger.Debugf("[%s] send: %s", market, message)
return n, err
}
// pongs back the huobi websocket client to keep the connection alive
func (s *HuobiFuturesScraper) pong(time string, market string, websocketConn *websocket.Conn) (int, error) {
n, err := s.send([]byte(fmt.Sprintf("{\"pong\":%s}", time)), market, websocketConn)
return n, err
}
// Authenticate - not required for Huobi to scrape the futures data.
func (s *HuobiFuturesScraper) Authenticate(market string, connection interface{}) error { return nil }
// ScraperClose - clean up after the scraper.
func (s *HuobiFuturesScraper) ScraperClose(market string, connection interface{}) error {
switch c := connection.(type) {
case *websocket.Conn:
message := []byte("{\"Unsub\":\"market." + market + ".trade.detail\"}")
_, err := s.send(message, market, c)
if err != nil {
return err
}
err = c.Close()
if err != nil {
return err
}
s.Logger.Infof("gracefully shutdown huobi scraper on market: %s", market)
time.Sleep(time.Duration(retryIn) * time.Second)
return nil
default:
return fmt.Errorf("unknown connection type, expected golang.org/x/net/websocket, got: %T", connection)
}
}
// Scrape starts a websocket scraper for market
func (s *HuobiFuturesScraper) Scrape(market string) {
s.validateMarket(market)
// this block is for listening to sigterms and interupts
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
userCancelled := make(chan bool, 1)
go func() {
sig := <-sigs
fmt.Println(sig)
userCancelled <- true
}()
for {
// IIFE for easy cleanup with defer
func() {
ws, err := websocket.Dial(wsURLHuobi, "", "http://www.google.com")
// defer inside of the function will cleanup before the next run
defer func() {
err = s.ScraperClose(market, ws)
if err != nil {
log.Error(err)
}
}()
if err != nil {
// an error opening is fatal. let this kill the programme
s.Logger.Errorf("[%s] %s", market, err)
time.Sleep(time.Duration(retryIn) * time.Second)
return
}
// subscribe to the trade detail channel
message := []byte("{\"Sub\":\"market." + market + ".trade.detail\"}")
_, err = s.send(message, market, ws)
if err != nil {
s.Logger.Errorf("problem subscriping to the [%s] trade channel, err: %s", market, err)
return
}
// create the conduit for the received messages
var msg = make([]byte, 512)
for {
select {
case <-userCancelled:
s.Logger.Infof("received interrupt, gracefully shutting down")
err := s.ScraperClose(market, ws)
if err != nil {
log.Error(err)
}
os.Exit(0)
default:
m, err := ws.Read(msg)
if err != nil {
s.Logger.Errorf("[%s] %s", market, err)
// an error reading means we may have lost the connection
// return out and just try again
return
}
newmsg := msg[:m]
unzipmsg, err := parseGzip(newmsg)
if err != nil {
s.Logger.Errorf("[%s] problem saving to %s, err: %s", market, s.Writer.GetWriteFileName("huobi", market), err)
return
}
s.Logger.Debugf("[%s] byteLen:%d, unzipLen:%d %s", market, m, len(unzipmsg), unzipmsg)
if len(unzipmsg) == pingMsgLengthHuobi {
if string(unzipmsg[2:6]) == "ping" {
_, err := s.pong(string(unzipmsg[8:21]), market, ws)
if err != nil {
s.Logger.Errorf("[%s] problem ponging the websocket server, err: %s", market, err)
return
}
}
} else {
// ensure that scrapeDataSaveLocation exists
_, err := s.Writer.Write(string(unzipmsg)+"\n", scrapeDataSaveLocationHuobi+s.Writer.GetWriteFileName("huobi", market))
if err != nil {
s.Logger.Errorf("[%s] problem saving to %s, err: %s", market, s.Writer.GetWriteFileName("huobi", market), err)
return
}
}
}
}
}()
}
// s.waitGroup.Done()
}
// ScrapeMarkets - will scrape the markets specified during instantiation
func (s *HuobiFuturesScraper) ScrapeMarkets() {
for _, market := range s.Markets {
s.WaitGroup.Add(1)
go s.Scrape(market)
}
s.WaitGroup.Wait()
}
// ------------- Huobi util functions -------------------
// AllFuturesMarketsHuobi - returns all the futures markets tradable on Huobi.
// Lists all of the Huobi Futures markets. TODO: add a REST HTTP call to obtain the list
// of trdabale markets.
func AllFuturesMarketsHuobi() []string {
allContracts := []string{}
for _, market := range allowedMarketsHuobi {
for _, maturity := range allowedFrequenciesHuobi {
allContracts = append(allContracts, market+"_"+maturity)
}
}
return allContracts
}
// Ensures that the provided market to scrape is supported by Huobi
// This function is only required if we manually write out the markets.
// This function will be removed when we make AllHuobiFuturesMarkets make
// a rest request
func (s *HuobiFuturesScraper) validateMarket(market string) {
parts := strings.Split(market, "_")
if len(parts) != 2 {
panic("incorrect market provided. should be of the form symbol_frequency")
}
tradeSymbol := parts[0]
tradeFrequency := parts[1]
containsSymbol := utils.Contains(&allowedMarketsHuobi, tradeSymbol)
if !containsSymbol {
panic("provided trade symbol is not supported")
}
containsFreq := utils.Contains(&allowedFrequenciesHuobi, tradeFrequency)
if !containsFreq {
panic("provided frequency is not supported")
}
}
// Huobi websocket API sends back gzips, this will parse it.
func parseGzip(data []byte) (unzipped []byte, err error) {
b := new(bytes.Buffer)
err = binary.Write(b, binary.LittleEndian, data)
if err != nil {
return
}
r, err := gzip.NewReader(b)
if err != nil {
return
}
defer func() {
cerr := r.Close()
if err == nil {
err = cerr
}
}()
unzipped, err = ioutil.ReadAll(r)
if err != nil {
return
}
return
}