-
Notifications
You must be signed in to change notification settings - Fork 0
/
exchange.go
109 lines (86 loc) · 1.82 KB
/
exchange.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
package main
import (
"errors"
"fmt"
"io"
"log"
"strings"
"sync"
"time"
"golang.org/x/net/websocket"
)
type Command struct {
Name string
Args []string
}
type Exchange struct {
sync.RWMutex
Name string
addr string
origin string
ws *websocket.Conn
reqID int64
}
func NewExchange(name, addr, origin string) *Exchange {
return &Exchange{
Name: name,
addr: addr,
origin: origin,
reqID: 1,
}
}
func (e *Exchange) Run() {
for {
ws, err := websocket.Dial(e.addr, "", e.origin)
if err != nil {
log.Println(fmt.Errorf("unable to connect to %s, reconnecting... %s", e.Name, err))
time.Sleep(BinanceReconnectDelay * time.Second)
continue
}
e.ws = ws
e.readMessages()
log.Printf("%s run", e.Name)
}
}
func (e *Exchange) readMessages() {
var data []byte
for {
err := websocket.Message.Receive(e.ws, &data)
if errors.Is(err, io.EOF) {
return
}
if err != nil {
log.Println(err)
return
}
log.Println(string(data))
}
}
func (e *Exchange) sendMessage(message []byte) {
log.Printf("send: %s: %s", e.Name, string(message))
err := websocket.Message.Send(e.ws, string(message))
if err != nil {
log.Println(err)
return
}
}
func (e *Exchange) FormatPair(pair string) string {
pair = strings.ReplaceAll(pair, "/", "")
pair = strings.ToLower(pair)
return pair
}
func (e *Exchange) incrReqID() {
e.Lock()
defer e.Unlock()
e.reqID++
}
func (e *Exchange) Subscribe(pair string) {
req := "{\"method\": \"SUBSCRIBE\", \"params\": [\"%s@bookTicker\"], \"id\": %d}\n"
e.sendMessage([]byte(fmt.Sprintf(req, e.FormatPair(pair), e.reqID)))
e.incrReqID()
}
func (e *Exchange) Unsubscribe(pair string) {
req := "{\"method\": \"UNSUBSCRIBE\", \"params\": [\"%s@bookTicker\"], \"id\": %d}\n"
e.sendMessage([]byte(fmt.Sprintf(req, e.FormatPair(pair), e.reqID)))
e.incrReqID()
}