forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpotWs.go
181 lines (143 loc) · 3.87 KB
/
SpotWs.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
package binance
import (
json2 "encoding/json"
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/soulsplit/goex"
"github.com/soulsplit/goex/internal/logger"
)
type req struct {
Method string `json:"method"`
Params []string `json:"params"`
Id int `json:"id"`
}
type resp struct {
Stream string `json:"stream"`
Data json2.RawMessage `json:"data"`
}
type depthResp struct {
LastUpdateId int `json:"lastUpdateId"`
Bids [][]interface{} `json:"bids"`
Asks [][]interface{} `json:"asks"`
}
type SpotWs struct {
c *goex.WsConn
reqId int
depthCallFn func(depth *goex.Depth)
tickerCallFn func(ticker *goex.Ticker)
tradeCallFn func(trade *goex.Trade)
}
func NewSpotWs() *SpotWs {
spotWs := &SpotWs{}
logger.Debugf("proxy url: %s", os.Getenv("HTTPS_PROXY"))
wsBuilder := goex.NewWsBuilder().
WsUrl("wss://stream.binance.com:9443/stream?streams=depth/miniTicker/ticker/trade").
ProxyUrl(os.Getenv("HTTPS_PROXY")).
ProtoHandleFunc(spotWs.handle).AutoReconnect()
spotWs.c = wsBuilder.Build()
spotWs.reqId = 1
return spotWs
}
func (s *SpotWs) DepthCallback(f func(depth *goex.Depth)) {
s.depthCallFn = f
}
func (s *SpotWs) TickerCallback(f func(ticker *goex.Ticker)) {
s.tickerCallFn = f
}
func (s *SpotWs) TradeCallback(f func(trade *goex.Trade)) {
s.tradeCallFn = f
}
func (s *SpotWs) SubscribeDepth(pair goex.CurrencyPair) error {
defer func() {
s.reqId++
}()
return s.c.Subscribe(req{
Method: "SUBSCRIBE",
Params: []string{
fmt.Sprintf("%s@depth10@100ms", pair.ToLower().ToSymbol("")),
},
Id: s.reqId,
})
}
func (s *SpotWs) SubscribeTicker(pair goex.CurrencyPair) error {
defer func() {
s.reqId++
}()
return s.c.Subscribe(req{
Method: "SUBSCRIBE",
Params: []string{pair.ToLower().ToSymbol("") + "@ticker"},
Id: s.reqId,
})
}
func (s *SpotWs) SubscribeTrade(pair goex.CurrencyPair) error {
panic("implement me")
}
func (s *SpotWs) handle(data []byte) error {
var r resp
err := json2.Unmarshal(data, &r)
if err != nil {
logger.Errorf("json unmarshal ws response error [%s] , response data = %s", err, string(data))
return err
}
if strings.HasSuffix(r.Stream, "@depth10@100ms") {
return s.depthHandle(r.Data, adaptStreamToCurrencyPair(r.Stream))
}
if strings.HasSuffix(r.Stream, "@ticker") {
return s.tickerHandle(r.Data, adaptStreamToCurrencyPair(r.Stream))
}
logger.Warn("unknown ws response:", string(data))
return nil
}
func (s *SpotWs) depthHandle(data json2.RawMessage, pair goex.CurrencyPair) error {
var (
depthR depthResp
dep goex.Depth
err error
)
err = json2.Unmarshal(data, &depthR)
if err != nil {
logger.Errorf("unmarshal depth response error %s[] , response data = %s", err, string(data))
return err
}
dep.UTime = time.Now()
dep.Pair = pair
for _, bid := range depthR.Bids {
dep.BidList = append(dep.BidList, goex.DepthRecord{
Price: goex.ToFloat64(bid[0]),
Amount: goex.ToFloat64(bid[1]),
})
}
for _, ask := range depthR.Asks {
dep.AskList = append(dep.AskList, goex.DepthRecord{
Price: goex.ToFloat64(ask[0]),
Amount: goex.ToFloat64(ask[1]),
})
}
sort.Sort(sort.Reverse(dep.AskList))
s.depthCallFn(&dep)
return nil
}
func (s *SpotWs) tickerHandle(data json2.RawMessage, pair goex.CurrencyPair) error {
var (
tickerData = make(map[string]interface{}, 4)
ticker goex.Ticker
)
err := json2.Unmarshal(data, &tickerData)
if err != nil {
logger.Errorf("unmarshal ticker response data error [%s] , data = %s", err, string(data))
return err
}
ticker.Pair = pair
ticker.Vol = goex.ToFloat64(tickerData["v"])
ticker.Last = goex.ToFloat64(tickerData["c"])
ticker.Sell = goex.ToFloat64(tickerData["a"])
ticker.Buy = goex.ToFloat64(tickerData["b"])
ticker.High = goex.ToFloat64(tickerData["h"])
ticker.Low = goex.ToFloat64(tickerData["l"])
ticker.Date = goex.ToUint64(tickerData["E"])
s.tickerCallFn(&ticker)
return nil
}