This repository has been archived by the owner on Nov 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 147
/
BybitWebsocket.go
89 lines (78 loc) · 1.95 KB
/
BybitWebsocket.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
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"reflect"
"time"
"unsafe"
"github.com/gorilla/websocket"
)
func main() {
// testnet
wsurl := "wss://stream-testnet.bybit.com/realtime"
// main site
// wsurl := "wss://stream.bybit.com/realtime"
key := ""
secret := ""
//generate signature
expires := fmt.Sprintf("%v", time.Now().Unix()) + "1000"
h := hmac.New(sha256.New, []byte(secret))
_val := "GET/realtime" + expires
io.WriteString(h, _val)
sign := fmt.Sprintf("%x", h.Sum(nil))
//connect
ws, _, err := websocket.DefaultDialer.Dial(wsurl, nil)
if err != nil {
fmt.Println("Connect Error!")
return
}
//auth
args := []string{key, expires, sign}
param := make(map[string]interface{})
param["op"] = "auth"
param["args"] = args
req, _ := json.Marshal(param)
err = ws.WriteMessage(websocket.TextMessage, []byte(req))
if err != nil {
fmt.Println("Write Websocket Message Error!")
return
}
//subscribe orderBookL2_25
param = make(map[string]interface{})
param["op"] = "subscribe"
args = []string{"orderBookL2_25.BTCUSD"}
param["args"] = args
req, _ = json.Marshal(param)
if err := ws.WriteMessage(websocket.TextMessage, []byte(req)); err != nil {
fmt.Println("Subscribe Order Book Error!")
return
}
//subscribe position
param = make(map[string]interface{})
param["op"] = "subscribe"
args = []string{"position"}
param["args"] = args
req, _ = json.Marshal(param)
if err := ws.WriteMessage(websocket.TextMessage, []byte(req)); err != nil {
fmt.Println("Subscribe Position Error!")
return
}
//read message from server
for true {
_, msg, err := ws.ReadMessage()
if err != nil {
fmt.Println("Read Server Message Error!")
return
}
response := BytesToString(msg)
fmt.Println("the message is ", response)
}
}
func BytesToString(b []byte) string {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := reflect.StringHeader{bh.Data, bh.Len}
return *(*string)(unsafe.Pointer(&sh))
}