forked from beldur/kraken-go-api-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
krakenapi.go
888 lines (758 loc) · 22.5 KB
/
krakenapi.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
package krakenapi
import (
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
)
const (
// APIURL is the official Kraken API Endpoint
APIURL = "https://api.kraken.com"
// APIVersion is the official Kraken API Version Number
APIVersion = "0"
// APIUserAgent identifies this library with the Kraken API
APIUserAgent = "Kraken GO API Agent (https://github.com/beldur/kraken-go-api-client)"
)
// List of valid public methods
var publicMethods = []string{
"Assets",
"AssetPairs",
"Depth",
"OHLC",
"OHLCWithInterval",
"Spread",
"Ticker",
"Time",
"Trades",
}
// List of valid private methods
var privateMethods = []string{
"AddExport",
"AddOrder",
"Balance",
"CancelOrder",
"ClosedOrders",
"DepositAddresses",
"DepositMethods",
"DepositStatus",
"ExportStatus",
"GetWebSocketsToken",
"Ledgers",
"OpenOrders",
"OpenPositions",
"QueryLedgers",
"QueryOrders",
"QueryTrades",
"RemoveExport",
"RetrieveExport",
"TradeBalance",
"TradesHistory",
"TradeVolume",
"WalletTransfer",
"Withdraw",
"WithdrawCancel",
"WithdrawInfo",
"WithdrawStatus",
}
var privateMethodTokenCountOverrides = map[string]int{
"Ledgers": 2,
"QueryLedgers": 2,
"ClosedOrders": 2,
"AddOrder": 0,
"CancelOrder": 0,
}
// These represent the minimum order sizes for the respective coins
// Should be monitored through here: https://support.kraken.com/hc/en-us/articles/205893708-What-is-the-minimum-order-size-
const (
MinimumREP = 0.3
MinimumXBT = 0.002
MinimumBCH = 0.002
MinimumDASH = 0.03
MinimumDOGE = 3000.0
MinimumEOS = 3.0
MinimumETH = 0.02
MinimumETC = 0.3
MinimumGNO = 0.03
MinimumICN = 2.0
MinimumLTC = 0.1
MinimumMLN = 0.1
MinimumXMR = 0.1
MinimumXRP = 30.0
MinimumXLM = 300.0
MinimumZEC = 0.02
MinimumUSDT = 5.0
)
// KrakenApi represents a Kraken API Client connection
type KrakenApi = KrakenAPI
// KrakenAPI represents a Kraken API Client connection
type KrakenAPI struct {
key string
secret string
client *http.Client
mutex *sync.Mutex
serializeRequests bool
enableRateLimiter bool
limiter *rate.Limiter
}
// New creates a new Kraken API client
func New(key, secret string) *KrakenAPI {
krakenAPI := KrakenAPI{
key: key,
secret: secret,
client: http.DefaultClient,
}
return &krakenAPI
}
// NewWithClient creates a new Kraken API client with custom http client
func NewWithClient(key, secret string, httpClient *http.Client) *KrakenAPI {
return NewWithClientSerialized(
key,
secret,
httpClient,
nil,
)
}
func NewWithClientSerialized(
key, secret string,
httpClient *http.Client,
mutex *sync.Mutex,
) *KrakenAPI {
k := New(key, secret).WithClient(httpClient)
k.serializeRequests = mutex != nil
k.mutex = mutex
return k
}
// WithClient adds an HTTP client into the KrakenAPI
func (api *KrakenAPI) WithClient(httpClient *http.Client) *KrakenAPI {
api.client = httpClient
return api
}
func NewWithClientSerializedRateLimited(
key, secret string,
httpClient *http.Client,
mutex *sync.Mutex,
refreshRate time.Duration,
maxBurst int,
) *KrakenApi {
k := NewWithClientSerialized(
key,
secret,
httpClient,
mutex,
)
k.SetRateLimiter(
refreshRate,
maxBurst,
)
return k
}
func (api *KrakenApi) SetRateLimiter(
refreshRate time.Duration,
maxBurst int,
) {
api.enableRateLimiter = true
api.limiter = rate.NewLimiter(rate.Every(refreshRate), maxBurst)
}
// Time returns the server's time
func (api *KrakenAPI) Time() (*TimeResponse, *http.Response, error) {
resp := &TimeResponse{}
httpResp, err := api.queryPublic("Time", nil, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Assets returns the servers available assets
func (api *KrakenAPI) Assets() (*AssetsResponse, *http.Response, error) {
resp := &AssetsResponse{}
httpResp, err := api.queryPublic("Assets", nil, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// AssetPairs returns the servers available asset pairs
func (api *KrakenAPI) AssetPairs() (*AssetPairsResponse, *http.Response, error) {
resp := &AssetPairsResponse{}
httpResp, err := api.queryPublic("AssetPairs", nil, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Ticker returns the ticker for given comma separated pairs
func (api *KrakenAPI) Ticker(pairs ...string) (*TickerResponse, *http.Response, error) {
resp := &TickerResponse{}
httpResp, err := api.queryPublic("Ticker", url.Values{
"pair": {strings.Join(pairs, ",")},
}, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// OHLCWithInterval returns a OHLCResponse struct based on the given pair
func (api *KrakenAPI) OHLCWithInterval(pair string, interval string) (*OHLCResponse, *http.Response, error) {
urlValue := url.Values{}
urlValue.Add("pair", pair)
if interval == "" {
urlValue.Add("interval", "1")
} else {
switch interval {
// supported values https://www.kraken.com/features/api#get-ohlc-data
case "1", "5", "15", "30", "60", "240", "1440", "10080", "21600":
urlValue.Add("interval", interval)
default:
return nil, nil, fmt.Errorf("Unsupported value for Interval: " + interval)
}
}
// Returns a map[string]interface{} as an interface{}
mapResponse := map[string]interface{}{}
httpResp, err := api.queryPublic("OHLC", urlValue, &mapResponse)
if err != nil {
return nil, httpResp, err
}
// Converts the interface into map[string]interface{}
// mapResponse := interfaceResponse.(map[string]interface{})
// Extracts the list of OHLC from the map to build a slice of interfaces
OHLCsUnstructured := mapResponse[pair].([]interface{})
ret := new(OHLCResponse)
for _, OHLCInterfaceSlice := range OHLCsUnstructured {
OHLCObj, OHLCErr := NewOHLC(OHLCInterfaceSlice.([]interface{}))
if OHLCErr != nil {
return nil, httpResp, OHLCErr
}
ret.OHLC = append(ret.OHLC, OHLCObj)
}
ret.Pair = pair
ret.Last = mapResponse["last"].(float64)
return ret, httpResp, nil
}
// OHLC returns a OHLCResponse struct based on the given pair
func (api *KrakenAPI) OHLC(pair string) (*OHLCResponse, *http.Response, error) {
ret, resp, err := api.OHLCWithInterval(pair, "1")
return ret, resp, err
}
// TradesHistory returns the Trades History within a specified time frame (start to end).
func (api *KrakenAPI) TradesHistory(start int64, end int64, args map[string]string) (*TradesHistoryResponse, *http.Response, error) {
params := url.Values{}
if start > 0 {
params.Add("start", strconv.FormatInt(start, 10))
}
if end > 0 {
params.Add("end", strconv.FormatInt(end, 10))
}
if value, ok := args["type"]; ok {
params.Add("type", value)
}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
resp := &TradesHistoryResponse{}
httpResp, err := api.queryPrivate("TradesHistory", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Trades returns the recent trades for given pair
func (api *KrakenAPI) Trades(pair string, since int64) (*TradesResponse, *http.Response, error) {
values := url.Values{"pair": {pair}}
if since > 0 {
values.Set("since", strconv.FormatInt(since, 10))
}
v := map[string]interface{}{}
httpResp, err := api.queryPublic("Trades", values, &v)
if err != nil {
return nil, httpResp, err
}
last, err := strconv.ParseInt(v["last"].(string), 10, 64)
if err != nil {
return nil, httpResp, err
}
result := &TradesResponse{
Last: last,
Trades: make([]TradeInfo, 0),
}
trades := v[pair].([]interface{})
for _, v := range trades {
trade := v.([]interface{})
priceString := trade[0].(string)
price, _ := strconv.ParseFloat(priceString, 64)
volumeString := trade[1].(string)
volume, _ := strconv.ParseFloat(trade[1].(string), 64)
tradeInfo := TradeInfo{
Price: priceString,
PriceFloat: price,
Volume: volumeString,
VolumeFloat: volume,
Time: int64(trade[2].(float64)),
Buy: trade[3].(string) == BUY,
Sell: trade[3].(string) == SELL,
Market: trade[4].(string) == MARKET,
Limit: trade[4].(string) == LIMIT,
Miscellaneous: trade[5].(string),
}
result.Trades = append(result.Trades, tradeInfo)
}
return result, httpResp, nil
}
// Balance returns all account asset balances
func (api *KrakenAPI) Balance() (*BalanceResponse, *http.Response, error) {
resp := &BalanceResponse{}
httpResp, err := api.queryPrivate("Balance", url.Values{}, &resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// TradeBalance returns trade balance info
func (api *KrakenAPI) TradeBalance(args map[string]string) (*TradeBalanceResponse, *http.Response, error) {
params := url.Values{}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
if value, ok := args["asset"]; ok {
params.Add("asset", value)
}
resp := &TradeBalanceResponse{}
httpResp, err := api.queryPrivate("TradeBalance", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// TradeVolume returns trade volume info
func (api *KrakenAPI) TradeVolume(args map[string]string) (*TradeVolumeResponse, *http.Response, error) {
params := url.Values{}
if value, ok := args["pair"]; ok {
params.Add("pair", value)
}
if value, ok := args["fee-info"]; ok {
params.Add("fee-info", value)
}
resp := &TradeVolumeResponse{}
httpResp, err := api.queryPrivate("TradeVolume", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// OpenOrders returns all open orders
func (api *KrakenAPI) OpenOrders(args map[string]string) (*OpenOrdersResponse, *http.Response, error) {
params := url.Values{}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp := &OpenOrdersResponse{}
httpResp, err := api.queryPrivate("OpenOrders", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// ClosedOrders returns all closed orders
func (api *KrakenAPI) ClosedOrders(args map[string]string) (*ClosedOrdersResponse, *http.Response, error) {
params := url.Values{}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
if value, ok := args["start"]; ok {
params.Add("start", value)
}
if value, ok := args["end"]; ok {
params.Add("end", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
if value, ok := args["closetime"]; ok {
params.Add("closetime", value)
}
resp := &ClosedOrdersResponse{}
httpResp, err := api.queryPrivate("ClosedOrders", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Depth returns the order book for given pair and orders count.
func (api *KrakenAPI) Depth(pair string, count int) (*OrderBook, *http.Response, error) {
dr := DepthResponse{}
httpResp, err := api.queryPublic("Depth", url.Values{
"pair": {pair}, "count": {strconv.Itoa(count)},
}, &dr)
if err != nil {
return nil, httpResp, err
}
if book, found := dr[pair]; found {
return &book, httpResp, nil
}
return nil, httpResp, errors.New("invalid response")
}
// CancelOrder cancels order
func (api *KrakenAPI) CancelOrder(txid string) (*CancelOrderResponse, *http.Response, error) {
params := url.Values{}
params.Add("txid", txid)
resp := &CancelOrderResponse{}
httpResp, err := api.queryPrivate("CancelOrder", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// QueryOrders shows order
func (api *KrakenAPI) QueryOrders(txids string, args map[string]string) (*QueryOrdersResponse, *http.Response, error) {
params := url.Values{"txid": {txids}}
if value, ok := args["trades"]; ok {
params.Add("trades", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp := &QueryOrdersResponse{}
httpResp, err := api.queryPrivate("QueryOrders", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// QueryTrades
func (api *KrakenAPI) QueryTrades(txid string, trades bool) (*QueryTradesResponse, *http.Response, error) {
params := url.Values{}
params.Add("txid", txid)
params.Add("trades", strconv.FormatBool(trades))
resp := &QueryTradesResponse{}
httpResp, err := api.queryPrivate("QueryTrades", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// DepositStatus retrieves deposit statuses
func (api *KrakenAPI) DepositStatus(asset string, args map[string]string) (*DepositStatusResponse, *http.Response, error) {
resp := &DepositStatusResponse{}
httpResp, err := api.movementStatus("DepositStatus", asset, args, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// WithdrawStatus retrieves withdraw statuses
func (api *KrakenAPI) WithdrawStatus(asset string, args map[string]string) (*WithdrawStatusResponse, *http.Response, error) {
resp := &WithdrawStatusResponse{}
httpResp, err := api.movementStatus("WithdrawStatus", asset, args, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
func (api *KrakenAPI) movementStatus(movementType string, asset string, args map[string]string, typ interface{}) (*http.Response, error) {
params := url.Values{}
params.Add("asset", asset)
if value, ok := args["method"]; ok {
params.Add("method", value)
}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
return api.queryPrivate(movementType, params, typ)
}
// GetOpenPositions retrieves the open positions
func (api *KrakenAPI) GetOpenPositions(args map[string]string) (*PositionsResponse, *http.Response, error) {
params := url.Values{}
if value, ok := args["txid"]; ok {
params.Add("txid", value)
}
if value, ok := args["docalcs"]; ok {
params.Add("docalcs", value)
}
resp := &PositionsResponse{}
httpResp, err := api.queryPrivate("OpenPositions", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// AddOrder adds new order
func (api *KrakenAPI) AddOrder(pair string, direction string, orderType string, volume string, args map[string]string) (*AddOrderResponse, *http.Response, error) {
params := url.Values{
"pair": {pair},
"type": {direction},
"ordertype": {orderType},
"volume": {volume},
}
if value, ok := args["price"]; ok {
params.Add("price", value)
}
if value, ok := args["price2"]; ok {
params.Add("price2", value)
}
if value, ok := args["leverage"]; ok {
params.Add("leverage", value)
}
if value, ok := args["oflags"]; ok {
params.Add("oflags", value)
}
if value, ok := args["starttm"]; ok {
params.Add("starttm", value)
}
if value, ok := args["expiretm"]; ok {
params.Add("expiretm", value)
}
if value, ok := args["validate"]; ok {
params.Add("validate", value)
}
if value, ok := args["close_order_type"]; ok {
params.Add("close[ordertype]", value)
}
if value, ok := args["close_price"]; ok {
params.Add("close[price]", value)
}
if value, ok := args["close_price2"]; ok {
params.Add("close[price2]", value)
}
if value, ok := args["trading_agreement"]; ok {
params.Add("trading_agreement", value)
}
if value, ok := args["userref"]; ok {
params.Add("userref", value)
}
resp := &AddOrderResponse{}
httpResp, err := api.queryPrivate("AddOrder", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Ledgers returns ledgers informations
func (api *KrakenAPI) Ledgers(args map[string]string) (*LedgersResponse, *http.Response, error) {
params := url.Values{}
if value, ok := args["aclass"]; ok {
params.Add("aclass", value)
}
if value, ok := args["asset"]; ok {
params.Add("asset", value)
}
if value, ok := args["type"]; ok {
params.Add("type", value)
}
if value, ok := args["start"]; ok {
params.Add("start", value)
}
if value, ok := args["end"]; ok {
params.Add("end", value)
}
if value, ok := args["ofs"]; ok {
params.Add("ofs", value)
}
resp := &LedgersResponse{}
httpResp, err := api.queryPrivate("Ledgers", params, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// DepositAddresses returns deposit addresses
func (api *KrakenAPI) DepositAddresses(asset string, method string) (*DepositAddressesResponse, *http.Response, error) {
resp := &DepositAddressesResponse{}
httpResp, err := api.queryPrivate("DepositAddresses", url.Values{
"asset": {asset},
"method": {method},
}, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Withdraw executes a withdrawal, returning a reference ID
func (api *KrakenAPI) Withdraw(asset string, key string, amount *big.Float) (*WithdrawResponse, *http.Response, error) {
resp := &WithdrawResponse{}
httpResp, err := api.queryPrivate("Withdraw", url.Values{
"asset": {asset},
"key": {key},
"amount": {amount.String()},
}, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// WithdrawInfo returns withdrawal information
func (api *KrakenAPI) WithdrawInfo(asset string, key string, amount *big.Float) (*WithdrawInfoResponse, *http.Response, error) {
resp := &WithdrawInfoResponse{}
httpResp, err := api.queryPrivate("WithdrawInfo", url.Values{
"asset": {asset},
"key": {key},
"amount": {amount.String()},
}, resp)
if err != nil {
return nil, httpResp, err
}
return resp, httpResp, nil
}
// Query sends a query to Kraken api for given method and parameters
func (api *KrakenAPI) Query(method string, data map[string]string) (map[string]interface{}, *http.Response, error) {
values := url.Values{}
for key, value := range data {
values.Set(key, value)
}
var m map[string]interface{}
// Check if method is public or private
if isStringInSlice(method, publicMethods) {
httpRes, err := api.queryPublic(method, values, &m)
return m, httpRes, err
} else if isStringInSlice(method, privateMethods) {
httpRes, err := api.queryPrivate(method, values, &m)
return m, httpRes, err
}
return nil, nil, fmt.Errorf("Method '%s' is not valid", method)
}
// Execute a public method query
func (api *KrakenAPI) queryPublic(method string, values url.Values, typ interface{}) (*http.Response, error) {
url := fmt.Sprintf("%s/%s/public/%s", APIURL, APIVersion, method)
httpResp, err := api.doRequest(url, values, nil, typ)
return httpResp, err
}
// queryPrivate executes a private method query
func (api *KrakenAPI) queryPrivate(method string, values url.Values, typ interface{}) (*http.Response, error) {
urlPath := fmt.Sprintf("/%s/private/%s", APIVersion, method)
reqURL := fmt.Sprintf("%s%s", APIURL, urlPath)
secret, _ := base64.StdEncoding.DecodeString(api.secret)
if api.serializeRequests {
api.mutex.Lock()
defer api.mutex.Unlock()
}
// Determine the number of tokens to count
if api.enableRateLimiter {
count, ok := privateMethodTokenCountOverrides[method]
if !ok {
count = 1
}
for i := 0; i < count; i++ {
api.limiter.Wait(context.Background())
}
}
values.Set("nonce", fmt.Sprintf("%d", time.Now().UnixNano())) // Likely have to mutex this.
// Create signature
signature := createSignature(urlPath, values, secret)
// Add Key and signature to request headers
headers := map[string]string{
"API-Key": api.key,
"API-Sign": signature,
}
httpResp, err := api.doRequest(reqURL, values, headers, typ)
return httpResp, err
}
// doRequest executes a HTTP Request to the Kraken API and returns the result
func (api *KrakenAPI) doRequest(reqURL string, values url.Values, headers map[string]string, typ interface{}) (*http.Response, error) {
// Create request
req, err := http.NewRequest("POST", reqURL, strings.NewReader(values.Encode()))
if err != nil {
return nil, fmt.Errorf("Could not execute request! #1 (%s)", err.Error())
}
req.Header.Add("User-Agent", APIUserAgent)
for key, value := range headers {
req.Header.Add(key, value)
}
// Execute request
resp, err := api.client.Do(req)
if err != nil {
return resp, fmt.Errorf("Could not execute request! #2 (%s)", err.Error())
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return resp, fmt.Errorf("Could not execute request!(%s)", resp.Status)
}
// Read request
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, fmt.Errorf("Could not execute request! #3 (%s)", err.Error())
}
// Check mime type of response
mimeType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return resp, fmt.Errorf("Could not execute request #4! (%s)", err.Error())
}
if mimeType != "application/json" {
return resp, fmt.Errorf("Could not execute request #5! (%s)", fmt.Sprintf("Response Content-Type is '%s', but should be 'application/json'.", mimeType))
}
// if typ == nil {
// result := gjson.GetBytes(body, "result")
// mapList := BalanceResponse{}
// result.ForEach(
// func(key, value gjson.Result) bool {
// mapList[key.String()] = value.Float()
// return true
// },
// )
// return mapList, resp, nil
// }
// Parse request
var jsonData KrakenResponse
// Set the KrakenResponse.Result to typ so `json.Unmarshal` will
// unmarshal it into given type, instead of `interface{}`.
// if typ != nil {
// jsonData.Result = typ
// }
err = json.Unmarshal(body, &jsonData)
if err != nil {
return resp, fmt.Errorf("Could not execute request! #6 (%s)", err.Error())
}
// Check for Kraken API error
if len(jsonData.Error) > 0 {
return resp, fmt.Errorf("Could not execute request! #7 (%s)", jsonData.Error)
}
err = json.Unmarshal(jsonData.Result, typ)
return resp, err
}
// isStringInSlice is a helper function to test if given term is in a list of strings
func isStringInSlice(term string, list []string) bool {
for _, found := range list {
if term == found {
return true
}
}
return false
}
// getSha256 creates a sha256 hash for given []byte
func getSha256(input []byte) []byte {
sha := sha256.New()
sha.Write(input)
return sha.Sum(nil)
}
// getHMacSha512 creates a hmac hash with sha512
func getHMacSha512(message, secret []byte) []byte {
mac := hmac.New(sha512.New, secret)
mac.Write(message)
return mac.Sum(nil)
}
func createSignature(urlPath string, values url.Values, secret []byte) string {
// See https://www.kraken.com/help/api#general-usage for more information
shaSum := getSha256([]byte(values.Get("nonce") + values.Encode()))
macSum := getHMacSha512(append([]byte(urlPath), shaSum...), secret)
return base64.StdEncoding.EncodeToString(macSum)
}