-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpricetest.go
101 lines (86 loc) · 1.97 KB
/
pricetest.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
package main
import (
"encoding/json"
"goalert/services"
"log"
"os"
"os/signal"
"strconv"
"github.com/gorilla/websocket"
)
type Message struct {
EventType string `json:"e"`
EventTime int64 `json:"E"`
Symbol string `json:"s"`
Price string `json:"c"`
C float64 `json:"C"`
}
func UnmarshalWelcome(data []byte) (Message, error) {
var r Message
err := json.Unmarshal(data, &r)
return r, err
}
func main() {
endpoint := "wss://stream.binance.com:9443/ws"
symbols := []string{"btcusdt"}
services.AddMovingAverageWindow("btcusdt", 5)
services.AddMovingAverageWindow("btcusdt", 10)
services.AddMovingAverageWindow("btcusdt", 15)
c, _, err := websocket.DefaultDialer.Dial(endpoint, nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
for _, symbol := range symbols {
subscribeMsg := []byte(`{"method":"SUBSCRIBE","params":["` + symbol + `@ticker"],"id":1}`)
err := c.WriteMessage(websocket.TextMessage, subscribeMsg)
if err != nil {
log.Fatal("subscribe:", err)
}
}
done := make(chan struct{})
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
prettyPrint(message)
}
}()
for {
select {
case <-done:
return
case <-interrupt:
log.Println("interrupt")
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
}
return
}
}
}
func prettyPrint(message []byte) {
var m Message
err := json.Unmarshal(message, &m)
if err != nil {
log.Println("unmarshal:", err)
return
}
if m.Price != "" {
floatPrice, _ := strconv.ParseFloat(m.Price, 64)
services.AddPrice("btcusdt", floatPrice)
services.PrintStockData("btcusdt")
}
log.Printf("Symbol: %s, Price: %s", m.Symbol, m.Price)
}