forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwapWs.go
218 lines (178 loc) · 5.23 KB
/
SwapWs.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package bitmex
import (
"encoding/json"
"fmt"
"sort"
"time"
. "github.com/soulsplit/goex"
"github.com/soulsplit/goex/internal/logger"
)
type SubscribeOp struct {
Op string `json:"op"`
Args []string `json:"args"`
}
type wsMessage struct {
Table string `json:"table"`
Action string `json:"action"`
Data json.RawMessage
}
type tickerData struct {
Symbol string `json:"symbol"`
MakerFee float64 `json:"makerFee"`
TakerFee float64 `json:"takerFee"`
LastPrice float64 `json:"lastPrice"`
HighPrice float64 `json:"highPrice"`
LowPrice float64 `json:"lowPrice"`
AskPrice float64 `json:"askPrice"`
BidPrice float64 `json:"bidPrice"`
HomeNotional24h float64 `json:"homeNotional24h"`
Turnover24h float64 `json:"turnover24h"`
Timestamp string `json:"timestamp"`
}
type depthData struct {
Symbol string `json:"symbol"`
Bids [][]interface{} `json:"bids"`
Asks [][]interface{} `json:"asks"`
Timestamp string `json:"timestamp"`
}
type SwapWs struct {
c *WsConn
depthCall func(depth *Depth)
tickerCall func(ticker *FutureTicker)
tickerCacheMap map[string]FutureTicker
}
func NewSwapWs() *SwapWs {
s := new(SwapWs)
wsBuilder := NewWsBuilder().DisableEnableCompression().WsUrl("wss://www.bitmex.com/realtime")
wsBuilder = wsBuilder.Heartbeat(func() []byte { return []byte("ping") }, 5*time.Second)
wsBuilder = wsBuilder.ProtoHandleFunc(s.handle).AutoReconnect()
s.c = wsBuilder.Build()
s.tickerCacheMap = make(map[string]FutureTicker, 10)
return s
}
func (s *SwapWs) DepthCallback(f func(depth *Depth)) {
s.depthCall = f
}
func (s *SwapWs) TickerCallback(f func(ticker *FutureTicker)) {
s.tickerCall = f
}
func (s *SwapWs) TradeCallback(f func(trade *Trade, contract string)) {
panic("implement me")
}
func (s *SwapWs) SubscribeDepth(pair CurrencyPair, contractType string) error {
//{"op": "subscribe", "args": ["orderBook10:XBTUSD"]}
op := SubscribeOp{
Op: "subscribe",
Args: []string{
fmt.Sprintf("orderBook10:%s", AdaptCurrencyPairToSymbol(pair, contractType)),
},
}
return s.c.Subscribe(op)
}
func (s *SwapWs) SubscribeTicker(pair CurrencyPair, contractType string) error {
return s.c.Subscribe(SubscribeOp{
Op: "subscribe",
Args: []string{
"instrument:" + AdaptCurrencyPairToSymbol(pair, contractType),
},
})
}
func (s *SwapWs) SubscribeTrade(pair CurrencyPair, contractType string) error {
panic("implement me")
}
func (s *SwapWs) handle(data []byte) error {
if string(data) == "pong" {
return nil
}
var msg wsMessage
err := json.Unmarshal(data, &msg)
if err != nil {
logger.Errorf("unmarshal error , message: %s", string(data))
return err
}
switch msg.Table {
case "orderBook10":
if msg.Action != "update" {
return nil
}
var (
depthData []depthData
dep Depth
)
err = json.Unmarshal(msg.Data, &depthData)
if err != nil {
logger.Errorf("unmarshal depth data error , data: %s", string(msg.Data))
return nil
}
if len(depthData) == 0 {
logger.Warn("depth data len==0 ??")
return nil
}
dep.UTime, _ = time.Parse(time.RFC3339, depthData[0].Timestamp)
dep.Pair, dep.ContractType = AdaptWsSymbol(depthData[0].Symbol)
for _, item := range depthData[0].Bids {
dep.BidList = append(dep.BidList, DepthRecord{
Price: ToFloat64(item[0]),
Amount: ToFloat64(item[1]),
})
}
for _, item := range depthData[0].Asks {
dep.AskList = append(dep.AskList, DepthRecord{
Price: ToFloat64(item[0]),
Amount: ToFloat64(item[1]),
})
}
sort.Sort(sort.Reverse(dep.AskList))
s.depthCall(&dep)
case "instrument":
var tickerData []tickerData
err = json.Unmarshal(msg.Data, &tickerData)
if err != nil {
logger.Errorf("ticker data unmarshal error , data: %s", string(msg.Data))
return err
}
if msg.Action == "partial" {
ticker := s.tickerCacheMap[tickerData[0].Symbol]
ticker.Ticker = new(Ticker)
ticker.Pair, ticker.ContractType = AdaptWsSymbol(tickerData[0].Symbol)
ticker.Vol = tickerData[0].HomeNotional24h
ticker.Last = tickerData[0].LastPrice
ticker.Sell = tickerData[0].AskPrice
ticker.Buy = tickerData[0].BidPrice
ticker.High = tickerData[0].HighPrice
ticker.Low = tickerData[0].LowPrice
tickerTime, _ := time.Parse(time.RFC3339, tickerData[0].Timestamp)
ticker.Date = uint64(tickerTime.Unix())
s.tickerCacheMap[tickerData[0].Symbol] = ticker
s.tickerCall(&ticker)
}
if msg.Action == "update" {
ticker := s.tickerCacheMap[tickerData[0].Symbol]
tickerTime, _ := time.Parse(time.RFC3339, tickerData[0].Timestamp)
ticker.Date = uint64(tickerTime.Unix())
if tickerData[0].LastPrice > 0 {
ticker.Last = tickerData[0].LastPrice
}
if tickerData[0].AskPrice > 0 {
ticker.Sell = tickerData[0].AskPrice
}
if tickerData[0].BidPrice > 0 {
ticker.Buy = tickerData[0].BidPrice
}
if tickerData[0].HighPrice > 0 {
ticker.High = tickerData[0].HighPrice
}
if tickerData[0].LowPrice > 0 {
ticker.Low = tickerData[0].LowPrice
}
if tickerData[0].HomeNotional24h > 0 {
ticker.Vol = tickerData[0].HomeNotional24h
}
s.tickerCacheMap[tickerData[0].Symbol] = ticker
s.tickerCall(&ticker)
}
default:
logger.Warnf("unknown ws message: %s", string(data))
}
return nil
}