-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhitbtc.go
474 lines (431 loc) · 12.2 KB
/
hitbtc.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package hitbtc
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
const (
API_BASE = "https://api.hitbtc.com/api/"
API_VERSION = "1"
API_MARKETS = "/public/symbols"
API_ORDERBOOK = "/public/%s/orderbook?format_price=number&format_amount=number&size=5"
API_PLACEORDER = "/trading/new_order"
API_CANCELORDER = "/trading/cancel_order"
API_CANCELORDERS = "/trading/cancel_orders"
API_TRADEBALANCE = "/trading/balance"
API_PAYMENTBALANCE = "/payment/balance"
API_ADDRESS = "/payment/address/%s"
API_TRANSACTIONS = "/payment/transactions"
API_TRANSACTION = "/payment/transactions/%s"
API_WITHDRAW = "/payment/payout"
API_TRANSFERTOMAIN = "/payment/transfer_to_main"
API_TRANSFERTOTRADING = "/payment/transfer_to_trading"
API_QUERYORDER = "/trading/order"
)
type Hitbtc struct {
httpClient client
}
func NewHitbtc(access, secret string) *Hitbtc {
return &Hitbtc{client{
apiKey: access,
apiSecret: secret,
httpClient: http.DefaultClient,
httpTimeout: time.Second * 30,
}}
}
/*
{
"symbols": [
{
"symbol": "BTCUSD",
"step": "0.01",
"lot": "0.01",
"currency": "USD",
"commodity": "BTC",
"takeLiquidityRate": "0.002",
"provideLiquidityRate": "0.002"
},
{
"symbol": "BTCEUR",
"step": "0.01",
"lot": "0.01",
"currency": "EUR",
"commodity": "BTC",
"takeLiquidityRate": "0.002",
"provideLiquidityRate": "0.002"
},
...
]
}
*/
func (h *Hitbtc) GetMarkets() (MarketsMap, error) {
r, err := h.httpClient.do("GET", API_MARKETS, "", false)
if err != nil {
return nil, err
}
var response Markets
if err = json.Unmarshal(r, &response); err != nil {
return nil, err
}
marketsMap := MarketsMap{}
for _, v := range response.Symbols {
marketsMap[v.Symbol] = v
}
return marketsMap, nil
}
/*
{
"asks": [
[ "405.71", "0.09" ],
[ "406.65", "0.06" ],
[ "409.51", "0.15" ],
[ "413.93", "51.6" ],
[ "414.59", "47.1" ]
],
"bids": [
[ "398.3", "0.15" ],
[ "396.99", "0.13" ],
[ "395", "0.5" ],
[ "391.93", "42.4" ],
[ "383.67", "145.4" ]
]
}
*/
func (h *Hitbtc) GetOrderBook(pair string) (*OrderBook, error) {
apiUrl := fmt.Sprintf(API_ORDERBOOK, pair)
r, err := h.httpClient.do("GET", apiUrl, "", false)
if err != nil {
fmt.Println(string(r))
return nil, err
}
var d map[string][][]float64
err = json.Unmarshal(r, &d)
orderBook := OrderBook{Buy: make([]OneOrderBook, 0), Sell: make([]OneOrderBook, 0)}
for _, buy := range d["bids"] {
oneOrder := OneOrderBook{Rate: buy[0], Quantity: buy[1]}
orderBook.Buy = append(orderBook.Buy, oneOrder)
}
for _, sell := range d["asks"] {
oneOrder := OneOrderBook{Rate: sell[0], Quantity: sell[1]}
orderBook.Sell = append(orderBook.Sell, oneOrder)
}
return &orderBook, err
}
/*
Parameter Required Type Description
clientOrderId Yes string Unique order ID generated by client. From 8 to 32 characters
symbol Yes string Currency symbol traded on HitBTC exchange (see Currency symbols), e.g. BTCUSD
side Yes buy or sell Side of a trade
price Yes - for limit orders decimal Order price
quantity No integer Order quantity in lots
type No limit, stopLimit, stopMarket, market Order type
timeInForce No GTC - Good-Til-Canceled
IOC - Immediate-Or-Cancel
FOK - Fill-Or-Kill
DAY - day Time in force. Default value - GTC
stopPrice Yes - for stopLimit, stopMarket string Stop price
{ "ExecutionReport":
{ "orderId": "58521038",
"clientOrderId": "11111112",
"execReportType": "new",
"orderStatus": "new",
"symbol": "BTCUSD",
"side": "buy",
"timestamp": 1395236779235,
"price": 0.1,
"quantity": 100,
"type": "limit",
"timeInForce": "GTC",
"lastQuantity": 0,
"lastPrice": 0,
"leavesQuantity": 100,
"cumQuantity": 0,
"averagePrice": 0 } }
*/
func (h *Hitbtc) BuyLimit(pair string, amount, price float64) (string, error) {
return h.placeOrder(pair, buy, amount, price)
}
func (h *Hitbtc) SellLimit(pair string, amount, price float64) (string, error) {
return h.placeOrder(pair, sell, amount, price)
}
func (h *Hitbtc) adjustPriceAmount(pair string, amount, price float64) (amountLots int, priceNew float64, err error) {
m, err := h.GetMarkets()
if err != nil {
return
}
// price = 0.09999991
// step = 0.01
// priceNew = 0.10
// lot = 0.001
// amount = 0.1
// amountLots = 100
mkt := m[pair]
amountLots = int(amount / mkt.Lot)
priceNew = float64(int64((1.0/mkt.Step)*price)) * mkt.Step
return
}
func (h *Hitbtc) placeOrder(pair string, side Side, amount, price float64) (string, error) {
amountLots, priceNew, err := h.adjustPriceAmount(pair, amount, price)
fmt.Printf("placeOrder(\"%s\",\"%s\",%.8f,%.8f)\n", pair, side, amount, price)
fmt.Printf("adjustPriceAmount(\"%s\",%.8f,%.8f) = %d,%.8f\n", pair, amount, price, amountLots, priceNew)
if err != nil {
return "", err
}
order := NewTradeLimitOrder(pair, side, amountLots, priceNew)
r, err := h.httpClient.do("POST", API_PLACEORDER, order.String(), true)
if err != nil {
fmt.Println(string(r))
return "", err
}
var response TradeResponseSuccess
err = json.Unmarshal(r, &response)
if err != nil {
fmt.Println(string(r))
return "", err
}
//fmt.Println(string(r))
if response.ExecutionReport.OrderStatus == "new" {
return response.ExecutionReport.ClientOrderId, nil
}
return "", fmt.Errorf("order status [%s] reason [%s]",
response.ExecutionReport.OrderStatus,
response.ExecutionReport.OrderRejectReason,
)
}
func (h *Hitbtc) GetOrder(orderID string) (*QueryOrder, error) {
order := NewQueryOrder(orderID)
r, err := h.httpClient.do("GET", API_QUERYORDER, order.String(), true)
if err != nil {
fmt.Println(string(r))
return nil, err
}
var response queryOrders
err = json.Unmarshal(r, &response)
if err != nil {
fmt.Println(string(r))
return nil, err
}
retOrders := &QueryOrder{Orders: make([]OneQueryOrder, 0)}
m, err := h.GetMarkets()
if err != nil {
return nil, err
}
for _, order := range response.Orders {
retOrders.Orders = append(retOrders.Orders,
OneQueryOrder{
OrderId: orderID,
Symbol: order.Symbol,
DealAmount: (order.OrderQuantity - order.QuantityLeaves) * m[order.Symbol].Lot,
RemainAmount: order.QuantityLeaves,
AvgPrice: order.AvgPrice,
},
)
}
return retOrders, nil
}
func (h *Hitbtc) CancelOrder(orderID string) error {
order := NewCancelOrder(orderID)
r, err := h.httpClient.do("POST", API_CANCELORDER, order.String(), true)
if err != nil {
fmt.Println(string(r))
return err
}
var rejected CancelOrderRejected
err = json.Unmarshal(r, &rejected)
if rejected.CancelReject.RejectReasonCode != "" {
return fmt.Errorf("CancelOrder %s error %s", orderID, rejected.CancelReject.RejectReasonCode)
}
var response TradeResponseSuccess
err = json.Unmarshal(r, &response)
if err != nil {
fmt.Println(string(r))
return err
}
//fmt.Println(string(r))
return nil
}
func (h *Hitbtc) CancelOrders(pair string) error {
order := NewCancelOrders(pair)
r, err := h.httpClient.do("POST", API_CANCELORDERS, order.String(), true)
if err != nil {
fmt.Println(string(r))
return err
}
var response TradeMultiResponseSuccess
err = json.Unmarshal(r, &response)
if err != nil {
fmt.Println(string(r))
return err
}
return nil
}
func (h *Hitbtc) GetTradeBalance() (*TradeBalance, error) {
r, err := h.httpClient.do("GET", API_TRADEBALANCE, "", true)
if err != nil {
fmt.Println(string(r))
return nil, err
}
var response TradeBalance
err = json.Unmarshal(r, &response)
if err != nil {
fmt.Println(string(r))
return nil, err
}
return &response, nil
}
func (h *Hitbtc) GetPaymentBalance() (*PaymentBalance, error) {
r, err := h.httpClient.do("GET", API_PAYMENTBALANCE, "", true)
if err != nil {
fmt.Println(string(r))
return nil, err
}
var response PaymentBalance
err = json.Unmarshal(r, &response)
//fmt.Println(string(r))
if err != nil {
return nil, err
}
return &response, nil
}
func (h *Hitbtc) transfer(coin string, amount float64, isTomain bool) error {
api := API_TRANSFERTOTRADING
if isTomain {
api = API_TRANSFERTOMAIN
}
order := NewTransferRequest(coin, amount)
r, err := h.httpClient.do("POST", api, order.String(), true)
if err != nil {
fmt.Println(string(r))
return err
}
var response map[string]string = make(map[string]string)
err = json.Unmarshal(r, &response)
if err != nil {
return err
}
return nil
}
func (h *Hitbtc) TransferToMain(coin string, amount float64) error {
return h.transfer(coin, amount, true)
}
func (h *Hitbtc) TransferToTrading(coin string, amount float64) error {
return h.transfer(coin, amount, false)
}
func (h *Hitbtc) Withdraw(coin string, amount float64, address, paymentID string) (string, error) {
order := NewWithdrawRequest(coin, amount, address, paymentID)
r, err := h.httpClient.do("POST", API_WITHDRAW, order.String(), true)
if err != nil {
fmt.Println(string(r))
return "", err
}
var response map[string]string = make(map[string]string)
err = json.Unmarshal(r, &response)
if err != nil {
return "", err
}
return response["transaction"], nil
}
func (h *Hitbtc) GetTransaction(transactionID string) (*OneDepositWithdrawal, error) {
api := fmt.Sprintf(API_TRANSACTION, transactionID)
r, err := h.httpClient.do("GET", api, "id="+transactionID, true)
if err != nil {
return nil, err
}
var response struct {
Transaction OneTransaction `json:"transaction"`
}
err = json.Unmarshal(r, &response)
//fmt.Println(string(r))
if err != nil {
fmt.Println(string(r))
return nil, err
}
return &OneDepositWithdrawal{
Id: response.Transaction.Id,
Coin: response.Transaction.CurrencyCodeTo,
Amount: response.Transaction.AmountFrom,
Created: time.Unix(response.Transaction.Created, 0),
Finished: time.Unix(response.Transaction.Finished, 0),
IsDone: response.Transaction.Status != "pending",
}, nil
}
func (h *Hitbtc) GetDepositWithdrawal(coin string, offset, limit int) (*DepositWithdrawal, int, error) {
if limit <= 0 {
limit = 100
}
if offset < 0 {
offset = 0
}
api := fmt.Sprintf(API_TRANSACTIONS)
fmt.Println(api)
r, err := h.httpClient.do("GET", api, fmt.Sprintf("limit=%d&offset=%d", limit, offset), true)
if err != nil {
fmt.Println(string(r))
return nil, 0, err
}
var response Transaction
err = json.Unmarshal(r, &response)
//fmt.Println(string(r))
if err != nil {
fmt.Println(string(r))
return nil, 0, err
}
var depositWithdrawal DepositWithdrawal = DepositWithdrawal{
Deposit: make([]OneDepositWithdrawal, 0),
Withdraw: make([]OneDepositWithdrawal, 0),
}
for _, oneTran := range response.Transactions {
if oneTran.Type == "payin" {
if oneTran.CurrencyCodeTo == coin {
depositWithdrawal.Deposit = append(depositWithdrawal.Deposit,
OneDepositWithdrawal{
Id: oneTran.Id,
Coin: oneTran.CurrencyCodeTo,
Amount: oneTran.AmountFrom,
Created: time.Unix(oneTran.Created, 0),
Finished: time.Unix(oneTran.Finished, 0),
IsDone: oneTran.Status != "pending",
},
)
}
} else {
if oneTran.CurrencyCodeFrom == coin {
depositWithdrawal.Withdraw = append(depositWithdrawal.Withdraw,
OneDepositWithdrawal{
Id: oneTran.Id,
Coin: oneTran.CurrencyCodeFrom,
Amount: oneTran.AmountTo,
Created: time.Unix(oneTran.Created, 0),
Finished: time.Unix(oneTran.Finished, 0),
IsDone: oneTran.Status != "pending",
Address: oneTran.ExternalData,
},
)
}
}
}
return &depositWithdrawal, len(response.Transactions), nil
}
func (h *Hitbtc) GetDepositAddress(coin string) (string, error) {
api := fmt.Sprintf(API_ADDRESS, coin)
r, err := h.httpClient.do("GET", api, "", true)
if err != nil {
fmt.Println(string(r))
return "", err
}
var response map[string]string = make(map[string]string)
err = json.Unmarshal(r, &response)
fmt.Println(string(r))
if err != nil {
return "", err
}
return response["address"], nil
}
func (h *Hitbtc) WalletValid(coin string) bool {
_, err := h.GetDepositAddress(coin)
if err != nil {
return false
}
return true
}