forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Zb.go
450 lines (369 loc) · 11.2 KB
/
Zb.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
package zb
import (
"encoding/json"
"errors"
"fmt"
. "github.com/nntaoli-project/GoEx"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
MARKET_URL = "http://api.zb.com/data/v1/"
TICKER_API = "ticker?market=%s"
DEPTH_API = "depth?market=%s&size=%d"
TRADE_URL = "https://trade.zb.com/api/"
GET_ACCOUNT_API = "getAccountInfo"
GET_ORDER_API = "getOrder"
GET_UNFINISHED_ORDERS_API = "getUnfinishedOrdersIgnoreTradeType"
CANCEL_ORDER_API = "cancelOrder"
PLACE_ORDER_API = "order"
WITHDRAW_API = "withdraw"
CANCELWITHDRAW_API = "cancelWithdraw"
)
type Zb struct {
httpClient *http.Client
accessKey,
secretKey string
}
func New(httpClient *http.Client, accessKey, secretKey string) *Zb {
return &Zb{httpClient, accessKey, secretKey}
}
func (zb *Zb) GetExchangeName() string {
return ZB
}
func (zb *Zb) GetTicker(currency CurrencyPair) (*Ticker, error) {
symbol := currency.AdaptBchToBcc().AdaptUsdToUsdt().ToSymbol("_")
resp, err := HttpGet(zb.httpClient, MARKET_URL+fmt.Sprintf(TICKER_API, symbol))
if err != nil {
return nil, err
}
//log.Println(resp)
tickermap := resp["ticker"].(map[string]interface{})
ticker := new(Ticker)
ticker.Pair = currency
ticker.Date, _ = strconv.ParseUint(resp["date"].(string), 10, 64)
ticker.Buy, _ = strconv.ParseFloat(tickermap["buy"].(string), 64)
ticker.Sell, _ = strconv.ParseFloat(tickermap["sell"].(string), 64)
ticker.Last, _ = strconv.ParseFloat(tickermap["last"].(string), 64)
ticker.High, _ = strconv.ParseFloat(tickermap["high"].(string), 64)
ticker.Low, _ = strconv.ParseFloat(tickermap["low"].(string), 64)
ticker.Vol, _ = strconv.ParseFloat(tickermap["vol"].(string), 64)
return ticker, nil
}
func (zb *Zb) GetDepth(size int, currency CurrencyPair) (*Depth, error) {
symbol := currency.AdaptBchToBcc().AdaptUsdToUsdt().ToSymbol("_")
resp, err := HttpGet(zb.httpClient, MARKET_URL+fmt.Sprintf(DEPTH_API, symbol, size))
if err != nil {
return nil, err
}
//log.Println(resp)
asks, isok1 := resp["asks"].([]interface{})
bids, isok2 := resp["bids"].([]interface{})
if isok2 != true || isok1 != true {
return nil, errors.New("no depth data!")
}
//log.Println(asks)
//log.Println(bids)
depth := new(Depth)
depth.Pair = currency
for _, e := range bids {
var r DepthRecord
ee := e.([]interface{})
r.Amount = ee[1].(float64)
r.Price = ee[0].(float64)
depth.BidList = append(depth.BidList, r)
}
for _, e := range asks {
var r DepthRecord
ee := e.([]interface{})
r.Amount = ee[1].(float64)
r.Price = ee[0].(float64)
depth.AskList = append(depth.AskList, r)
}
return depth, nil
}
func (zb *Zb) buildPostForm(postForm *url.Values) error {
postForm.Set("accesskey", zb.accessKey)
payload := postForm.Encode()
secretkeySha, _ := GetSHA(zb.secretKey)
sign, err := GetParamHmacMD5Sign(secretkeySha, payload)
if err != nil {
return err
}
postForm.Set("sign", sign)
//postForm.Del("secret_key")
postForm.Set("reqTime", fmt.Sprintf("%d", time.Now().UnixNano()/1000000))
return nil
}
func (zb *Zb) GetAccount() (*Account, error) {
params := url.Values{}
params.Set("method", "getAccountInfo")
zb.buildPostForm(¶ms)
//log.Println(params.Encode())
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+GET_ACCOUNT_API, params)
if err != nil {
return nil, err
}
var respmap map[string]interface{}
err = json.Unmarshal(resp, &respmap)
if err != nil {
log.Println("json unmarshal error")
return nil, err
}
if respmap["code"] != nil && respmap["code"].(float64) != 1000 {
return nil, errors.New(string(resp))
}
acc := new(Account)
acc.Exchange = zb.GetExchangeName()
acc.SubAccounts = make(map[Currency]SubAccount)
resultmap := respmap["result"].(map[string]interface{})
coins := resultmap["coins"].([]interface{})
acc.NetAsset = ToFloat64(resultmap["netAssets"])
acc.Asset = ToFloat64(resultmap["totalAssets"])
for _, v := range coins {
vv := v.(map[string]interface{})
subAcc := SubAccount{}
subAcc.Amount = ToFloat64(vv["available"])
subAcc.ForzenAmount = ToFloat64(vv["freez"])
subAcc.Currency = NewCurrency(vv["key"].(string), "").AdaptBchToBcc()
acc.SubAccounts[subAcc.Currency] = subAcc
}
//log.Println(string(resp))
//log.Println(acc)
return acc, nil
}
func (zb *Zb) placeOrder(amount, price string, currency CurrencyPair, tradeType int) (*Order, error) {
symbol := currency.AdaptBchToBcc().AdaptUsdToUsdt().ToSymbol("_")
params := url.Values{}
params.Set("method", "order")
params.Set("price", price)
params.Set("amount", amount)
params.Set("currency", symbol)
params.Set("tradeType", fmt.Sprintf("%d", tradeType))
zb.buildPostForm(¶ms)
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+PLACE_ORDER_API, params)
if err != nil {
log.Println(err)
return nil, err
}
//log.Println(string(resp));
respmap := make(map[string]interface{})
err = json.Unmarshal(resp, &respmap)
if err != nil {
log.Println(err)
return nil, err
}
code := respmap["code"].(float64)
if code != 1000 {
log.Println(string(resp))
return nil, errors.New(fmt.Sprintf("%.0f", code))
}
orid := respmap["id"].(string)
order := new(Order)
order.Amount, _ = strconv.ParseFloat(amount, 64)
order.Price, _ = strconv.ParseFloat(price, 64)
order.Status = ORDER_UNFINISH
order.Currency = currency
order.OrderTime = int(time.Now().UnixNano() / 1000000)
order.OrderID, _ = strconv.Atoi(orid)
switch tradeType {
case 0:
order.Side = SELL
case 1:
order.Side = BUY
}
return order, nil
}
func (zb *Zb) LimitBuy(amount, price string, currency CurrencyPair) (*Order, error) {
return zb.placeOrder(amount, price, currency, 1)
}
func (zb *Zb) LimitSell(amount, price string, currency CurrencyPair) (*Order, error) {
return zb.placeOrder(amount, price, currency, 0)
}
func (zb *Zb) CancelOrder(orderId string, currency CurrencyPair) (bool, error) {
symbol := currency.AdaptBchToBcc().AdaptUsdToUsdt().ToSymbol("_")
params := url.Values{}
params.Set("method", "cancelOrder")
params.Set("id", orderId)
params.Set("currency", symbol)
zb.buildPostForm(¶ms)
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+CANCEL_ORDER_API, params)
if err != nil {
log.Println(err)
return false, err
}
respmap := make(map[string]interface{})
err = json.Unmarshal(resp, &respmap)
if err != nil {
log.Println(err)
return false, err
}
code := respmap["code"].(float64)
if code == 1000 {
return true, nil
}
//log.Println(respmap)
return false, errors.New(fmt.Sprintf("%.0f", code))
}
func parseOrder(order *Order, ordermap map[string]interface{}) {
//log.Println(ordermap)
//order.Currency = currency;
order.OrderID, _ = strconv.Atoi(ordermap["id"].(string))
order.OrderID2 = ordermap["id"].(string)
order.Amount = ordermap["total_amount"].(float64)
order.DealAmount = ordermap["trade_amount"].(float64)
order.Price = ordermap["price"].(float64)
// order.Fee = ordermap["fees"].(float64)
if order.DealAmount > 0 {
order.AvgPrice = ToFloat64(ordermap["trade_money"]) / order.DealAmount
} else {
order.AvgPrice = 0
}
order.OrderTime = int(ordermap["trade_date"].(float64))
orType := ordermap["type"].(float64)
switch orType {
case 0:
order.Side = SELL
case 1:
order.Side = BUY
default:
log.Printf("unknown order type %f", orType)
}
_status := TradeStatus(ordermap["status"].(float64))
switch _status {
case 0:
order.Status = ORDER_UNFINISH
case 1:
order.Status = ORDER_CANCEL
case 2:
order.Status = ORDER_FINISH
case 3:
order.Status = ORDER_UNFINISH
}
}
func (zb *Zb) GetOneOrder(orderId string, currency CurrencyPair) (*Order, error) {
symbol := currency.AdaptBchToBcc().AdaptUsdToUsdt().ToSymbol("_")
params := url.Values{}
params.Set("method", "getOrder")
params.Set("id", orderId)
params.Set("currency", symbol)
zb.buildPostForm(¶ms)
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+GET_ORDER_API, params)
if err != nil {
log.Println(err)
return nil, err
}
//println(string(resp))
ordermap := make(map[string]interface{})
err = json.Unmarshal(resp, &ordermap)
if err != nil {
log.Println(err)
return nil, err
}
order := new(Order)
order.Currency = currency
parseOrder(order, ordermap)
return order, nil
}
func (zb *Zb) GetUnfinishOrders(currency CurrencyPair) ([]Order, error) {
params := url.Values{}
symbol := currency.AdaptBchToBcc().AdaptUsdToUsdt().ToSymbol("_")
params.Set("method", "getUnfinishedOrdersIgnoreTradeType")
params.Set("currency", symbol)
params.Set("pageIndex", "1")
params.Set("pageSize", "100")
zb.buildPostForm(¶ms)
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+GET_UNFINISHED_ORDERS_API, params)
if err != nil {
log.Println(err)
return nil, err
}
respstr := string(resp)
//println(respstr)
if strings.Contains(respstr, "\"code\":3001") {
log.Println(respstr)
return nil, nil
}
var resps []interface{}
err = json.Unmarshal(resp, &resps)
if err != nil {
log.Println(err)
return nil, err
}
var orders []Order
for _, v := range resps {
ordermap := v.(map[string]interface{})
order := Order{}
order.Currency = currency
parseOrder(&order, ordermap)
orders = append(orders, order)
}
return orders, nil
}
func (zb *Zb) GetOrderHistorys(currency CurrencyPair, currentPage, pageSize int) ([]Order, error) {
return nil, nil
}
func (zb *Zb) GetKlineRecords(currency CurrencyPair, period, size, since int) ([]Kline, error) {
return nil, nil
}
func (zb *Zb) Withdraw(amount string, currency Currency, fees, receiveAddr, safePwd string) (string, error) {
params := url.Values{}
params.Set("method", "withdraw")
params.Set("currency", strings.ToLower(currency.AdaptBchToBcc().String()))
params.Set("amount", amount)
params.Set("fees", fees)
params.Set("receiveAddr", receiveAddr)
params.Set("safePwd", safePwd)
zb.buildPostForm(¶ms)
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+WITHDRAW_API, params)
if err != nil {
log.Println("withdraw fail.", err)
return "", err
}
respMap := make(map[string]interface{})
err = json.Unmarshal(resp, &respMap)
if err != nil {
log.Println(err, string(resp))
return "", err
}
if respMap["code"].(float64) == 1000 {
return respMap["id"].(string), nil
}
return "", errors.New(string(resp))
}
func (zb *Zb) CancelWithdraw(id string, currency Currency, safePwd string) (bool, error) {
params := url.Values{}
params.Set("method", "cancelWithdraw")
params.Set("currency", strings.ToLower(currency.AdaptBchToBcc().String()))
params.Set("downloadId", id)
params.Set("safePwd", safePwd)
zb.buildPostForm(¶ms)
resp, err := HttpPostForm(zb.httpClient, TRADE_URL+CANCELWITHDRAW_API, params)
if err != nil {
log.Println("cancel withdraw fail.", err)
return false, err
}
respMap := make(map[string]interface{})
err = json.Unmarshal(resp, &respMap)
if err != nil {
log.Println(err, string(resp))
return false, err
}
if respMap["code"].(float64) == 1000 {
return true, nil
}
return false, errors.New(string(resp))
}
func (zb *Zb) GetTrades(currencyPair CurrencyPair, since int64) ([]Trade, error) {
panic("unimplements")
}
func (zb *Zb) MarketBuy(amount, price string, currency CurrencyPair) (*Order, error) {
panic("unsupport the market order")
}
func (zb *Zb) MarketSell(amount, price string, currency CurrencyPair) (*Order, error) {
panic("unsupport the market order")
}