-
Notifications
You must be signed in to change notification settings - Fork 126
/
FuturesDeribitScraper.go
189 lines (170 loc) · 5.69 KB
/
FuturesDeribitScraper.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
package scrapers
import (
"encoding/json"
"errors"
"fmt"
"time"
utils "github.com/diadata-org/diadata/pkg/utils"
"github.com/gorilla/websocket"
)
// const scrapeDataSaveLocationDeribit = ""
type deribitInstrument struct {
InstrumentName string `json:"instrument_name"`
Kind string `json:"kind"`
TickSize float64 `json:"tick_size"`
TakerCommission float64 `json:"taker_commission"`
Strike float64 `json:"strike"`
SettlementPeriod string `json:"settlement_period"`
QuoteCurrency string `json:"quote_currency"`
OptionType string `json:"option_type"`
MinTradeAmount float64 `json:"min_trade_amount"`
MakerCommission float64 `json:"maker_commission"`
IsActive bool `json:"is_active"`
ExpirationTimestamp int64 `json:"expiration_timestamp"`
CreationTimestamp int64 `json:"creation_timestamp"`
ContractSize float64 `json:"contract_size"`
BaseCurrency string `json:"base_currency"`
}
type deribitInstruments struct {
Result []deribitInstrument `json:"result"`
}
type ParsedDeribitResponse struct {
Jsonrpc string `json:"jsonrpc"`
Method string `json:"method"`
Params ParsedDeribitResponseParams `json:"params"`
}
type ParsedDeribitResponseParams struct {
Channel string `json:"channel"`
Data ParsedDeribitOptionOrderbookEntry `json:"data"`
}
type ParsedDeribitOptionOrderbookEntry struct {
Timestamp int64 `json:"timestamp"`
InstrumentName string `json:"instrument_name"`
ChangeId int64 `json:"change_id"`
Bids [][]float64 `json:"bids"`
Asks [][]float64 `json:"asks"`
}
func (s *DeribitScraper) send(message *map[string]interface{}, websocketConn *websocket.Conn) error {
err := websocketConn.WriteJSON(*message)
if err != nil {
return err
}
return nil
}
// ScraperClose - responsible for closing out the scraper for a market
func (s *DeribitScraper) ScraperClose(market string, websocketConnection interface{}) error {
switch c := websocketConnection.(type) {
case *websocket.Conn:
err := c.WriteJSON(map[string]string{"op": "unsubscribe", "channel": "trades", "market": market})
if err != nil {
return err
}
log.Infof("gracefully shutdown deribit scraper on market: %s", market)
time.Sleep(time.Duration(retryIn) * time.Second)
return nil
default:
return fmt.Errorf("unknown connection type, expected gorilla/websocket, got: %T", c)
}
}
// Scrape starts a websocket scraper for market
func (s *DeribitScraper) Scrape(market string) {
err := s.validateMarket(market, s.MarketKind)
if err != nil {
return
}
s.validateRefreshEveryToken()
optionRequest := &map[string]interface{}{
"method": "public/subscribe",
"params": &map[string]interface{}{
"channels": []string{"book." + market + ".none.1.100ms"}, // will give us orderbook snapshots every 100 ms
},
"jsonrpc": "2.0",
"id": 0,
}
futureRequest := &map[string]interface{}{
"method": "private/subscribe",
"params": &map[string]interface{}{
"channels": []string{"trades." + market + ".raw"},
},
"jsonrpc": "2.0",
"id": 0,
}
switch s.MarketKind {
case DeribitFuture:
err = s.send(futureRequest, s.WsConnection)
case DeribitOption:
err = s.send(optionRequest, s.WsConnection)
default:
panic("unknown market kind")
}
if err != nil {
log.Errorf("could not send ws message. restarting the websocket, err: %s", err)
return
}
}
// ScrapeMarkets - will scrape the markets specified during instantiation
func (s *DeribitScraper) ScrapeMarkets() {
for _, market := range s.Markets {
s.WaitGroup.Add(1)
go s.Scrape(market)
}
s.WaitGroup.Wait()
}
// marketKind can be "future" or "option"
func (s *DeribitScraper) validateMarket(market string, marketKind DeribitScraperKind) error {
allFuturesMarketsDeribit, err := allDeribitMarketsOfKind(marketKind)
if err != nil {
return err
}
containsMarket := utils.Contains(&allFuturesMarketsDeribit, market)
if !containsMarket {
return errors.New(market + " market is unavailable")
}
return nil
}
func (s *DeribitScraper) validateRefreshEveryToken() {
if s.RefreshTokenEvery >= 900 {
panic("When you use https://testapp.deribit.com/api_console, you will see that upon a successful authentication, the response will include expiresIn field. Which is set at 900. This means that the token we generated is only valid for 900 seconds, and we have to refresh it before then.")
}
}
func deribitMarkets(market string, marketKind DeribitScraperKind) ([]string, error) {
if market != "BTC" && market != "ETH" {
panic("unsupported market. only btc & eth are supported")
}
body, _, err := utils.GetRequest("https://www.deribit.com/api/v2/public/get_instruments?currency=" + market)
if err != nil {
return nil, err
}
decodedMsg := deribitInstruments{}
err = json.Unmarshal(body, &decodedMsg)
if err != nil {
return nil, err
}
var allMarkets []string
for _, market := range decodedMsg.Result {
switch marketKind {
case DeribitFuture:
if market.Kind == "future" {
allMarkets = append(allMarkets, market.InstrumentName)
}
case DeribitOption:
if market.Kind == "option" {
allMarkets = append(allMarkets, market.InstrumentName)
}
default:
panic("unknown market kind")
}
}
return allMarkets, nil
}
func allDeribitMarketsOfKind(marketKind DeribitScraperKind) ([]string, error) {
BTCMarkets, err := deribitMarkets("BTC", marketKind)
if err != nil {
return nil, fmt.Errorf("could not fetch btc futures markets: %w", err)
}
ETHMarkets, err := deribitMarkets("ETH", marketKind)
if err != nil {
return nil, fmt.Errorf("could not fetch eth futures markets: %w", err)
}
return append(BTCMarkets, ETHMarkets...), nil
}