-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinternal.go
291 lines (258 loc) · 6.71 KB
/
internal.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package hitbtc
import (
"container/list"
"log"
"time"
jsoniter "github.com/json-iterator/go"
)
type basicRequest struct {
ID string `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
type paramsLogin struct {
Algo string `json:"algo"`
Nonce string `json:"nonce"`
Signature string `json:"signature"`
PKey string `json:"pKey"`
}
type paramsOrder struct {
ClientOrderID string `json:"clientOrderId"`
RequestOrderID string `json:"requestClientId"`
Symbol string `json:"symbol"`
Side string `json:"side"`
Type string `json:"type"`
TimeInForce string `json:"timeInForce"`
Quantity string `json:"quantity"`
Price string `json:"price"`
}
type noParams struct{}
type paramsSymbol struct {
Symbol string `json:"symbol"`
}
type responseCatcher struct {
Method string
Channel *chan int
}
type responseBalance struct {
Currency string `json:"currency"`
Available string `json:"available"`
Reserved string `json:"reserved"`
}
type responseOrder struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
ClientOrderID string `json:"clientOrderId"`
Side string `json:"side"`
Status string `json:"status"`
Type string `json:"type"`
Quantity string `json:"quantity"`
Price string `json:"price"`
CumQuantity string `json:"cumQuantity"`
TradeQuantity string `json:"tradeQuantity"`
TradePrice string `json:"tradePrice"`
TradeFee string `json:"tradeFee"`
}
type responseOrderbook struct {
Symbol string `json:"symbol"`
Sequence int `json:"sequence"`
Ask []responseOrderbookItem `json:"ask"`
Bid []responseOrderbookItem `json:"bid"`
}
type responseOrderbookItem struct {
Price string `json:"price"`
Size string `json:"size"`
}
type responseSymbol struct {
ID string `json:"id"`
BaseCurrency string `json:"baseCurrency"`
QuoteCurrency string `json:"quoteCurrency"`
QuantityIncrement string `json:"quantityIncrement"`
TickSize string `json:"tickSize"`
TakeLiquidityRate string `json:"takeLiquidityRate"`
ProvideLiquidityRate string `json:"provideLiquidityRate"`
FeeCurrency string `json:"feeCurrency"`
}
type responseTicker struct {
Ask string `json:"ask"`
Bid string `json:"bid"`
Symbol string `json:"symbol"`
}
func (C *Client) read() {
for {
_, msg, err := C.ws.ReadMessage()
if err != nil {
log.Println(err)
C.Reconnect()
continue
}
C.incoming <- msg
}
}
func (C *Client) send(payload interface{}) error {
if err := C.ws.WriteJSON(payload); err != nil {
log.Println(err)
return err
}
return nil
}
func (C *Client) CopyBooks(depth int) map[string]*Orderbook {
res := make(map[string]*Orderbook)
C.bookLock.RLock()
for k, v := range C.books {
if len(v.Asks) < depth || len(v.Bids) < depth {
res[k] = nil
continue
}
res[k] = &Orderbook{
Asks: v.Asks[:depth],
Bids: v.Bids[:depth],
TS: v.TS,
}
}
C.bookLock.RUnlock()
return res
}
func (C *Client) worker() {
var id, method, err string
for {
select {
case msg := <-C.incoming:
method = jsoniter.Get(msg, "method").ToString()
if len(method) != 0 {
if method == "ticker" {
C.handleTicker(msg)
} else if method == "snapshotOrderbook" {
C.handleSnapshotOrderbook(msg)
} else if method == "updateOrderbook" {
C.bookUpdates <- msg
} else if method == "report" {
log.Println(string(msg))
resp := responseOrder{}
jsoniter.Get(msg, "params").ToVal(&resp)
C.handleOrdersReport(resp)
}
continue
}
id = jsoniter.Get(msg, "id").ToString()
err = jsoniter.Get(msg, "error").ToString()
if len(err) != 0 {
log.Println("err", string(msg))
}
if req, ok := C.requests[id]; ok {
if len(err) == 0 {
if req == "getSymbols" {
C.handleGetSymbols(msg)
} else if req == "getTradingBalance" {
C.handleGetBalance(msg)
} else if req == "getOrders" {
C.handleGetActiveOrders(msg)
}
}
delete(C.requests, id)
}
}
}
}
func (C *Client) workerUpdateOrderbook() {
for i := 0; i < 2; i++ {
go func() {
for {
resp := <-C.bookUpdates
C.handleUpdateOrderbook(resp)
}
}()
}
}
func (C *Client) handleOrdersReport(resp responseOrder) {
defer C.orderLock.Unlock()
coid := resp.ClientOrderID
C.orderLock.Lock()
C.orders[coid] = &Order{
ClientOrderID: coid,
Symbol: resp.Symbol,
Side: resp.Side,
Status: resp.Status,
Type: resp.Type,
Quantity: stf(resp.Quantity),
CumQuantity: stf(resp.CumQuantity),
Price: stf(resp.Price),
TradePrice: stf(resp.TradePrice),
TradeQuantity: stf(resp.TradeQuantity),
TradeFee: stf(resp.TradeFee),
}
}
func (C *Client) handleSnapshotOrderbook(msg []byte) {
defer C.bookLock.Unlock()
resp := responseOrderbook{}
jsoniter.Get(msg, "params").ToVal(&resp)
book, symbol := parseBook(resp, C.MaxBookDepth)
C.bookLock.Lock()
C.books[symbol] = book
C.deferedBooks[symbol] = list.New()
}
func (C *Client) handleUpdateOrderbook(msg []byte) {
defer C.bookLock.Unlock()
resp := responseOrderbook{}
jsoniter.Get(msg, "params").ToVal(&resp)
update, symbol := parseBook(resp, 0)
C.bookLock.Lock()
book, _ := C.books[symbol]
defered, _ := C.deferedBooks[symbol]
defered.PushBack(update)
if book == nil {
return
}
for u := defered.Front(); u != nil; {
if book.Seq+1 == u.Value.(*Orderbook).Seq {
mergeBook(book, u.Value.(*Orderbook), C.MaxBookDepth)
defered.Remove(u)
u = defered.Front()
} else {
u = u.Next()
}
}
}
func (C *Client) handleGetActiveOrders(msg []byte) {
o := make([]responseOrder, 0, 1)
log.Println(string(msg))
jsoniter.Get(msg, "result").ToVal(&o)
for _, v := range o {
C.handleOrdersReport(v)
}
}
func (C *Client) handleGetSymbols(msg []byte) {
s := make([]responseSymbol, 0, 1)
jsoniter.Get(msg, "result").ToVal(&s)
for _, v := range s {
C.Symbols[v.ID] = Symbol{
BaseCurrency: v.BaseCurrency,
QuoteCurrency: v.QuoteCurrency,
QuantityIncrement: stf(v.QuantityIncrement),
FeeCurrency: v.FeeCurrency,
ProvideLiquidityRate: stf(v.ProvideLiquidityRate),
TickSize: stf(v.TickSize),
}
}
}
func (C *Client) handleGetBalance(msg []byte) {
b := make([]responseBalance, 0, 1)
jsoniter.Get(msg, "result").ToVal(&b)
for _, v := range b {
C.balance[v.Currency] = BalanceItem{
stf(v.Available),
stf(v.Reserved),
}
}
}
func (C *Client) handleTicker(msg []byte) {
defer C.tickerLock.Unlock()
t := responseTicker{}
jsoniter.Get(msg, "params").ToVal(&t)
C.tickerLock.Lock()
C.tickers[t.Symbol] = &Ticker{
Ask: stf(t.Ask),
Bid: stf(t.Bid),
TS: time.Now(),
}
}