-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
client_web_socket.go
177 lines (148 loc) · 3.2 KB
/
client_web_socket.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
package bybit
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
const (
// WebsocketBaseURL :
WebsocketBaseURL = "wss://stream.bybit.com"
// WebsocketBaseURL2 :
WebsocketBaseURL2 = "wss://stream.bytick.com"
)
// WebSocketClient :
type WebSocketClient struct {
debug bool
logger *log.Logger
baseURL string
key string
secret string
dialer *websocket.Dialer
}
func (c *WebSocketClient) debugf(format string, v ...interface{}) {
if c.debug {
c.logger.Printf(format, v...)
}
}
// NewWebsocketClient :
func NewWebsocketClient() *WebSocketClient {
return &WebSocketClient{
logger: newDefaultLogger(),
baseURL: WebsocketBaseURL,
}
}
// WithDebug :
func (c *WebSocketClient) WithDebug(debug bool) *WebSocketClient {
c.debug = debug
return c
}
// WithLogger :
func (c *WebSocketClient) WithLogger(logger *log.Logger) *WebSocketClient {
c.debug = true
c.logger = logger
return c
}
// WithAuth :
func (c *WebSocketClient) WithAuth(key string, secret string) *WebSocketClient {
c.key = key
c.secret = secret
return c
}
// WithBaseURL :
func (c *WebSocketClient) WithBaseURL(url string) *WebSocketClient {
c.baseURL = url
return c
}
// WithDialer :
func (c *WebSocketClient) WithDialer(dialer *websocket.Dialer) *WebSocketClient {
c.dialer = dialer
return c
}
// hasAuth : check has auth key and secret
func (c *WebSocketClient) hasAuth() bool {
return c.key != "" && c.secret != ""
}
func (c *WebSocketClient) buildAuthParam() ([]byte, error) {
if !c.hasAuth() {
return nil, fmt.Errorf("this is private endpoint, please set api key and secret")
}
expires := time.Now().Unix()*1000 + 10000
req := fmt.Sprintf("GET/realtime%d", expires)
s := hmac.New(sha256.New, []byte(c.secret))
if _, err := s.Write([]byte(req)); err != nil {
return nil, err
}
signature := hex.EncodeToString(s.Sum(nil))
param := struct {
Op string `json:"op"`
Args []interface{} `json:"args"`
}{
Op: "auth",
Args: []interface{}{c.key, expires, signature},
}
buf, err := json.Marshal(param)
if err != nil {
return nil, err
}
return buf, nil
}
// WebsocketExecutor :
type WebsocketExecutor interface {
Run() error
Close() error
Ping() error
}
// Start :
func (c *WebSocketClient) Start(ctx context.Context, executors []WebsocketExecutor) {
done := make(chan struct{})
go func() {
defer close(done)
for {
for _, executor := range executors {
if err := executor.Run(); err != nil {
if IsErrWebsocketClosed(err) {
return
}
c.debugf("websocket executor error: %s", err)
return
}
}
}
}()
ticker := time.NewTicker(20 * time.Second)
defer ticker.Stop()
ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
defer stop()
for {
select {
case <-done:
return
case <-ticker.C:
for _, executor := range executors {
if err := executor.Ping(); err != nil {
return
}
}
case <-ctx.Done():
c.debugf("caught websocket interrupt signal")
for _, executor := range executors {
if err := executor.Close(); err != nil {
return
}
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}