forked from go-numb/go-dydx
/
connect.go
245 lines (205 loc) · 5.88 KB
/
connect.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
package realtime
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/buger/jsonparser"
"github.com/magiclars-off/go-dydx/private"
"github.com/magiclars-off/go-dydx/public"
"github.com/gorilla/websocket"
)
const (
PRODUCTION = "wss://api.dydx.exchange/v3/ws"
STAGING = "wss://api.stage.dydx.exchange/v3/ws"
)
const (
UNDEFINED = "undefined"
ERROR = "error"
ACCOUNT = "v3_accounts"
MARKETS = "v3_markets"
ORDERBOOK = "v3_orderbook"
TRADES = "v3_trades"
)
type request struct {
Type string `json:"type"`
Channel string `json:"channel"`
// Public
ID string `json:"id,omitempty"`
IncludeOffsets bool `json:"includeOffsets,omitempty"`
// Private
AccountNumber string `json:"accountNumber,omitempty"`
ApiKey string `json:"apiKey,omitempty"`
Signature string `json:"signature,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Passphrase string `json:"passphrase,omitempty"`
}
type Response struct {
Type string `json:"type"`
Channel string `json:"channel"`
ConnectionID string `json:"connection_id,omitempty"`
ID string `json:"id,omitempty"`
MessageID int `json:"message_id,omitempty"`
Contents any `json:"-"`
Account Account `json:"-"`
Markets public.MarketsResponse `json:"-"`
Trades public.TradesResponse `json:"-"`
Orderbook public.OrderbookResponse `json:"-"`
Results error
}
type Account struct {
Orders []private.Order `json:"orders"`
private.AccountResponse
private.TransfersResponse
private.FundingPaymentsResponse
}
func subscribe(conn *websocket.Conn, private *private.Private, channels, symbols []string) error {
for i := range channels {
if private != nil && channels[i] == ACCOUNT {
r := &request{
Type: "subscribe",
Channel: channels[i],
// single account
AccountNumber: "0",
ApiKey: private.ApiKeyCredentials.Key,
Passphrase: private.ApiKeyCredentials.Passphrase,
}
isoTimestamp := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
r.Signature = private.Sign("/ws/accounts", http.MethodGet, isoTimestamp, "")
r.Timestamp = isoTimestamp
if err := conn.WriteJSON(r); err != nil {
return err
}
time.Sleep(time.Second)
fmt.Println("account request")
continue
}
for j := range symbols {
r := &request{ // "{"type":"subscribe","channel":"v3_trades","id":"BTC-USD"}
Type: "subscribe",
Channel: channels[i],
ID: symbols[j],
}
if r.Channel == ORDERBOOK {
r.IncludeOffsets = true
}
if err := conn.WriteJSON(r); err != nil {
return err
}
time.Sleep(time.Second)
}
}
return nil
}
func unsubscribe(conn *websocket.Conn, channels, symbols []string) error {
for i := range channels {
if err := conn.WriteJSON(&request{
Type: "unsubscribe",
Channel: channels[i],
}); err != nil {
return err
}
}
return nil
}
func ping(conn *websocket.Conn) (err error) {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := conn.WriteMessage(websocket.PingMessage, []byte(`pong`)); err != nil {
goto EXIT
}
}
}
EXIT:
return err
}
func Connect(ctx context.Context, ch chan Response, channels, symbols []string, private *private.Private, l *log.Logger) error {
RESTART:
if l == nil {
l = log.New(os.Stdout, "dYdX websocket ", log.Llongfile)
}
conn, _, err := websocket.DefaultDialer.Dial(PRODUCTION, nil)
if err != nil {
return err
}
// Initial connect
_, msg, err := conn.ReadMessage()
if err != nil {
l.Printf("[ERROR]: msg error: %+v", err)
return err
}
if err := subscribe(conn, private, channels, symbols); err != nil {
l.Printf("[ERROR]: connected error: %+v", string(msg))
return err
}
// Dorument: The server will send pings every 30s and expects a pong within 10s. The server does not expect pings, but will respond with a pong if sent one.
// Pong every 10 seconds without Ping.
go ping(conn)
func() {
defer conn.Close()
defer unsubscribe(conn, channels, symbols)
for {
var res Response
_, msg, err := conn.ReadMessage()
if err != nil {
l.Printf("[ERROR]: msg error: %+v", err)
res.Channel = ERROR
res.Results = fmt.Errorf("%v", err)
ch <- res
}
if err := json.Unmarshal(msg, &res); err != nil {
l.Printf("[ERROR]: unmarshal error: %+v", string(msg))
res.Channel = ERROR
res.Results = fmt.Errorf("%v", string(msg))
ch <- res
}
data, _, _, err := jsonparser.Get(msg, "contents")
if err != nil {
err = fmt.Errorf("[ERROR]: data err: %v %s", err, string(msg))
l.Println(err)
res.Channel = ERROR
res.Results = err
ch <- res
}
switch res.Channel {
case ACCOUNT:
if err := json.Unmarshal(data, &res.Account); err != nil {
l.Printf("[WARN]: cant unmarshal accounts %+v", err)
continue
}
case MARKETS:
if err := json.Unmarshal(data, &res.Markets); err != nil {
l.Printf("[WARN]: cant unmarshal orderbook %+v", err)
continue
}
case TRADES:
if err := json.Unmarshal(data, &res.Trades); err != nil {
l.Printf("[WARN]: cant unmarshal trades %+v", err)
continue
}
case ORDERBOOK:
if err := json.Unmarshal(data, &res.Orderbook); err != nil {
l.Printf("[WARN]: cant unmarshal orderbook %+v", err)
continue
}
case ERROR:
message, _, _, err := jsonparser.Get(msg, "message")
err = fmt.Errorf("[ERROR]: type err: %v %s", err, string(message))
l.Println(err)
res.Channel = ERROR
res.Results = err
default:
res.Channel = UNDEFINED
res.Results = fmt.Errorf("%v", string(msg))
}
ch <- res
}
}()
goto RESTART
}