forked from VictorFrWu/bybit.go.api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbybit_websocket.go
205 lines (173 loc) · 4.39 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
package bybit_connector
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
type MessageHandler func(message string) error
var mu sync.Mutex
func (b *WebSocket) handleIncomingMessages() {
for {
_, message, err := b.conn.ReadMessage()
if err != nil {
fmt.Println("Error reading:", err)
return
}
if b.onMessage != nil {
err := b.onMessage(string(message))
if err != nil {
fmt.Println("Error handling message:", err)
return
}
}
}
}
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
isPrivate 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,
isPrivate: true,
}
// Apply the provided options
for _, opt := range options {
opt(c)
}
return c
}
func NewBybitPublicWebSocket(url string, pingInterval int, handler MessageHandler, options ...WebsocketOption) *WebSocket {
c := &WebSocket{
url: url,
pingInterval: pingInterval, // default is 20 seconds
onMessage: handler,
}
// Apply the provided options
for _, opt := range options {
opt(c)
}
return c
}
func (b *WebSocket) Connect(args []string) error {
var err error
wssUrl := b.url
if b.maxAliveTime != "" {
wssUrl += "?max_alive_time=" + b.maxAliveTime
}
b.conn, _, err = websocket.DefaultDialer.Dial(b.url, nil)
if err != nil {
return err
}
if b.requiresAuthentication() {
if err = b.sendAuth(); err != nil {
return err
}
}
go b.handleIncomingMessages()
b.ctx, b.cancel = context.WithCancel(context.Background())
Ping(b)
return b.sendSubscription(args)
}
func Ping(b *WebSocket) {
ticker := time.NewTicker(time.Duration(b.pingInterval) * time.Second)
go func() {
defer ticker.Stop() // Ensure the ticker is stopped when this goroutine ends
for {
select {
case <-ticker.C: // Wait until the ticker sends a signal
mu.Lock()
defer mu.Unlock()
if err := b.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
fmt.Println("Failed to send ping:", err)
}
case <-b.ctx.Done():
fmt.Println("Exit ping")
return
}
}
}()
}
func (b *WebSocket) Disconnect() error {
b.cancel()
return b.conn.Close()
}
func (b *WebSocket) Send(message string) error {
mu.Lock()
defer mu.Unlock()
return b.conn.WriteMessage(websocket.TextMessage, []byte(message))
}
func (b *WebSocket) requiresAuthentication() bool {
return b.url == WEBSOCKET_PRIVATE_MAINNET ||
b.url == WEBSOCKET_PRIVATE_TESTNET ||
b.url == V3_CONTRACT_PRIVATE ||
b.url == V3_UNIFIED_PRIVATE ||
b.url == V3_SPOT_PRIVATE ||
b.isPrivate
}
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) sendSubscription(args []string) error {
subMessage := map[string]interface{}{
"req_id": uuid.New(),
"op": "subscribe",
"args": args,
}
fmt.Println("subscribe msg:", fmt.Sprintf("%v", subMessage["args"]))
return b.SendAsJson(subMessage)
}
func (b *WebSocket) SendAsJson(v interface{}) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
return b.Send(string(data))
}