-
Notifications
You must be signed in to change notification settings - Fork 4
/
bitvavo.go
1869 lines (1706 loc) · 62.8 KB
/
bitvavo.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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bitvavo
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
"time"
)
var rateLimitRemaining = 1000
var rateLimitReset = 0
type TimeResponse struct {
Action string `json:"action"`
Response Time `json:"response"`
}
type Time struct {
Time int `json:"time"`
}
type MarketsResponse struct {
Action string `json:"action"`
Response []Markets `json:"response"`
}
type Markets struct {
Status string `json:"status"`
Base string `json:"base"`
Quote string `json:"quote"`
Market string `json:"market"`
PricePrecision int `json:"pricePrecision"`
MinOrderInQuoteAsset string `json:"minOrderInQuoteAsset"`
MinOrderInBaseAsset string `json:"minOrderInBaseAsset"`
OrderTypes []string `json:"orderTypes"`
}
type AssetsResponse struct {
Action string `json:"action"`
Response []Assets `json:"response"`
}
type Assets struct {
Symbol string `json:"symbol"`
Name string `json:"name"`
Decimals int `json:"decimals"`
DepositFee string `json:"depositFee"`
DepositConfirmations int `json:"depositConfirmations"`
DepositStatus string `json:"depositStatus"`
WithdrawalFee string `json:"withdrawalFee"`
WithdrawalMinAmount string `json:"withdrawalMinAmount"`
WithdrawalStatus string `json:"withdrawalStatus"`
Networks []string `json:"networks"`
Message string `json:"message"`
}
type BookResponse struct {
Action string `json:"action"`
Response Book `json:"response"`
}
type Book struct {
Market string `json:"market"`
Nonce int `json:"nonce"`
Bids [][]string `json:"bids"`
Asks [][]string `json:"asks"`
}
type PublicTradesResponse struct {
Action string `json:"action"`
Response []PublicTrades `json:"response"`
}
type PublicTrades struct {
Timestamp int `json:"timestamp"`
Id string `json:"id"`
Amount string `json:"amount"`
Price string `json:"price"`
Side string `json:"side"`
}
type CandlesResponse struct {
Action string `json:"action"`
Response []interface{} `json:"response"`
}
type Candles struct {
Candles []Candle `json:"candles"`
}
type Candle struct {
Timestamp int
Open string
High string
Low string
Close string
Volume string
}
type Ticker24hResponse struct {
Action string `json:"action"`
Response []Ticker24h `json:"response"`
}
type Ticker24h struct {
Market string `json:"market"`
Open string `json:"open"`
High string `json:"high"`
Low string `json:"low"`
Last string `json:"last"`
Volume string `json:"volume"`
VolumeQuote string `json:"volumeQuote"`
Bid string `json:"bid"`
Ask string `json:"ask"`
Timestamp int `json:"timestamp"`
BidSize string `json:"bidSize"`
AskSize string `json:"askSize"`
}
type TickerPriceResponse struct {
Action string `json:"action"`
Response []TickerPrice `json:"response"`
}
type TickerPrice struct {
Market string `json:"market"`
Price string `json:"price"`
}
type TickerBookResponse struct {
Action string `json:"action"`
Response []TickerBook `json:"response"`
}
type TickerBook struct {
Market string `json:"market"`
Bid string `json:"bid"`
Ask string `json:"ask"`
BidSize string `json:"bidSize"`
AskSize string `json:"askSize"`
}
type PlaceOrderResponse struct {
Action string `json:"action"`
Response Order `json:"response"`
}
type Order struct {
OrderId string `json:"orderId"`
Market string `json:"market"`
Created int `json:"created"`
Updated int `json:"updated"`
Status string `json:"status"`
Side string `json:"side"`
OrderType string `json:"orderType"`
Amount string `json:"amount"`
AmountRemaining string `json:"amountRemaining"`
Price string `json:"price"`
AmountQuote string `json:"amountQuote"`
AmountQuoteRemaining string `json:"amountQuoteRemaining"`
OnHold string `json:"onHold"`
OnHoldCurrency string `json:"onHoldCurrency"`
FilledAmount string `json:"filledAmount"`
FilledAmountQuote string `json:"filledAmountQuote"`
FeePaid string `json:"feePaid"`
FeeCurrency string `json:"feeCurrency"`
Fills []Fill `json:"fills"`
SelfTradePrevention string `json:"selfTradePrevention"`
Visible bool `json:"visible"`
DisableMarketProtection bool `json:"disableMarketProtection"`
TimeInForce string `json:"timeInForce"`
PostOnly bool `json:"postOnly"`
TriggerAmount string `json:"triggerAmount"`
TriggerPrice string `json:"triggerPrice"`
TriggerType string `json:"triggerType"`
TriggerReference string `json:"triggerReference"`
}
type Fill struct {
Id string `json:"id"`
Timestamp int `json:"timestamp"`
Amount string `json:"amount"`
Price string `json:"price"`
Taker bool `json:"taker"`
Fee string `json:"fee"`
FeeCurrency string `json:"feeCurrency"`
Settled bool `json:"settled"`
}
type GetOrderResponse struct {
Action string `json:"action"`
Response Order `json:"response"`
}
type UpdateOrderResponse struct {
Action string `json:"action"`
Response Order `json:"response"`
}
type CancelOrderResponse struct {
Action string `json:"action"`
Response CancelOrder `json:"response"`
}
type CancelOrder struct {
OrderId string `json:"orderId"`
}
type GetOrdersResponse struct {
Action string `json:"action"`
Response []Order `json:"response"`
}
type CancelOrdersResponse struct {
Action string `json:"action"`
Response []CancelOrder `json:"response"`
}
type OrdersOpenResponse struct {
Action string `json:"action"`
Response []Order `json:"response"`
}
type TradesResponse struct {
Action string `json:"action"`
Response []Trades `json:"response"`
}
type Trades struct {
Id string `json:"id"`
Timestamp int `json:"timestamp"`
Market string `json:"market"`
Amount string `json:"amount"`
Side string `json:"side"`
Price string `json:"price"`
Taker bool `json:"taker"`
Fee string `json:"fee"`
FeeCurrency string `json:"feeCurrency"`
Settled bool `json:"settled"`
}
type AccountResponse struct {
Action string `json:"action"`
Response Account `json:"response"`
}
type Account struct {
Fees FeeObject `json:"fees"`
}
type FeeObject struct {
Taker string `json:"taker"`
Maker string `json:"maker"`
Volume string `json:"volume"`
}
type BalanceResponse struct {
Action string `json:"action"`
Response []Balance `json:"response"`
}
type Balance struct {
Symbol string `json:"symbol"`
Available string `json:"available"`
InOrder string `json:"inOrder"`
}
type DepositAssetsResponse struct {
Action string `json:"action"`
Response DepositAssets `json:"response"`
}
type DepositAssets struct {
Address string `json:"address"`
Iban string `json:"iban"`
Bic string `json:"bic"`
Description string `json:"description"`
PaymentId string `json:"paymentId"`
}
type WithdrawAssetsResponse struct {
Action string `json:"action"`
Response WithdrawAssets `json:"response"`
}
type WithdrawAssets struct {
Symbol string `json:"symbol"`
Amount string `json:"amount"`
Success bool `json:"success"`
}
type HistoryResponse struct {
Action string `json:"action"`
Response []History `json:"response"`
}
type History struct {
Symbol string `json:"symbol"`
Amount string `json:"amount"`
Address string `json:"address"`
PaymentId string `json:"paymentId"`
Fee string `json:"fee"`
TxId string `json:"txId"`
Timestamp int `json:"timestamp"`
Status string `json:"status"`
}
type SubscriptionTickerResponse struct {
Action string `json:"action"`
Response SubscriptionTicker `json:"response"`
}
type SubscriptionTicker struct {
Event string `json:"event"`
Market string `json:"market"`
BestBid string `json:"bestBid"`
BestBidSize string `json:"bestBidSize"`
BestAsk string `json:"bestAsk"`
BestAskSize string `json:"bestAskSize"`
LastPrice string `json:"lastPrice"`
}
type SubscriptionTicker24h struct {
Event string `json:"event"`
Data []Ticker24h `json:"data"`
}
type SubscriptionAccountFill struct {
Event string `json:"event"`
Timestamp int `json:"timestamp"`
Market string `json:"market"`
OrderId string `json:"orderId"`
FillId string `json:"fillId"`
Amount string `json:"amount"`
Price string `json:"price"`
Taker bool `json:"taker"`
Fee string `json:"fee"`
FeeCurrency string `json:"feeCurrency"`
}
type SubscriptionAccountOrder struct {
Event string `json:"event"`
OrderId string `json:"orderId"`
Market string `json:"market"`
Created int `json:"created"`
Updated int `json:"updated"`
Status string `json:"status"`
Side string `json:"side"`
OrderType string `json:"orderType"`
Amount string `json:"amount"`
AmountRemaining string `json:"amountRemaining"`
AmountQuote string `json:"amountQuote"`
AmountQuoteRemaining string `json:"amountQuoteRemaining"`
Price string `json:"price"`
OnHold string `json:"onHold"`
OnHoldCurrency string `json:"onHoldCurrency"`
TimeInForce string `json:"timeInForce"`
PostOnly bool `json:"postOnly"`
SelfTradePrevention string `json:"selfTradePrevention"`
Visible bool `json:"visible"`
TriggerAmount string `json:"triggerAmount"`
TriggerPrice string `json:"triggerPrice"`
TriggerType string `json:"triggerType"`
TriggerReference string `json:"triggerReference"`
}
type SubscriptionCandlesResponse struct {
Action string `json:"action"`
Response SubscriptionTicker `json:"response"`
}
type SubscriptionCandles struct {
Event string `json:"event"`
Market string `json:"market"`
Interval string `json:"interval"`
Candle []Candle `json:"candle"`
}
type PreCandle struct {
Event string `json:"event"`
Market string `json:"market"`
Interval string `json:"interval"`
Candle []interface{} `json:"candle"`
}
type SubscriptionTrades struct {
Event string `json:"event"`
Timestamp int `json:"timestamp"`
Market string `json:"market"`
Id string `json:"id"`
Amount string `json:"amount"`
Price string `json:"price"`
Side string `json:"side"`
}
type SubscriptionBookUpdate struct {
Event string `json:"event"`
Market string `json:"market"`
Nonce int `json:"nonce"`
Bids [][]string `json:"bids"`
Asks [][]string `json:"asks"`
}
type SubscriptionTickAccObject struct {
Action string `json:"action"`
Channels []string `json:"channels"`
}
type SubscriptionTickerObject struct {
Action string `json:"action"`
Channels []SubscriptionTickAccSubObject `json:"channels"`
}
type SubscriptionTickAccSubObject struct {
Name string `json:"name"`
Markets []string `json:"markets"`
}
type SubscriptionTradesBookObject struct {
Action string `json:"action"`
Channels []SubscriptionTradesBookSubObject `json:"channels"`
}
type SubscriptionTradesBookSubObject struct {
Name string `json:"name"`
Markets []string `json:"markets"`
}
type SubscriptionCandlesObject struct {
Action string `json:"action"`
Channels []SubscriptionCandlesSubObject `json:"channels"`
}
type SubscriptionCandlesSubObject struct {
Name string `json:"name"`
Interval []string `json:"interval"`
Markets []string `json:"markets"`
}
type LocalBook struct {
Book map[string]Book `json:"book"`
}
type MyError struct {
Err error
CustomError CustomError
}
func (e MyError) Error() string {
if e.Err != nil {
errorString := e.Err.Error()
return errorString
} else {
return fmt.Sprintf("Error returned by API: errorCode:%d, Message: %s", e.CustomError.Code, e.CustomError.Message)
}
}
type CustomError struct {
Code int `json:"errorCode"`
Message string `json:"error"`
Action string `json:"action"`
}
type Bitvavo struct {
ApiKey, ApiSecret string
RestUrl string
WsUrl string
AccessWindow int
WS Websocket
reconnectTimer int
Debugging bool
}
type Websocket struct {
ApiKey string
WsUrl string
Debugging bool
BookLock sync.Mutex
sendLock sync.Mutex
conn *websocket.Conn
localBook LocalBook
reconnectOnError bool
authenticated bool
authenticationFailed bool
keepLocalBook bool
errChannel chan MyError
timeChannel chan Time
marketsChannel chan []Markets
assetsChannel chan []Assets
bookChannel chan Book
publicTradesChannel chan []PublicTrades
candlesChannel chan []Candle
ticker24hChannel chan []Ticker24h
tickerPriceChannel chan []TickerPrice
tickerBookChannel chan []TickerBook
placeOrderChannel chan Order
getOrderChannel chan Order
updateOrderChannel chan Order
cancelOrderChannel chan CancelOrder
getOrdersChannel chan []Order
cancelOrdersChannel chan []CancelOrder
ordersOpenChannel chan []Order
tradesChannel chan []Trades
accountChannel chan Account
balanceChannel chan []Balance
depositAssetsChannel chan DepositAssets
withdrawAssetsChannel chan WithdrawAssets
depositHistoryChannel chan []History
withdrawalHistoryChannel chan []History
subscriptionTickerChannelMap map[string]chan SubscriptionTicker
subscriptionTickerOptionsMap map[string]SubscriptionTickerObject
subscriptionTicker24hChannelMap map[string]chan Ticker24h
subscriptionTicker24hOptionsMap map[string]SubscriptionTickerObject
subscriptionAccountFillChannelMap map[string]chan SubscriptionAccountFill
subscriptionAccountOrderChannelMap map[string]chan SubscriptionAccountOrder
subscriptionAccountOptionsMap map[string]SubscriptionTickerObject
subscriptionCandlesOptionsMap map[string]map[string]SubscriptionCandlesObject
subscriptionCandlesChannelMap map[string]map[string]chan SubscriptionCandles
subscriptionTradesChannelMap map[string]chan SubscriptionTrades
subscriptionTradesOptionsMap map[string]SubscriptionTradesBookObject
subscriptionBookUpdateChannelMap map[string]chan SubscriptionBookUpdate
subscriptionBookUpdateOptionsMap map[string]SubscriptionTradesBookObject
subscriptionBookChannelMap map[string]chan Book
subscriptionBookOptionsFirstMap map[string]map[string]string
subscriptionBookOptionsSecondMap map[string]SubscriptionTradesBookObject
}
func (bitvavo Bitvavo) NewWebsocket() (*Websocket, chan MyError) {
ws := Websocket{}
ws.Debugging = bitvavo.Debugging
ws.ApiKey = bitvavo.ApiKey
ws.conn = bitvavo.InitWS()
ws.reconnectOnError = true
ws.authenticated = false
ws.authenticationFailed = false
ws.keepLocalBook = false
errChannel := make(chan MyError)
ws.errChannel = errChannel
go bitvavo.handleMessage(&ws)
return &ws, errChannel
}
func (bitvavo Bitvavo) createSignature(timestamp string, method string, url string, body map[string]string, ApiSecret string) string {
result := timestamp + method + "/v2" + url
if len(body) != 0 {
bodyString, err := json.Marshal(body)
if err != nil {
errorToConsole("Converting map to string went wrong!")
}
result = result + string(bodyString)
}
h := hmac.New(sha256.New, []byte(ApiSecret))
h.Write([]byte(result))
sha := hex.EncodeToString(h.Sum(nil))
return sha
}
func (bitvavo Bitvavo) sendPublic(endpoint string) []byte {
client := &http.Client{}
req, err := http.NewRequest("GET", endpoint, bytes.NewBuffer(nil))
if err != nil {
errorToConsole("We caught error " + err.Error())
}
if bitvavo.ApiKey != "" {
millis := time.Now().UnixNano() / 1000000
timeString := strconv.FormatInt(millis, 10)
sig := bitvavo.createSignature(timeString, "GET", strings.Replace(endpoint, bitvavo.RestUrl, "", 1), map[string]string{}, bitvavo.ApiSecret)
req.Header.Set("bitvavo-access-key", bitvavo.ApiKey)
req.Header.Set("bitvavo-access-signature", sig)
req.Header.Set("bitvavo-access-timestamp", timeString)
req.Header.Set("bitvavo-access-window", strconv.Itoa(bitvavo.AccessWindow))
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
errorToConsole("Caught error " + err.Error())
return []byte("caught error")
} else {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
errorToConsole("Caught error " + err.Error())
return []byte("caught error")
}
updateRateLimit(resp.Header)
return body
}
}
func (bitvavo Bitvavo) sendPrivate(endpoint string, postfix string, body map[string]string, method string) []byte {
millis := time.Now().UnixNano() / 1000000
timeString := strconv.FormatInt(millis, 10)
sig := bitvavo.createSignature(timeString, method, (endpoint + postfix), body, bitvavo.ApiSecret)
url := bitvavo.RestUrl + endpoint + postfix
client := &http.Client{}
byteBody := []byte{}
if len(body) != 0 {
bodyString, err := json.Marshal(body)
if err != nil {
errorToConsole("We caught error " + err.Error())
}
byteBody = []byte(bodyString)
} else {
byteBody = nil
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(byteBody))
req.Header.Set("bitvavo-access-key", bitvavo.ApiKey)
req.Header.Set("bitvavo-access-signature", sig)
req.Header.Set("bitvavo-access-timestamp", timeString)
req.Header.Set("bitvavo-access-window", strconv.Itoa(bitvavo.AccessWindow))
req.Header.Set("content-type", "application/json")
resp, err := client.Do(req)
if err != nil {
errorToConsole("We caught an error " + err.Error())
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
errorToConsole("Caught error " + err.Error())
return nil
}
updateRateLimit(resp.Header)
return respBody
}
func checkLimit() {
now := int(time.Nanosecond * time.Duration(time.Now().UnixNano()) / time.Millisecond)
if rateLimitReset <= now {
rateLimitRemaining = 1000
}
}
func updateRateLimit(response http.Header) {
for key, value := range response {
if key == "bitvavo-ratelimit-remaining" {
rateLimitRemaining, _ = strconv.Atoi(value[0])
}
if key == "bitvavo-ratelimit-resetat" {
rateLimitReset, _ = strconv.Atoi(value[0])
now := int(time.Nanosecond * time.Duration(time.Now().UnixNano()) / time.Millisecond)
var timeToWait = rateLimitReset - now
time.AfterFunc(time.Duration(timeToWait)*time.Millisecond, checkLimit)
}
}
}
func (bitvavo Bitvavo) GetRemainingLimit() int {
return rateLimitRemaining
}
func (bitvavo Bitvavo) createPostfix(options map[string]string) string {
result := []string{}
for k := range options {
result = append(result, (k + "=" + options[k]))
}
params := strings.Join(result, "&")
if len(params) != 0 {
params = "?" + params
}
return params
}
func handleAPIError(jsonResponse []byte) error {
var e CustomError
err := json.Unmarshal(jsonResponse, &e)
if err != nil {
errorToConsole("error casting")
return MyError{Err: err}
}
if e.Code == 105 {
rateLimitRemaining = 0
rateLimitReset, _ = strconv.Atoi(strings.Split(strings.Split(e.Message, " at ")[1], ".")[0])
now := int(time.Nanosecond * time.Duration(time.Now().UnixNano()) / time.Millisecond)
var timeToWait = rateLimitReset - now
time.AfterFunc(time.Duration(timeToWait)*time.Millisecond, checkLimit)
}
return MyError{CustomError: e}
}
func (bitvavo Bitvavo) Time() (Time, error) {
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/time")
var t Time
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return Time{}, MyError{Err: err}
}
if t.Time == 0.0 {
return Time{}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: market
func (bitvavo Bitvavo) Markets(options map[string]string) ([]Markets, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/markets" + postfix)
t := make([]Markets, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Markets{Markets{}}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: symbol
func (bitvavo Bitvavo) Assets(options map[string]string) ([]Assets, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/assets" + postfix)
t := make([]Assets, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Assets{Assets{}}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: depth
func (bitvavo Bitvavo) Book(symbol string, options map[string]string) (Book, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/" + symbol + "/book" + postfix)
var t Book
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return Book{}, MyError{Err: err}
}
if t.Market == "" {
return Book{}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: limit, start, end, tradeIdFrom, tradeIdTo
func (bitvavo Bitvavo) PublicTrades(symbol string, options map[string]string) ([]PublicTrades, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/" + symbol + "/trades" + postfix)
t := make([]PublicTrades, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []PublicTrades{PublicTrades{}}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: limit, start, end
func (bitvavo Bitvavo) Candles(symbol string, interval string, options map[string]string) ([]Candle, error) {
options["interval"] = interval
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/" + symbol + "/candles" + postfix)
var t []interface{}
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Candle{Candle{}}, MyError{Err: err}
}
var candles []Candle
for i := 0; i < len(t); i++ {
entry := reflect.ValueOf(t[i])
candles = append(candles, Candle{Timestamp: int(entry.Index(0).Interface().(float64)), Open: entry.Index(1).Interface().(string), High: entry.Index(2).Interface().(string), Low: entry.Index(3).Interface().(string), Close: entry.Index(4).Interface().(string), Volume: entry.Index(5).Interface().(string)})
}
return candles, nil
}
// options: market
func (bitvavo Bitvavo) TickerPrice(options map[string]string) ([]TickerPrice, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/ticker/price" + postfix)
t := make([]TickerPrice, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
var t TickerPrice
err = json.Unmarshal(jsonResponse, &t)
if err != nil {
return []TickerPrice{TickerPrice{}}, MyError{Err: err}
}
if t.Market == "" {
return []TickerPrice{TickerPrice{}}, handleAPIError(jsonResponse)
}
return []TickerPrice{t}, nil
}
return t, nil
}
// options: market
func (bitvavo Bitvavo) TickerBook(options map[string]string) ([]TickerBook, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/ticker/book" + postfix)
t := make([]TickerBook, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
var t TickerBook
err = json.Unmarshal(jsonResponse, &t)
if err != nil {
return []TickerBook{TickerBook{}}, MyError{Err: err}
}
if t.Market == "" {
return []TickerBook{TickerBook{}}, handleAPIError(jsonResponse)
}
return []TickerBook{t}, nil
}
return t, nil
}
// options: market
func (bitvavo Bitvavo) Ticker24h(options map[string]string) ([]Ticker24h, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPublic(bitvavo.RestUrl + "/ticker/24h" + postfix)
t := make([]Ticker24h, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
var t Ticker24h
err = json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Ticker24h{Ticker24h{}}, MyError{Err: err}
}
if t.Market == "" {
return []Ticker24h{Ticker24h{}}, handleAPIError(jsonResponse)
}
return []Ticker24h{t}, nil
}
return t, nil
}
// optional body parameters: limit:(amount, price, postOnly), market:(amount, amountQuote, disableMarketProtection)
// stopLoss/takeProfit:(amount, amountQuote, disableMarketProtection, triggerType, triggerReference, triggerAmount)
// stopLossLimit/takeProfitLimit:(amount, price, postOnly, triggerType, triggerReference, triggerAmount)
// all orderTypes: timeInForce, selfTradePrevention, responseRequired
func (bitvavo Bitvavo) PlaceOrder(market string, side string, orderType string, body map[string]string) (Order, error) {
body["market"] = market
body["side"] = side
body["orderType"] = orderType
jsonResponse := bitvavo.sendPrivate("/order", "", body, "POST")
var t Order
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return Order{}, MyError{Err: err}
}
if t.OrderId == "" {
return Order{}, handleAPIError(jsonResponse)
}
return t, nil
}
func (bitvavo Bitvavo) GetOrder(market string, orderId string) (Order, error) {
options := map[string]string{"market": market, "orderId": orderId}
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/order", postfix, map[string]string{}, "GET")
var t Order
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return Order{}, MyError{Err: err}
}
if t.OrderId == "" {
return Order{}, handleAPIError(jsonResponse)
}
return t, nil
}
// Optional body parameters: limit:(amount, amountRemaining, price, timeInForce, selfTradePrevention, postOnly)
// untriggered stopLoss/takeProfit:(amount, amountQuote, disableMarketProtection, triggerType, triggerReference, triggerAmount)
// stopLossLimit/takeProfitLimit: (amount, price, postOnly, triggerType, triggerReference, triggerAmount)
func (bitvavo Bitvavo) UpdateOrder(market string, orderId string, body map[string]string) (Order, error) {
body["market"] = market
body["orderId"] = orderId
jsonResponse := bitvavo.sendPrivate("/order", "", body, "PUT")
var t Order
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return Order{}, MyError{Err: err}
}
if t.OrderId == "" {
return Order{}, handleAPIError(jsonResponse)
}
return t, nil
}
func (bitvavo Bitvavo) CancelOrder(market string, orderId string) (CancelOrder, error) {
options := map[string]string{"market": market, "orderId": orderId}
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/order", postfix, map[string]string{}, "DELETE")
var t CancelOrder
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return CancelOrder{}, MyError{Err: err}
}
if t.OrderId == "" {
return CancelOrder{}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: limit, start, end, orderIdFrom, orderIdTo
func (bitvavo Bitvavo) GetOrders(market string, options map[string]string) ([]Order, error) {
options["market"] = market
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/orders", postfix, map[string]string{}, "GET")
t := make([]Order, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Order{Order{}}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: market
func (bitvavo Bitvavo) CancelOrders(options map[string]string) ([]CancelOrder, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/orders", postfix, map[string]string{}, "DELETE")
t := make([]CancelOrder, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []CancelOrder{CancelOrder{}}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: market
func (bitvavo Bitvavo) OrdersOpen(options map[string]string) ([]Order, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/ordersOpen", postfix, map[string]string{}, "GET")
t := make([]Order, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Order{Order{}}, handleAPIError(jsonResponse)
}
return t, nil
}
// options: limit, start, end, tradeIdFrom, tradeIdTo
func (bitvavo Bitvavo) Trades(market string, options map[string]string) ([]Trades, error) {
options["market"] = market
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/trades", postfix, map[string]string{}, "GET")
t := make([]Trades, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Trades{Trades{}}, handleAPIError(jsonResponse)
}
return t, nil
}
func (bitvavo Bitvavo) Account() (Account, error) {
jsonResponse := bitvavo.sendPrivate("/account", "", map[string]string{}, "GET")
var t Account
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return Account{}, MyError{Err: err}
}
return t, nil
}
// options: symbol
func (bitvavo Bitvavo) Balance(options map[string]string) ([]Balance, error) {
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/balance", postfix, map[string]string{}, "GET")
t := make([]Balance, 0)
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return []Balance{Balance{}}, handleAPIError(jsonResponse)
}
return t, nil
}
func (bitvavo Bitvavo) DepositAssets(symbol string) (DepositAssets, error) {
options := map[string]string{"symbol": symbol}
postfix := bitvavo.createPostfix(options)
jsonResponse := bitvavo.sendPrivate("/deposit", postfix, map[string]string{}, "GET")
var t DepositAssets
err := json.Unmarshal(jsonResponse, &t)
if err != nil {
return DepositAssets{}, MyError{Err: err}
}
if t.Address == "" {
return DepositAssets{}, handleAPIError(jsonResponse)
}
return t, nil
}
// optional body parameters: paymentId, internal, addWithdrawalFee
func (bitvavo Bitvavo) WithdrawAssets(symbol string, amount string, address string, body map[string]string) (WithdrawAssets, error) {
body["symbol"] = symbol
body["amount"] = amount
body["address"] = address