forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
huobi_websocket.go
237 lines (204 loc) · 7.07 KB
/
huobi_websocket.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package huobi
import (
"log"
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/socketio"
)
const (
huobiSocketIOAddress = "https://hq.huobi.com:443"
//Service API
huobiSocketReqSymbolList = "reqSymbolList"
huobiSocketReqSymbolDetail = "reqSymbolDetail"
huobiSocketReqSubscribe = "reqMsgSubscribe"
huobiSocketReqUnsubscribe = "reqMsgUnsubscribe"
// Market data API
huobiSocketMarketDetail = "marketDetail"
huobiSocketTradeDetail = "tradeDetail"
huobiSocketMarketDepthTop = "marketDepthTop"
huobiSocketMarketDepthTopShort = "marketDepthTopShort"
huobiSocketMarketDepth = "marketDepth"
huobiSocketMarketDepthTopDiff = "marketDepthTopDiff"
huobiSocketMarketDepthDiff = "marketDepthDiff"
huobiSocketMarketLastKline = "lastKLine"
huobiSocketMarketLastTimeline = "lastTimeLine"
huobiSocketMarketOverview = "marketOverview"
huobiSocketMarketStatic = "marketStatic"
// History data API
huobiSocketReqTimeline = "reqTimeLine"
huobiSocketReqKline = "reqKLine"
huobiSocketReqDepthTop = "reqMarketDepthTop"
huobiSocketReqDepth = "reqMarketDepth"
huobiSocketReqTradeDetailTop = "reqTradeDetailTop"
huobiSocketReqMarketDetail = "reqMarketDetail"
)
// HuobiSocket is a pointer to a IO Socket
var HuobiSocket *socketio.SocketIO
// Depth holds depth information
type Depth struct {
SymbolID string `json:"symbolId"`
Time float64 `json:"time"`
Version float64 `json:"version"`
BidName string `json:"bidName"`
BidPrice []float64 `json:"bidPrice"`
BidTotal []float64 `json:"bidTotal"`
BidAmount []float64 `json:"bidAmount"`
AskName string `json:"askName"`
AskPrice []float64 `json:"askPrice"`
AskTotal []float64 `json:"askTotal"`
AskAmount []float64 `json:"askAmount"`
}
// WebsocketTrade holds full trade data
type WebsocketTrade struct {
Price []float64 `json:"price"`
Level []float64 `json:"level"`
Amount []float64 `json:"amount"`
AccuAmount []float64 `json:"accuAmount"`
}
// WebsocketTradeDetail holds specific trade details
type WebsocketTradeDetail struct {
SymbolID string `json:"symbolId"`
TradeID []int64 `json:"tradeId"`
Price []float64 `json:"price"`
Time []int64 `json:"time"`
Amount []float64 `json:"amount"`
TopBids []WebsocketTrade `json:"topBids"`
TopAsks []WebsocketTrade `json:"topAsks"`
}
// WebsocketMarketOverview holds market overview data
type WebsocketMarketOverview struct {
SymbolID string `json:"symbolId"`
Last float64 `json:"priceNew"`
Open float64 `json:"priceOpen"`
High float64 `json:"priceHigh"`
Low float64 `json:"priceLow"`
Ask float64 `json:"priceAsk"`
Bid float64 `json:"priceBid"`
Volume float64 `json:"totalVolume"`
TotalAmount float64 `json:"totalAmount"`
}
// WebsocketLastTimeline holds timeline data
type WebsocketLastTimeline struct {
ID int64 `json:"_id"`
SymbolID string `json:"symbolId"`
Time int64 `json:"time"`
LastPrice float64 `json:"priceLast"`
Amount float64 `json:"amount"`
Volume float64 `json:"volume"`
Count int64 `json:"count"`
}
// WebsocketResponse is a general response type for websocket
type WebsocketResponse struct {
Version int `json:"version"`
MsgType string `json:"msgType"`
RequestIndex int64 `json:"requestIndex"`
RetCode int64 `json:"retCode"`
RetMessage string `json:"retMsg"`
Payload map[string]interface{} `json:"payload"`
}
// BuildHuobiWebsocketRequest packages a new request
func (h *HUOBI) BuildHuobiWebsocketRequest(msgType string, requestIndex int64, symbolRequest []string) map[string]interface{} {
request := map[string]interface{}{}
request["version"] = 1
request["msgType"] = msgType
if requestIndex != 0 {
request["requestIndex"] = requestIndex
}
if len(symbolRequest) != 0 {
request["symbolIdList"] = symbolRequest
}
return request
}
// BuildHuobiWebsocketRequestExtra packages an extra request
func (h *HUOBI) BuildHuobiWebsocketRequestExtra(msgType string, requestIndex int64, symbolIDList interface{}) interface{} {
request := map[string]interface{}{}
request["version"] = 1
request["msgType"] = msgType
if requestIndex != 0 {
request["requestIndex"] = requestIndex
}
request["symbolList"] = symbolIDList
return request
}
// BuildHuobiWebsocketParamsList packages a parameter list
func (h *HUOBI) BuildHuobiWebsocketParamsList(objectName, currency, pushType, period, count, from, to, percentage string) interface{} {
list := map[string]interface{}{}
list["symbolId"] = currency
list["pushType"] = pushType
if period != "" {
list["period"] = period
}
if percentage != "" {
list["percent"] = percentage
}
if count != "" {
list["count"] = count
}
if from != "" {
list["from"] = from
}
if to != "" {
list["to"] = to
}
listArray := []map[string]interface{}{}
listArray = append(listArray, list)
listCompleted := make(map[string][]map[string]interface{})
listCompleted[objectName] = listArray
return listCompleted
}
// OnConnect handles connection establishment
func (h *HUOBI) OnConnect(output chan socketio.Message) {
if h.Verbose {
log.Printf("%s Connected to Websocket.", h.GetName())
}
for _, x := range h.EnabledPairs {
currency := common.StringToLower(x)
msg := h.BuildHuobiWebsocketRequestExtra(huobiSocketReqSubscribe, 100, h.BuildHuobiWebsocketParamsList(huobiSocketMarketOverview, currency, "pushLong", "", "", "", "", ""))
result, err := common.JSONEncode(msg)
if err != nil {
log.Println(err)
}
output <- socketio.CreateMessageEvent("request", string(result), nil, HuobiSocket.Version)
}
}
// OnDisconnect handles disconnection
func (h *HUOBI) OnDisconnect(output chan socketio.Message) {
log.Printf("%s Disconnected from websocket server.. Reconnecting.\n", h.GetName())
h.WebsocketClient()
}
// OnError handles error issues
func (h *HUOBI) OnError() {
log.Printf("%s Error with Websocket connection.. Reconnecting.\n", h.GetName())
h.WebsocketClient()
}
// OnMessage handles messages from the exchange
func (h *HUOBI) OnMessage(message []byte, output chan socketio.Message) {
}
// OnRequest handles requests
func (h *HUOBI) OnRequest(message []byte, output chan socketio.Message) {
response := WebsocketResponse{}
err := common.JSONDecode(message, &response)
if err != nil {
log.Println(err)
}
}
// WebsocketClient creates a new websocket client
func (h *HUOBI) WebsocketClient() {
events := make(map[string]func(message []byte, output chan socketio.Message))
events["request"] = h.OnRequest
events["message"] = h.OnMessage
HuobiSocket = &socketio.SocketIO{
Version: 0.9,
OnConnect: h.OnConnect,
OnEvent: events,
OnError: h.OnError,
OnDisconnect: h.OnDisconnect,
}
for h.Enabled && h.Websocket {
err := socketio.ConnectToSocket(huobiSocketIOAddress, HuobiSocket)
if err != nil {
log.Printf("%s Unable to connect to Websocket. Err: %s\n", h.GetName(), err)
continue
}
log.Printf("%s Disconnected from Websocket.\n", h.GetName())
}
}