-
Notifications
You must be signed in to change notification settings - Fork 38
/
bybit_websocket.go
259 lines (222 loc) · 6.1 KB
/
bybit_websocket.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
package bybit_connector
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type MessageHandler func(message string) error
func (b *WebSocket) handleIncomingMessages() {
for {
_, message, err := b.conn.ReadMessage()
if err != nil {
fmt.Println("Error reading:", err)
b.isConnected = false
return
}
if b.onMessage != nil {
err := b.onMessage(string(message))
if err != nil {
fmt.Println("Error handling message:", err)
return
}
}
}
}
func (b *WebSocket) monitorConnection() {
ticker := time.NewTicker(time.Second * 5) // Check every 5 seconds
defer ticker.Stop()
for {
<-ticker.C
if !b.isConnected && b.ctx.Err() == nil { // Check if disconnected and context not done
fmt.Println("Attempting to reconnect...")
con := b.Connect() // Example, adjust parameters as needed
if con == nil {
fmt.Println("Reconnection failed:")
} else {
b.isConnected = true
go b.handleIncomingMessages() // Restart message handling
}
}
select {
case <-b.ctx.Done():
return // Stop the routine if context is done
default:
}
}
}
func (b *WebSocket) SetMessageHandler(handler MessageHandler) {
b.onMessage = handler
}
type WebSocket struct {
conn *websocket.Conn
url string
apiKey string
apiSecret string
maxAliveTime string
pingInterval int
onMessage MessageHandler
ctx context.Context
cancel context.CancelFunc
isConnected bool
}
type WebsocketOption func(*WebSocket)
func WithPingInterval(pingInterval int) WebsocketOption {
return func(c *WebSocket) {
c.pingInterval = pingInterval
}
}
func WithMaxAliveTime(maxAliveTime string) WebsocketOption {
return func(c *WebSocket) {
c.maxAliveTime = maxAliveTime
}
}
func NewBybitPrivateWebSocket(url, apiKey, apiSecret string, handler MessageHandler, options ...WebsocketOption) *WebSocket {
c := &WebSocket{
url: url,
apiKey: apiKey,
apiSecret: apiSecret,
maxAliveTime: "",
pingInterval: 20,
onMessage: handler,
}
// Apply the provided options
for _, opt := range options {
opt(c)
}
return c
}
func NewBybitPublicWebSocket(url string, handler MessageHandler) *WebSocket {
c := &WebSocket{
url: url,
pingInterval: 20, // default is 20 seconds
onMessage: handler,
}
return c
}
func (b *WebSocket) Connect() *WebSocket {
var err error
wssUrl := b.url
if b.maxAliveTime != "" {
wssUrl += "?max_alive_time=" + b.maxAliveTime
}
b.conn, _, err = websocket.DefaultDialer.Dial(wssUrl, nil)
if b.requiresAuthentication() {
if err = b.sendAuth(); err != nil {
fmt.Println("Failed Connection:", fmt.Sprintf("%v", err))
return nil
}
}
b.isConnected = true
go b.handleIncomingMessages()
go b.monitorConnection()
b.ctx, b.cancel = context.WithCancel(context.Background())
go ping(b)
return b
}
func (b *WebSocket) SendSubscription(args []string) (*WebSocket, error) {
reqID := uuid.New().String()
subMessage := map[string]interface{}{
"req_id": reqID,
"op": "subscribe",
"args": args,
}
fmt.Println("subscribe msg:", fmt.Sprintf("%v", subMessage["args"]))
if err := b.sendAsJson(subMessage); err != nil {
fmt.Println("Failed to send subscription:", err)
return b, err
}
fmt.Println("Subscription sent successfully.")
return b, nil
}
// sendRequest sends a custom request over the WebSocket connection.
func (b *WebSocket) sendRequest(op string, args map[string]interface{}, headers map[string]string) error {
reqID := uuid.New().String()
request := map[string]interface{}{
"reqId": reqID,
"header": headers,
"op": op,
"args": []interface{}{args},
}
fmt.Println("request headers:", fmt.Sprintf("%v", request["header"]))
fmt.Println("request op channel:", fmt.Sprintf("%v", request["op"]))
fmt.Println("request msg:", fmt.Sprintf("%v", request["args"]))
return b.sendAsJson(request)
}
func ping(b *WebSocket) {
if b.pingInterval <= 0 {
fmt.Println("Ping interval is set to a non-positive value.")
return
}
ticker := time.NewTicker(time.Duration(b.pingInterval) * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
currentTime := time.Now().Unix()
pingMessage := map[string]string{
"op": "ping",
"req_id": fmt.Sprintf("%d", currentTime),
}
jsonPingMessage, err := json.Marshal(pingMessage)
if err != nil {
fmt.Println("Failed to marshal ping message:", err)
continue
}
if err := b.conn.WriteMessage(websocket.TextMessage, jsonPingMessage); err != nil {
fmt.Println("Failed to send ping:", err)
return
}
fmt.Println("Ping sent with UTC time:", currentTime)
case <-b.ctx.Done():
fmt.Println("Ping context closed, stopping ping.")
return
}
}
}
func (b *WebSocket) Disconnect() error {
b.cancel()
b.isConnected = false
return b.conn.Close()
}
func (b *WebSocket) requiresAuthentication() bool {
return b.url == WEBSOCKET_PRIVATE_MAINNET ||
b.url == WEBSOCKET_PRIVATE_TESTNET || b.url == WEBSOCKET_TRADE_MAINNET || b.url == WEBSOCKET_TRADE_TESTNET || b.url == WEBSOCKET_TRADE_DEMO || b.url == WEBSOCKET_PRIVATE_DEMO
// v3 offline
/*
b.url == V3_CONTRACT_PRIVATE ||
b.url == V3_UNIFIED_PRIVATE ||
b.url == V3_SPOT_PRIVATE
*/
}
func (b *WebSocket) sendAuth() error {
// Get current Unix time in milliseconds
expires := time.Now().UnixNano()/1e6 + 10000
val := fmt.Sprintf("GET/realtime%d", expires)
h := hmac.New(sha256.New, []byte(b.apiSecret))
h.Write([]byte(val))
// Convert to hexadecimal instead of base64
signature := hex.EncodeToString(h.Sum(nil))
fmt.Println("signature generated : " + signature)
authMessage := map[string]interface{}{
"req_id": uuid.New(),
"op": "auth",
"args": []interface{}{b.apiKey, expires, signature},
}
fmt.Println("auth args:", fmt.Sprintf("%v", authMessage["args"]))
return b.sendAsJson(authMessage)
}
func (b *WebSocket) sendAsJson(v interface{}) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
return b.send(string(data))
}
func (b *WebSocket) send(message string) error {
return b.conn.WriteMessage(websocket.TextMessage, []byte(message))
}