-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
336 lines (300 loc) · 6.44 KB
/
client.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package hitbtc
import (
"container/list"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"sync"
"time"
"github.com/gorilla/websocket"
)
const (
BUY = "buy"
SELL = "sell"
IOC = "IOC"
GTC = "GTC"
FOK = "FOK"
)
type BalanceItem = [2]float64
type BookItem = [2]float64
type Orderbook struct {
Seq float64
TS time.Time
Asks []BookItem
Bids []BookItem
}
type Client struct {
APIKey string
SecretKey string
Symbols map[string]Symbol
MaxBookDepth int
Workers int
BookWorkers int
balance map[string]BalanceItem
books map[string]*Orderbook
bookLock sync.RWMutex
bookUpdates chan []byte
deferedBooks map[string]*list.List
incoming chan []byte
orders map[string]*Order
orderLock sync.RWMutex
requests map[string]string
subscriptions *list.List
tickers map[string]*Ticker
tickerLock sync.RWMutex
ws *websocket.Conn
}
type JSONMap = map[string]interface{}
type Symbol struct {
ID string `json:"id"`
BaseCurrency string `json:"baseCurrency"`
QuoteCurrency string `json:"quoteCurrency"`
QuantityIncrement float64 `json:"quantityIncrement"`
TickSize float64 `json:"tickSize"`
TakeLiquidityRate float64 `json:"takeLiquidityRate"`
ProvideLiquidityRate float64 `json:"provideLiquidityRate"`
FeeCurrency string `json:"feeCurrency"`
}
type Order struct {
Symbol string
ClientOrderID string
Side string
Status string
Type string
Quantity float64
Price float64
CumQuantity float64
TradeQuantity float64
TradePrice float64
TradeFee float64
}
type Ticker struct {
Ask float64
Bid float64
TS time.Time
}
func NewClient() *Client {
return &Client{
Symbols: make(map[string]Symbol),
MaxBookDepth: 10,
Workers: 1,
BookWorkers: 2,
incoming: make(chan []byte, 200),
bookUpdates: make(chan []byte, 100),
requests: make(map[string]string),
subscriptions: list.New(),
tickers: make(map[string]*Ticker),
books: make(map[string]*Orderbook),
balance: make(map[string]BalanceItem),
deferedBooks: make(map[string]*list.List),
orders: make(map[string]*Order),
}
}
func (C *Client) Login() {
if len(C.APIKey) == 0 {
return
}
log.Printf("Login with key [%s]\n", C.APIKey)
nonce := newID()
h := hmac.New(sha256.New, []byte(C.SecretKey))
h.Write([]byte(nonce))
C.send(basicRequest{
Method: "login",
ID: newID(),
Params: paramsLogin{
Algo: "HS256",
PKey: C.APIKey,
Nonce: nonce,
Signature: hex.EncodeToString(h.Sum(nil)),
},
})
}
func (C *Client) Reconnect() {
loopreconnect:
if C.ws != nil {
C.ws.Close()
}
log.Println("Connecting...")
for {
dialer := websocket.Dialer{
ReadBufferSize: 40960,
}
c, _, err := dialer.Dial("wss://api.hitbtc.com/api/2/ws", nil)
if err != nil {
log.Println(err)
time.Sleep(5 * time.Second)
C.ws = nil
} else {
C.ws = c
break
}
}
C.Login()
for e := C.subscriptions.Front(); e != nil; e = e.Next() {
req := e.Value.(basicRequest)
req.ID = newID()
log.Println("Resubscribe ", req)
if err := C.send(req); err != nil {
log.Println(err)
goto loopreconnect
}
}
}
func (C *Client) Run() {
C.Reconnect()
go C.read()
for i := 0; i < C.BookWorkers; i++ {
C.workerUpdateOrderbook()
}
for i := 0; i < C.Workers; i++ {
go C.worker()
}
}
func (C *Client) GetActiveOrders() {
id := newID()
C.requests[id] = "getOrders"
C.send(basicRequest{
Method: "getOrders",
ID: id,
Params: noParams{},
})
}
func (C *Client) GetBalance() {
id := newID()
C.requests[id] = "getTradingBalance"
C.send(basicRequest{
Method: "getTradingBalance",
ID: id,
Params: noParams{},
})
}
func (C *Client) GetSymbols() {
id := newID()
C.requests[id] = "getSymbols"
C.send(basicRequest{
Method: "getSymbols",
ID: id,
Params: noParams{},
})
}
func (C *Client) SubscribeTickers(symbols []string) {
for _, symbol := range symbols {
C.SubscribeTicker(symbol)
}
}
func (C *Client) SubscribeTicker(symbol string) {
req := basicRequest{
Method: "subscribeTicker",
ID: newID(),
Params: paramsSymbol{
Symbol: symbol,
},
}
C.subscriptions.PushBack(req)
C.send(req)
}
func (C *Client) SubscribeReports() {
req := basicRequest{
Method: "subscribeReports",
ID: newID(),
Params: noParams{},
}
C.subscriptions.PushBack(req)
C.send(req)
}
func (C *Client) SubscribeBooks(symbols []string) {
for _, symbol := range symbols {
C.SubscribeBook(symbol)
}
}
func (C *Client) SubscribeBook(symbol string) {
req := basicRequest{
Method: "subscribeOrderbook",
ID: newID(),
Params: paramsSymbol{
Symbol: symbol,
},
}
C.subscriptions.PushBack(req)
C.send(req)
}
func (C *Client) PlaceLimit(symbol string, price float64, quantity float64, side string, tif string) string {
coid := newID()
id := newID()
C.send(basicRequest{
Method: "newOrder",
ID: id,
Params: paramsOrder{
Symbol: symbol,
Side: side,
Type: "limit",
TimeInForce: tif,
ClientOrderID: coid,
Price: fmt.Sprintf("%.12f", price),
Quantity: fmt.Sprintf("%.12f", quantity),
},
})
return coid
}
func (C *Client) UpdateOrder(coid string, price float64, quantity float64) string {
newcoid := newID()
C.send(basicRequest{
Method: "cancelReplaceOrder",
ID: newID(),
Params: paramsOrder{
RequestOrderID: newcoid,
ClientOrderID: coid,
Price: fmt.Sprintf("%.12f", price),
Quantity: fmt.Sprintf("%.12f", quantity),
},
})
return newcoid
}
func (C *Client) CancelOrder(coid string) {
C.send(basicRequest{
Method: "cancelOrder",
ID: newID(),
Params: paramsOrder{
ClientOrderID: coid,
},
})
}
func (C *Client) Balance(symbol string) BalanceItem {
b, ok := C.balance[symbol]
if !ok {
return BalanceItem{0.0, 0.0}
}
return b
}
func (C *Client) Book(symbol string) *Orderbook {
defer C.bookLock.RUnlock()
C.bookLock.RLock()
b, ok := C.books[symbol]
if !ok {
return nil
}
ret := Orderbook(*b)
return &ret
}
func (C *Client) Order(coid string) *Order {
defer C.orderLock.RUnlock()
C.orderLock.RLock()
o, ok := C.orders[coid]
if !ok {
return nil
}
ret := Order(*o)
return &ret
}
func (C *Client) Ticker(symbol string) *Ticker {
defer C.tickerLock.RUnlock()
C.tickerLock.RLock()
t, ok := C.tickers[symbol]
if !ok {
return nil
}
ret := Ticker(*t)
return &ret
}