-
Notifications
You must be signed in to change notification settings - Fork 791
/
bitfinex.go
2328 lines (2141 loc) · 70.9 KB
/
bitfinex.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 bitfinex
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/nonce"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
)
const (
bitfinexAPIURLBase = "https://api.bitfinex.com"
tradeBaseURL = "https://trading.bitfinex.com"
// Version 1 API endpoints
bitfinexAPIVersion = "/v1/"
bitfinexStats = "stats/"
bitfinexAccountInfo = "account_infos"
bitfinexAccountFees = "account_fees"
bitfinexAccountSummary = "summary"
bitfinexBalances = "balances"
bitfinexTransfer = "transfer"
bitfinexWithdrawal = "withdraw"
bitfinexOrderNew = "order/new"
bitfinexOrderNewMulti = "order/new/multi"
bitfinexOrderCancel = "order/cancel"
bitfinexOrderCancelMulti = "order/cancel/multi"
bitfinexOrderCancelAll = "order/cancel/all"
bitfinexOrderCancelReplace = "order/cancel/replace"
bitfinexOrderStatus = "order/status"
bitfinexInactiveOrders = "hist"
bitfinexOrders = "orders"
bitfinexPositions = "positions"
bitfinexClaimPosition = "position/claim"
bitfinexHistory = "history"
bitfinexHistoryMovements = "movements"
bitfinexTradeHistory = "mytrades"
bitfinexOfferNew = "offer/new"
bitfinexOfferCancel = "offer/cancel"
bitfinexActiveCredits = "credits"
bitfinexOffers = "offers"
bitfinexMarginActiveFunds = "taken_funds"
bitfinexMarginUnusedFunds = "unused_taken_funds"
bitfinexMarginTotalFunds = "total_taken_funds"
bitfinexMarginClose = "funding/close"
bitfinexLendbook = "lendbook/"
bitfinexLends = "lends/"
bitfinexLeaderboard = "rankings"
// Version 2 API endpoints
bitfinexAPIVersion2 = "/v2/"
bitfinexV2MarginFunding = "calc/trade/avg?"
bitfinexV2Balances = "auth/r/wallets"
bitfinexV2AccountInfo = "auth/r/info/user"
bitfinexV2MarginInfo = "auth/r/info/margin/"
bitfinexV2FundingInfo = "auth/r/info/funding/%s"
bitfinexV2Auth = "auth/"
bitfinexDerivativeData = "status/deriv?"
bitfinexPlatformStatus = "platform/status"
bitfinexTickerBatch = "tickers"
bitfinexTicker = "ticker/"
bitfinexTrades = "trades/"
bitfinexOrderbook = "book/"
bitfinexHistoryShort = "hist"
bitfinexCandles = "candles/trade"
bitfinexKeyPermissions = "key_info"
bitfinexMarginInfo = "margin_infos"
bitfinexDepositMethod = "conf/pub:map:tx:method"
bitfinexDepositAddress = "auth/w/deposit/address"
bitfinexOrderUpdate = "auth/w/order/update"
bitfinexMarginPairs = "conf/pub:list:pair:margin"
bitfinexSpotPairs = "conf/pub:list:pair:exchange"
bitfinexMarginFundingPairs = "conf/pub:list:currency"
bitfinexFuturesPairs = "conf/pub:list:pair:futures" // TODO: Implement
bitfinexSecuritiesPairs = "conf/pub:list:pair:securities" // TODO: Implement
bitfinexInfoPairs = "conf/pub:info:pair"
bitfinexInfoFuturePairs = "conf/pub:info:pair:futures"
// Bitfinex platform status values
// When the platform is marked in maintenance mode bots should stop trading
// activity. Cancelling orders will be possible.
bitfinexMaintenanceMode = 0
bitfinexOperativeMode = 1
bitfinexChecksumFlag = 131072
bitfinexWsSequenceFlag = 65536
// CandlesTimeframeKey configures the timeframe in subscription.Subscription.Params
CandlesTimeframeKey = "_timeframe"
// CandlesPeriodKey configures the aggregated period in subscription.Subscription.Params
CandlesPeriodKey = "_period"
)
// Bitfinex is the overarching type across the bitfinex package
type Bitfinex struct {
exchange.Base
}
// GetPlatformStatus returns the Bifinex platform status
func (b *Bitfinex) GetPlatformStatus(ctx context.Context) (int, error) {
var response []int
err := b.SendHTTPRequest(ctx, exchange.RestSpot,
bitfinexAPIVersion2+
bitfinexPlatformStatus,
&response,
platformStatus)
if err != nil {
return -1, err
}
switch response[0] {
case bitfinexOperativeMode:
return bitfinexOperativeMode, nil
case bitfinexMaintenanceMode:
return bitfinexMaintenanceMode, nil
}
return -1, fmt.Errorf("unexpected platform status value %d", response[0])
}
func baseMarginInfo(data []interface{}) (MarginInfoV2, error) {
var resp MarginInfoV2
marginInfo, ok := data[1].([]any)
if !ok {
return resp, common.GetTypeAssertError("[]any", data[1], "MarginInfo")
}
if resp.UserPNL, ok = marginInfo[0].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[0], "UserPNL")
}
if resp.UserSwaps, ok = marginInfo[1].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[1], "UserSwaps")
}
if resp.MarginBalance, ok = marginInfo[2].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[2], "MarginBalance")
}
if resp.MarginNet, ok = marginInfo[3].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[3], "MarginNet")
}
if resp.MarginMin, ok = marginInfo[4].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[4], "MarginMin")
}
return resp, nil
}
func symbolMarginInfo(data []interface{}) ([]MarginInfoV2, error) {
resp := make([]MarginInfoV2, len(data))
for x := range data {
var tempResp MarginInfoV2
marginInfo, ok := data[x].([]any)
if !ok {
return nil, common.GetTypeAssertError("[]any", data[x], "MarginInfo")
}
var check bool
if tempResp.Symbol, check = marginInfo[1].(string); !check {
return nil, common.GetTypeAssertError("string", marginInfo[1], "Symbol")
}
pairMarginInfo, check := marginInfo[2].([]any)
if !check {
return nil, common.GetTypeAssertError("[]any", marginInfo[2], "MarginInfo.Data")
}
if len(pairMarginInfo) < 4 {
return nil, errors.New("invalid data received")
}
if tempResp.TradableBalance, ok = pairMarginInfo[0].(float64); !ok {
return nil, common.GetTypeAssertError("float64", pairMarginInfo[0], "MarginInfo.Data.TradableBalance")
}
if tempResp.GrossBalance, ok = pairMarginInfo[1].(float64); !ok {
return nil, common.GetTypeAssertError("float64", pairMarginInfo[1], "MarginInfo.Data.GlossBalance")
}
if tempResp.BestAskAmount, ok = pairMarginInfo[2].(float64); !ok {
return nil, common.GetTypeAssertError("float64", pairMarginInfo[2], "MarginInfo.Data.BestAskAmount")
}
if tempResp.BestBidAmount, ok = pairMarginInfo[3].(float64); !ok {
return nil, common.GetTypeAssertError("float64", pairMarginInfo[3], "MarginInfo.Data.BestBidAmount")
}
resp[x] = tempResp
}
return resp, nil
}
func defaultMarginV2Info(data []interface{}) (MarginInfoV2, error) {
var resp MarginInfoV2
var ok bool
if resp.Symbol, ok = data[1].(string); !ok {
return resp, common.GetTypeAssertError("string", data[1], "Symbol")
}
marginInfo, check := data[2].([]any)
if !check {
return resp, common.GetTypeAssertError("[]any", data[2], "MarginInfo.Data")
}
if len(marginInfo) < 4 {
return resp, errors.New("invalid data received")
}
if resp.TradableBalance, ok = marginInfo[0].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[0], "MarginInfo.Data.TradableBalance")
}
if resp.GrossBalance, ok = marginInfo[1].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[1], "MarginInfo.Data.GrossBalance")
}
if resp.BestAskAmount, ok = marginInfo[2].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[2], "MarginInfo.Data.BestAskAmount")
}
if resp.BestBidAmount, ok = marginInfo[3].(float64); !ok {
return resp, common.GetTypeAssertError("float64", marginInfo[3], "MarginInfo.Data.BestBidAmount")
}
return resp, nil
}
// GetV2MarginInfo gets v2 margin info for a symbol provided
// symbol: base, sym_all, any other trading symbol example tBTCUSD
func (b *Bitfinex) GetV2MarginInfo(ctx context.Context, symbol string) ([]MarginInfoV2, error) {
var data []interface{}
err := b.SendAuthenticatedHTTPRequestV2(ctx,
exchange.RestSpot, http.MethodPost,
bitfinexV2MarginInfo+symbol,
nil,
&data,
getMarginInfoRate)
if err != nil {
return nil, err
}
var tempResp MarginInfoV2
switch symbol {
case "base":
tempResp, err = baseMarginInfo(data)
if err != nil {
return nil, fmt.Errorf("%v - %s: %w", b.Name, symbol, err)
}
case "sym_all":
var resp []MarginInfoV2
resp, err = symbolMarginInfo(data)
return resp, err
default:
tempResp, err = defaultMarginV2Info(data)
if err != nil {
return nil, fmt.Errorf("%v - %s: %w", b.Name, symbol, err)
}
}
return []MarginInfoV2{tempResp}, nil
}
// GetV2MarginFunding gets borrowing rates for margin trading
func (b *Bitfinex) GetV2MarginFunding(ctx context.Context, symbol, amount string, period int32) (MarginV2FundingData, error) {
var resp []interface{}
var response MarginV2FundingData
params := make(map[string]interface{})
params["symbol"] = symbol
params["period"] = period
params["amount"] = amount
err := b.SendAuthenticatedHTTPRequestV2(ctx, exchange.RestSpot, http.MethodPost,
bitfinexV2MarginFunding,
params,
&resp,
getMarginInfoRate)
if err != nil {
return response, err
}
if len(resp) != 2 {
return response, errors.New("invalid data received")
}
avgRate, ok := resp[0].(float64)
if !ok {
return response, common.GetTypeAssertError("float64", resp[0], "MarketAveragePrice.PriceOrRate")
}
avgAmount, ok := resp[1].(float64)
if !ok {
return response, common.GetTypeAssertError("float64", resp[1], "MarketAveragePrice.Amount")
}
response.Symbol = symbol
response.RateAverage = avgRate
response.AmountAverage = avgAmount
return response, nil
}
// GetV2FundingInfo gets funding info for margin pairs
func (b *Bitfinex) GetV2FundingInfo(ctx context.Context, key string) (MarginFundingDataV2, error) {
var resp []interface{}
var response MarginFundingDataV2
err := b.SendAuthenticatedHTTPRequestV2(ctx, exchange.RestSpot, http.MethodPost,
fmt.Sprintf(bitfinexV2FundingInfo, key),
nil,
&resp,
getAccountFees)
if err != nil {
return response, err
}
if len(resp) != 3 {
return response, errors.New("invalid data received")
}
sym, ok := resp[0].(string)
if !ok {
return response, common.GetTypeAssertError("string", resp[0], "FundingInfo.sym")
}
symbol, ok := resp[1].(string)
if !ok {
return response, common.GetTypeAssertError("string", resp[1], "FundingInfo.Symbol")
}
fundingData, ok := resp[2].([]any)
if !ok {
return response, common.GetTypeAssertError("[]any", resp[2], "FundingInfo.FundingRateOrDuration")
}
response.Sym = sym
response.Symbol = symbol
if len(fundingData) < 4 {
return response, fmt.Errorf("%v GetV2FundingInfo: invalid length of fundingData", b.Name)
}
if response.Data.YieldLoan, ok = fundingData[0].(float64); !ok {
return response, errors.New("type conversion failed for YieldLoan")
}
if response.Data.YieldLend, ok = fundingData[1].(float64); !ok {
return response, errors.New("type conversion failed for YieldLend")
}
if response.Data.DurationLoan, ok = fundingData[2].(float64); !ok {
return response, errors.New("type conversion failed for DurationLoan")
}
if response.Data.DurationLend, ok = fundingData[3].(float64); !ok {
return response, errors.New("type conversion failed for DurationLend")
}
return response, nil
}
// GetAccountInfoV2 gets V2 account data
func (b *Bitfinex) GetAccountInfoV2(ctx context.Context) (AccountV2Data, error) {
var resp AccountV2Data
var data []interface{}
err := b.SendAuthenticatedHTTPRequestV2(ctx, exchange.RestSpot, http.MethodPost,
bitfinexV2AccountInfo,
nil,
&data,
getAccountFees)
if err != nil {
return resp, err
}
if len(data) < 8 {
return resp, fmt.Errorf("%v GetAccountInfoV2: invalid length of data", b.Name)
}
var ok bool
var tempString string
var tempFloat float64
if tempFloat, ok = data[0].(float64); !ok {
return resp, common.GetTypeAssertError("float64", data[0], "AccountInfo.AccountID")
}
resp.ID = int64(tempFloat)
if tempString, ok = data[1].(string); !ok {
return resp, common.GetTypeAssertError("string", data[1], "AccountInfo.AccountEmail")
}
resp.Email = tempString
if tempString, ok = data[2].(string); !ok {
return resp, common.GetTypeAssertError("string", data[2], "AccountInfo.AccountUsername")
}
resp.Username = tempString
if tempFloat, ok = data[3].(float64); !ok {
return resp, common.GetTypeAssertError("float64", data[3], "AccountInfo.Account.MTSAccountCreate")
}
resp.MTSAccountCreate = int64(tempFloat)
if tempFloat, ok = data[4].(float64); !ok {
return resp, common.GetTypeAssertError("float64", data[4], "AccountInfo.AccountVerified")
}
resp.Verified = int64(tempFloat)
if tempString, ok = data[7].(string); !ok {
return resp, common.GetTypeAssertError("string", data[7], "AccountInfo.AccountTimezone")
}
resp.Timezone = tempString
return resp, nil
}
// GetV2Balances gets v2 balances
func (b *Bitfinex) GetV2Balances(ctx context.Context) ([]WalletDataV2, error) {
var data [][4]interface{}
err := b.SendAuthenticatedHTTPRequestV2(ctx,
exchange.RestSpot, http.MethodPost,
bitfinexV2Balances,
nil,
&data,
getAccountFees)
if err != nil {
return nil, err
}
resp := make([]WalletDataV2, len(data))
for x := range data {
walletType, ok := data[x][0].(string)
if !ok {
return resp, common.GetTypeAssertError("string", data[x][0], "Wallets.WalletType")
}
currency, ok := data[x][1].(string)
if !ok {
return resp, common.GetTypeAssertError("string", data[x][1], "Wallets.Currency")
}
balance, ok := data[x][2].(float64)
if !ok {
return resp, common.GetTypeAssertError("float64", data[x][2], "Wallets.WalletBalance")
}
unsettledInterest, ok := data[x][3].(float64)
if !ok {
return resp, common.GetTypeAssertError("float64", data[x][3], "Wallets.UnsettledInterest")
}
resp[x] = WalletDataV2{
WalletType: walletType,
Currency: currency,
Balance: balance,
UnsettledInterest: unsettledInterest,
}
}
return resp, nil
}
// GetPairs gets pairs for different assets
func (b *Bitfinex) GetPairs(ctx context.Context, a asset.Item) ([]string, error) {
switch a {
case asset.Spot:
list, err := b.GetSiteListConfigData(ctx, bitfinexSpotPairs)
if err != nil {
return nil, err
}
filter, err := b.GetSiteListConfigData(ctx, bitfinexSecuritiesPairs)
if err != nil {
return nil, err
}
filtered := make([]string, 0, len(list))
for x := range list {
if common.StringDataCompare(filter, list[x]) {
continue
}
filtered = append(filtered, list[x])
}
return filtered, nil
case asset.Margin:
return b.GetSiteListConfigData(ctx, bitfinexMarginPairs)
case asset.Futures:
return b.GetSiteListConfigData(ctx, bitfinexFuturesPairs)
case asset.MarginFunding:
funding, err := b.GetTickerBatch(ctx)
if err != nil {
return nil, err
}
var pairs []string
for key := range funding {
symbol := key[1:]
if key[0] != 'f' || strings.Contains(symbol, ":") || len(symbol) > 6 {
continue
}
pairs = append(pairs, symbol)
}
return pairs, nil
default:
return nil, fmt.Errorf("%v GetPairs: %v %w", b.Name, a, asset.ErrNotSupported)
}
}
// GetSiteListConfigData returns site configuration data by pub:list:{Object}:{Detail}
// string sets.
// NOTE: See https://docs.bitfinex.com/reference/rest-public-conf
func (b *Bitfinex) GetSiteListConfigData(ctx context.Context, set string) ([]string, error) {
if set == "" {
return nil, errSetCannotBeEmpty
}
var resp [][]string
path := bitfinexAPIVersion2 + set
err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp, status)
if err != nil {
return nil, err
}
if len(resp) != 1 {
return nil, errors.New("invalid response")
}
return resp[0], nil
}
// GetSiteInfoConfigData returns site configuration data by pub:info:{AssetType} as a map
// path should be bitfinexInfoPairs or bitfinexInfoPairsFuture???
// NOTE: See https://docs.bitfinex.com/reference/rest-public-conf
func (b *Bitfinex) GetSiteInfoConfigData(ctx context.Context, assetType asset.Item) ([]order.MinMaxLevel, error) {
var path string
switch assetType {
case asset.Spot:
path = bitfinexInfoPairs
case asset.Futures:
path = bitfinexInfoFuturePairs
default:
return nil, fmt.Errorf("invalid asset type for GetSiteInfoConfigData: %s", assetType)
}
url := bitfinexAPIVersion2 + path
var resp [][][]any
err := b.SendHTTPRequest(ctx, exchange.RestSpot, url, &resp, status)
if err != nil {
return nil, err
}
if len(resp) != 1 {
return nil, errors.New("response did not contain only one item")
}
data := resp[0]
pairs := make([]order.MinMaxLevel, 0, len(data))
for i := range data {
if len(data[i]) != 2 {
return nil, errors.New("response contained a tuple without exactly 2 items")
}
pairSymbol, ok := data[i][0].(string)
if !ok {
return nil, fmt.Errorf("could not convert first item in SiteInfoConfigData to string: Type is %T", data[i][0])
}
if strings.Contains(pairSymbol, "TEST") {
continue
}
// SIC: Array type really is any. It contains nils and strings
info, ok := data[i][1].([]any)
if !ok {
return nil, fmt.Errorf("could not convert second item in SiteInfoConfigData to []any; Type is %T", data[i][1])
}
if len(info) < 5 {
return nil, errors.New("response contained order info with less than 5 elements")
}
minOrder, err := convert.FloatFromString(info[3])
if err != nil {
return nil, fmt.Errorf("could not convert MinOrderAmount: %s", err)
}
maxOrder, err := convert.FloatFromString(info[4])
if err != nil {
return nil, fmt.Errorf("could not convert MaxOrderAmount: %s", err)
}
pair, err := currency.NewPairFromString(pairSymbol)
if err != nil {
return nil, err
}
pairs = append(pairs, order.MinMaxLevel{
Asset: assetType,
Pair: pair,
MinimumBaseAmount: minOrder,
MaximumBaseAmount: maxOrder,
})
}
return pairs, nil
}
// GetDerivativeStatusInfo gets status data for the queried derivative
func (b *Bitfinex) GetDerivativeStatusInfo(ctx context.Context, keys, startTime, endTime string, sort, limit int64) ([]DerivativeDataResponse, error) {
params := url.Values{}
params.Set("keys", keys)
if startTime != "" {
params.Set("start", startTime)
}
if endTime != "" {
params.Set("end", endTime)
}
if sort != 0 {
params.Set("sort", strconv.FormatInt(sort, 10))
}
if limit != 0 {
params.Set("limit", strconv.FormatInt(limit, 10))
}
var result [][]interface{}
path := bitfinexAPIVersion2 + bitfinexDerivativeData +
params.Encode()
err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &result, status)
if err != nil {
return nil, err
}
finalResp := make([]DerivativeDataResponse, len(result))
for z := range result {
if len(result[z]) < 19 {
return finalResp, fmt.Errorf("%v GetDerivativeStatusInfo: invalid response, array length too small, check api docs for updates", b.Name)
}
var response DerivativeDataResponse
var ok bool
if response.Key, ok = result[z][0].(string); !ok {
return finalResp, common.GetTypeAssertError("string", result[z][0], "DerivativesStatus.Key")
}
if response.MTS, ok = result[z][1].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][1], "DerivativesStatus.MTS")
}
if response.DerivPrice, ok = result[z][3].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][3], "DerivativesStatus.DerivPrice")
}
if response.SpotPrice, ok = result[z][4].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][4], "DerivativesStatus.SpotPrice")
}
if response.InsuranceFundBalance, ok = result[z][6].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][6], "DerivativesStatus.InsuranceFundBalance")
}
if response.NextFundingEventTS, ok = result[z][8].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][8], "DerivativesStatus.NextFundingEventMTS")
}
if response.NextFundingAccrued, ok = result[z][9].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][9], "DerivativesStatus.NextFundingAccrued")
}
if response.NextFundingStep, ok = result[z][10].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][10], "DerivativesStatus.NextFundingStep")
}
if response.CurrentFunding, ok = result[z][12].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][12], "DerivativesStatus.CurrentFunding")
}
if response.MarkPrice, ok = result[z][15].(float64); !ok {
return finalResp, common.GetTypeAssertError("float64", result[z][15], "DerivativesStatus.MarkPrice")
}
switch t := result[z][18].(type) {
case float64:
response.OpenInterest = t
case nil:
break // SupportedCapability will default to 0
default:
return finalResp, common.GetTypeAssertError(" float64|nil", t, "DerivativesStatus.SupportedCapability")
}
finalResp[z] = response
}
return finalResp, nil
}
// GetTickerBatch returns all supported ticker information
func (b *Bitfinex) GetTickerBatch(ctx context.Context) (map[string]*Ticker, error) {
var response [][]any
path := bitfinexAPIVersion2 + bitfinexTickerBatch +
"?symbols=ALL"
err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &response, tickerBatch)
if err != nil {
return nil, err
}
var tickErrs error
var tickers = make(map[string]*Ticker)
for _, tickResp := range response {
symbol, ok := tickResp[0].(string)
if !ok {
tickErrs = common.AppendError(tickErrs, fmt.Errorf("%w: %v", errTickerInvalidSymbol, symbol))
continue
}
if t, err := tickerFromResp(symbol, tickResp[1:]); err != nil {
// We get too frequent intermittent formatting errors from tALT2612:USD to treat them as errors
if !errors.Is(err, errTickerInvalidResp) {
tickErrs = common.AppendError(tickErrs, err)
}
} else {
tickers[symbol] = t
}
}
return tickers, tickErrs
}
// GetTicker returns ticker information for one symbol
func (b *Bitfinex) GetTicker(ctx context.Context, symbol string) (*Ticker, error) {
var response []any
path := bitfinexAPIVersion2 + bitfinexTicker + symbol
err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &response, tickerFunction)
if err != nil {
return nil, err
}
t, err := tickerFromResp(symbol, response)
if err != nil {
return nil, err
}
return t, nil
}
var tickerFields = []string{"Bid", "BidSize", "Ask", "AskSize", "DailyChange", "DailyChangePercentage", "LastPrice", "DailyVolume", "DailyHigh", "DailyLow"}
func tickerFromResp(symbol string, respAny []any) (*Ticker, error) {
if strings.HasPrefix(symbol, "f") {
return tickerFromFundingResp(symbol, respAny)
}
if len(respAny) != 10 {
return nil, fmt.Errorf("%w for %s: %v", errTickerInvalidFieldCount, symbol, respAny)
}
resp := make([]float64, 10)
for i := range respAny {
f, ok := respAny[i].(float64)
if !ok {
return nil, fmt.Errorf("%w for %s field %s from %v", errTickerInvalidResp, symbol, tickerFields[i], respAny)
}
resp[i] = f
}
return &Ticker{
Bid: resp[0],
BidSize: resp[1],
Ask: resp[2],
AskSize: resp[3],
DailyChange: resp[4],
DailyChangePerc: resp[5],
Last: resp[6],
Volume: resp[7],
High: resp[8],
Low: resp[9],
}, nil
}
var fundingTickerFields = []string{"FlashReturnRate", "Bid", "BidPeriod", "BidSize", "Ask", "AskPeriod", "AskSize", "DailyChange", "DailyChangePercentage", "LastPrice", "DailyVolume", "DailyHigh", "DailyLow", "", "", "FFRAmountAvailable"}
func tickerFromFundingResp(symbol string, respAny []any) (*Ticker, error) {
if len(respAny) != 16 {
return nil, fmt.Errorf("%w for %s: %v", errTickerInvalidFieldCount, symbol, respAny)
}
resp := make([]float64, 16)
for i := range respAny {
if fundingTickerFields[i] == "" { // Unused nil fields
continue
}
f, ok := respAny[i].(float64)
if !ok {
return nil, fmt.Errorf("%w for %s field %s from %v", errTickerInvalidResp, symbol, fundingTickerFields[i], respAny)
}
resp[i] = f
}
return &Ticker{
FlashReturnRate: resp[0],
Bid: resp[1],
BidPeriod: int64(resp[2]),
BidSize: resp[3],
Ask: resp[4],
AskPeriod: int64(resp[5]),
AskSize: resp[6],
DailyChange: resp[7],
DailyChangePerc: resp[8],
Last: resp[9],
Volume: resp[10],
High: resp[11],
Low: resp[12],
FFRAmountAvailable: resp[15],
}, nil
}
// GetTrades gets historic trades that occurred on the exchange
//
// currencyPair e.g. "tBTCUSD"
// timestampStart is a millisecond timestamp
// timestampEnd is a millisecond timestamp
// reOrderResp reorders the returned data.
func (b *Bitfinex) GetTrades(ctx context.Context, currencyPair string, limit, timestampStart, timestampEnd int64, reOrderResp bool) ([]Trade, error) {
v := url.Values{}
if limit > 0 {
v.Set("limit", strconv.FormatInt(limit, 10))
}
if timestampStart > 0 {
v.Set("start", strconv.FormatInt(timestampStart, 10))
}
if timestampEnd > 0 {
v.Set("end", strconv.FormatInt(timestampEnd, 10))
}
sortVal := "0"
if reOrderResp {
sortVal = "1"
}
v.Set("sort", sortVal)
path := bitfinexAPIVersion2 + bitfinexTrades + currencyPair + "/hist" + "?" + v.Encode()
var resp [][]interface{}
err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp, tradeRateLimit)
if err != nil {
return nil, err
}
history := make([]Trade, len(resp))
for i := range resp {
amount, ok := resp[i][2].(float64)
if !ok {
return nil, errors.New("unable to type assert amount")
}
side := order.Buy.String()
if amount < 0 {
side = order.Sell.String()
amount *= -1
}
tid, ok := resp[i][0].(float64)
if !ok {
return nil, errors.New("unable to type assert trade ID")
}
timestamp, ok := resp[i][1].(float64)
if !ok {
return nil, errors.New("unable to type assert timestamp")
}
if len(resp[i]) > 4 {
var rate float64
rate, ok = resp[i][3].(float64)
if !ok {
return nil, errors.New("unable to type assert rate")
}
var period float64
period, ok = resp[i][4].(float64)
if !ok {
return nil, errors.New("unable to type assert period")
}
history[i] = Trade{
TID: int64(tid),
Timestamp: int64(timestamp),
Amount: amount,
Rate: rate,
Period: int64(period),
Type: side,
}
continue
}
price, ok := resp[i][3].(float64)
if !ok {
return nil, errors.New("unable to type assert price")
}
history[i] = Trade{
TID: int64(tid),
Timestamp: int64(timestamp),
Amount: amount,
Price: price,
Type: side,
}
}
return history, nil
}
// GetOrderbook retrieves the orderbook bid and ask price points for a currency
// pair - By default the response will return 25 bid and 25 ask price points.
// symbol - Example "tBTCUSD"
// precision - P0,P1,P2,P3,R0
// Values can contain limit amounts for both the asks and bids - Example
// "len" = 100
func (b *Bitfinex) GetOrderbook(ctx context.Context, symbol, precision string, limit int64) (Orderbook, error) {
var u = url.Values{}
if limit > 0 {
u.Set("len", strconv.FormatInt(limit, 10))
}
path := bitfinexAPIVersion2 + bitfinexOrderbook + symbol + "/" + precision + "?" + u.Encode()
var response [][]interface{}
err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &response, orderbookFunction)
if err != nil {
return Orderbook{}, err
}
var o Orderbook
if precision == "R0" {
// Raw book changes the return
for x := range response {
var b Book
if len(response[x]) > 3 {
// Funding currency
var ok bool
if b.Amount, ok = response[x][3].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert amount")
}
if b.Rate, ok = response[x][2].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert rate")
}
if b.Period, ok = response[x][1].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert period")
}
orderID, ok := response[x][0].(float64)
if !ok {
return Orderbook{}, errors.New("unable to type assert orderID")
}
b.OrderID = int64(orderID)
if b.Amount > 0 {
o.Asks = append(o.Asks, b)
} else {
b.Amount *= -1
o.Bids = append(o.Bids, b)
}
} else {
// Trading currency
var ok bool
if b.Amount, ok = response[x][2].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert amount")
}
if b.Price, ok = response[x][1].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert price")
}
orderID, ok := response[x][0].(float64)
if !ok {
return Orderbook{}, errors.New("unable to type assert order ID")
}
b.OrderID = int64(orderID)
if b.Amount > 0 {
o.Bids = append(o.Bids, b)
} else {
b.Amount *= -1
o.Asks = append(o.Asks, b)
}
}
}
} else {
for x := range response {
var b Book
if len(response[x]) > 3 {
// Funding currency
var ok bool
if b.Amount, ok = response[x][3].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert amount")
}
count, ok := response[x][2].(float64)
if !ok {
return Orderbook{}, errors.New("unable to type assert count")
}
b.Count = int64(count)
if b.Period, ok = response[x][1].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert period")
}
if b.Rate, ok = response[x][0].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert rate")
}
if b.Amount > 0 {
o.Asks = append(o.Asks, b)
} else {
b.Amount *= -1
o.Bids = append(o.Bids, b)
}
} else {
// Trading currency
var ok bool
if b.Amount, ok = response[x][2].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert amount")
}
count, ok := response[x][1].(float64)
if !ok {
return Orderbook{}, errors.New("unable to type assert count")
}
b.Count = int64(count)
if b.Price, ok = response[x][0].(float64); !ok {
return Orderbook{}, errors.New("unable to type assert price")
}
if b.Amount > 0 {
o.Bids = append(o.Bids, b)
} else {
b.Amount *= -1
o.Asks = append(o.Asks, b)
}
}
}
}
return o, nil
}
// GetStats returns various statistics about the requested pair
func (b *Bitfinex) GetStats(ctx context.Context, symbol string) ([]Stat, error) {
var response []Stat
path := bitfinexAPIVersion + bitfinexStats + symbol
return response, b.SendHTTPRequest(ctx, exchange.RestSpot, path, &response, statsV1)
}
// GetFundingBook the entire margin funding book for both bids and asks sides
// per currency string
// symbol - example "USD"
// WARNING: Orderbook now has this support, will be deprecated once a full
// conversion to full V2 API update is done.
func (b *Bitfinex) GetFundingBook(ctx context.Context, symbol string) (FundingBook, error) {
response := FundingBook{}
path := bitfinexAPIVersion + bitfinexLendbook + symbol
if err := b.SendHTTPRequest(ctx, exchange.RestSpot, path, &response, fundingbook); err != nil {
return response, err
}
return response, nil
}
// GetLends returns a list of the most recent funding data for the given
// currency: total amount provided and Flash Return Rate (in % by 365 days)
// over time
// Symbol - example "USD"
func (b *Bitfinex) GetLends(ctx context.Context, symbol string, values url.Values) ([]Lends, error) {
var response []Lends
path := common.EncodeURLValues(bitfinexAPIVersion+
bitfinexLends+
symbol,
values)
return response, b.SendHTTPRequest(ctx, exchange.RestSpot, path, &response, lends)
}
// GetCandles returns candle chart data
// timeFrame values: '1m', '5m', '15m', '30m', '1h', '3h', '6h', '12h', '1D', '1W', '14D', '1M'
// section values: last or hist
func (b *Bitfinex) GetCandles(ctx context.Context, symbol, timeFrame string, start, end int64, limit uint32, historic bool) ([]Candle, error) {
var fundingPeriod string
if symbol[0] == 'f' {