-
Notifications
You must be signed in to change notification settings - Fork 820
/
exchange.go
1949 lines (1719 loc) · 60.7 KB
/
exchange.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 exchange
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"unicode"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/common/key"
"github.com/thrasher-corp/gocryptotrader/config"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/collateral"
"github.com/thrasher-corp/gocryptotrader/exchanges/currencystate"
"github.com/thrasher-corp/gocryptotrader/exchanges/fundingrate"
"github.com/thrasher-corp/gocryptotrader/exchanges/futures"
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
"github.com/thrasher-corp/gocryptotrader/exchanges/margin"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/protocol"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
"github.com/thrasher-corp/gocryptotrader/exchanges/subscription"
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/gocryptotrader/portfolio/banking"
)
const (
warningBase64DecryptSecretKeyFailed = "exchange %s unable to base64 decode secret key.. Disabling Authenticated API support" //nolint // False positive (G101: Potential hardcoded credentials)
// DefaultHTTPTimeout is the default HTTP/HTTPS Timeout for exchange requests
DefaultHTTPTimeout = time.Second * 15
// DefaultWebsocketResponseCheckTimeout is the default delay in checking for an expected websocket response
DefaultWebsocketResponseCheckTimeout = time.Millisecond * 50
// DefaultWebsocketResponseMaxLimit is the default max wait for an expected websocket response before a timeout
DefaultWebsocketResponseMaxLimit = time.Second * 7
// DefaultWebsocketOrderbookBufferLimit is the maximum number of orderbook updates that get stored before being applied
DefaultWebsocketOrderbookBufferLimit = 5
)
// Public Errors
var (
ErrExchangeNameIsEmpty = errors.New("exchange name is empty")
ErrSymbolCannotBeMatched = errors.New("symbol cannot be matched")
)
var (
errEndpointStringNotFound = errors.New("endpoint string not found")
errConfigPairFormatRequiresDelimiter = errors.New("config pair format requires delimiter")
errSetDefaultsNotCalled = errors.New("set defaults not called")
errExchangeIsNil = errors.New("exchange is nil")
)
// SetRequester sets the instance of the requester
func (b *Base) SetRequester(r *request.Requester) error {
if r == nil {
return fmt.Errorf("%s cannot set requester, no requester provided", b.Name)
}
b.Requester = r
return nil
}
// SetClientProxyAddress sets a proxy address for REST and websocket requests
func (b *Base) SetClientProxyAddress(addr string) error {
if addr == "" {
return nil
}
proxy, err := url.Parse(addr)
if err != nil {
return fmt.Errorf("setting proxy address error %s",
err)
}
err = b.Requester.SetProxy(proxy)
if err != nil {
return err
}
if b.Websocket != nil {
err = b.Websocket.SetProxyAddress(addr)
if err != nil {
return err
}
}
return nil
}
// SetFeatureDefaults sets the exchanges default feature support set
func (b *Base) SetFeatureDefaults() {
if b.Config.Features == nil {
s := &config.FeaturesConfig{
Supports: config.FeaturesSupportedConfig{
Websocket: b.Features.Supports.Websocket,
REST: b.Features.Supports.REST,
RESTCapabilities: protocol.Features{
AutoPairUpdates: b.Features.Supports.RESTCapabilities.AutoPairUpdates,
},
},
}
if b.Config.SupportsAutoPairUpdates != nil {
s.Supports.RESTCapabilities.AutoPairUpdates = *b.Config.SupportsAutoPairUpdates
s.Enabled.AutoPairUpdates = *b.Config.SupportsAutoPairUpdates
} else {
s.Supports.RESTCapabilities.AutoPairUpdates = b.Features.Supports.RESTCapabilities.AutoPairUpdates
s.Enabled.AutoPairUpdates = b.Features.Supports.RESTCapabilities.AutoPairUpdates
if !s.Supports.RESTCapabilities.AutoPairUpdates {
b.Config.CurrencyPairs.LastUpdated = time.Now().Unix()
b.CurrencyPairs.LastUpdated = b.Config.CurrencyPairs.LastUpdated
}
}
b.Config.Features = s
b.Config.SupportsAutoPairUpdates = nil
} else {
if b.Features.Supports.RESTCapabilities.AutoPairUpdates != b.Config.Features.Supports.RESTCapabilities.AutoPairUpdates {
b.Config.Features.Supports.RESTCapabilities.AutoPairUpdates = b.Features.Supports.RESTCapabilities.AutoPairUpdates
if !b.Config.Features.Supports.RESTCapabilities.AutoPairUpdates {
b.Config.CurrencyPairs.LastUpdated = time.Now().Unix()
}
}
if b.Features.Supports.REST != b.Config.Features.Supports.REST {
b.Config.Features.Supports.REST = b.Features.Supports.REST
}
if b.Features.Supports.RESTCapabilities.TickerBatching != b.Config.Features.Supports.RESTCapabilities.TickerBatching {
b.Config.Features.Supports.RESTCapabilities.TickerBatching = b.Features.Supports.RESTCapabilities.TickerBatching
}
if b.Features.Supports.Websocket != b.Config.Features.Supports.Websocket {
b.Config.Features.Supports.Websocket = b.Features.Supports.Websocket
}
if b.IsSaveTradeDataEnabled() != b.Config.Features.Enabled.SaveTradeData {
b.SetSaveTradeDataStatus(b.Config.Features.Enabled.SaveTradeData)
}
if b.IsTradeFeedEnabled() != b.Config.Features.Enabled.TradeFeed {
b.SetTradeFeedStatus(b.Config.Features.Enabled.TradeFeed)
}
if b.IsFillsFeedEnabled() != b.Config.Features.Enabled.FillsFeed {
b.SetFillsFeedStatus(b.Config.Features.Enabled.FillsFeed)
}
b.SetSubscriptionsFromConfig()
b.Features.Enabled.AutoPairUpdates = b.Config.Features.Enabled.AutoPairUpdates
}
}
// SetSubscriptionsFromConfig sets the subscriptions from config
// If the subscriptions config is empty then Config will be updated from the exchange subscriptions,
// allowing e.SetDefaults to set default subscriptions for an exchange to update user's config
// Subscriptions not Enabled are skipped, meaning that e.Features.Subscriptions only contains Enabled subscriptions
func (b *Base) SetSubscriptionsFromConfig() {
b.settingsMutex.Lock()
defer b.settingsMutex.Unlock()
if len(b.Config.Features.Subscriptions) == 0 {
// Set config from the defaults, including any disabled subscriptions
b.Config.Features.Subscriptions = b.Features.Subscriptions
}
b.Features.Subscriptions = b.Config.Features.Subscriptions.Enabled()
if b.Verbose {
names := make([]string, 0, len(b.Features.Subscriptions))
for _, s := range b.Features.Subscriptions {
names = append(names, s.Channel)
}
log.Debugf(log.ExchangeSys, "Set %v 'Subscriptions' to %v", b.Name, strings.Join(names, ", "))
}
}
// SupportsRESTTickerBatchUpdates returns whether or not the
// exchange supports REST batch ticker fetching
func (b *Base) SupportsRESTTickerBatchUpdates() bool {
return b.Features.Supports.RESTCapabilities.TickerBatching
}
// SupportsAutoPairUpdates returns whether or not the exchange supports
// auto currency pair updating
func (b *Base) SupportsAutoPairUpdates() bool {
return b.Features.Supports.RESTCapabilities.AutoPairUpdates ||
b.Features.Supports.WebsocketCapabilities.AutoPairUpdates
}
// GetLastPairsUpdateTime returns the unix timestamp of when the exchanges
// currency pairs were last updated
func (b *Base) GetLastPairsUpdateTime() int64 {
return b.CurrencyPairs.LastUpdated
}
// GetAssetTypes returns the either the enabled or available asset types for an
// individual exchange
func (b *Base) GetAssetTypes(enabled bool) asset.Items {
return b.CurrencyPairs.GetAssetTypes(enabled)
}
// GetPairAssetType returns the associated asset type for the currency pair
// This method is only useful for exchanges that have pair names with multiple delimiters (BTC-USD-0626)
// Helpful if the exchange has only a single asset type but in that case the asset type can be hard coded
func (b *Base) GetPairAssetType(c currency.Pair) (asset.Item, error) {
assetTypes := b.GetAssetTypes(false)
for i := range assetTypes {
avail, err := b.GetAvailablePairs(assetTypes[i])
if err != nil {
return asset.Empty, err
}
if avail.Contains(c, true) {
return assetTypes[i], nil
}
}
return asset.Empty, errors.New("asset type not associated with currency pair")
}
// GetPairAndAssetTypeRequestFormatted returns the pair and the asset type
// when there is distinct differentiation between exchange request symbols asset
// types. e.g. "BTC-USD" Spot and "BTC_USD" PERP request formatted.
func (b *Base) GetPairAndAssetTypeRequestFormatted(symbol string) (currency.Pair, asset.Item, error) {
if symbol == "" {
return currency.EMPTYPAIR, asset.Empty, currency.ErrCurrencyPairEmpty
}
assetTypes := b.GetAssetTypes(true)
for i := range assetTypes {
pFmt, err := b.GetPairFormat(assetTypes[i], true)
if err != nil {
return currency.EMPTYPAIR, asset.Empty, err
}
enabled, err := b.GetEnabledPairs(assetTypes[i])
if err != nil {
return currency.EMPTYPAIR, asset.Empty, err
}
for j := range enabled {
if pFmt.Format(enabled[j]) == symbol {
return enabled[j], assetTypes[i], nil
}
}
}
return currency.EMPTYPAIR, asset.Empty, ErrSymbolCannotBeMatched
}
// GetClientBankAccounts returns banking details associated with
// a client for withdrawal purposes
func (b *Base) GetClientBankAccounts(exchangeName, withdrawalCurrency string) (*banking.Account, error) {
cfg := config.GetConfig()
return cfg.GetClientBankAccounts(exchangeName, withdrawalCurrency)
}
// GetExchangeBankAccounts returns banking details associated with an
// exchange for funding purposes
func (b *Base) GetExchangeBankAccounts(id, depositCurrency string) (*banking.Account, error) {
cfg := config.GetConfig()
return cfg.GetExchangeBankAccounts(b.Name, id, depositCurrency)
}
// SetCurrencyPairFormat checks the exchange request and config currency pair
// formats and syncs it with the exchanges SetDefault settings
func (b *Base) SetCurrencyPairFormat() error {
if b.Config.CurrencyPairs == nil {
b.Config.CurrencyPairs = new(currency.PairsManager)
}
b.Config.CurrencyPairs.UseGlobalFormat = b.CurrencyPairs.UseGlobalFormat
if b.Config.CurrencyPairs.UseGlobalFormat {
b.Config.CurrencyPairs.RequestFormat = b.CurrencyPairs.RequestFormat
b.Config.CurrencyPairs.ConfigFormat = b.CurrencyPairs.ConfigFormat
return nil
}
if b.Config.CurrencyPairs.ConfigFormat != nil {
b.Config.CurrencyPairs.ConfigFormat = nil
}
if b.Config.CurrencyPairs.RequestFormat != nil {
b.Config.CurrencyPairs.RequestFormat = nil
}
assetTypes := b.GetAssetTypes(false)
for x := range assetTypes {
if _, err := b.Config.CurrencyPairs.Get(assetTypes[x]); err != nil {
ps, err := b.CurrencyPairs.Get(assetTypes[x])
if err != nil {
return err
}
err = b.Config.CurrencyPairs.Store(assetTypes[x], ps)
if err != nil {
return err
}
}
}
return nil
}
// SetConfigPairs sets the exchanges currency pairs to the pairs set in the config
func (b *Base) SetConfigPairs() error {
assetTypes := b.Config.CurrencyPairs.GetAssetTypes(false)
exchangeAssets := b.CurrencyPairs.GetAssetTypes(false)
for x := range assetTypes {
if !exchangeAssets.Contains(assetTypes[x]) {
log.Warnf(log.ExchangeSys,
"%s exchange asset type %s unsupported, please manually remove from configuration",
b.Name,
assetTypes[x])
continue // If there are unsupported assets contained in config, skip.
}
var enabledAsset bool
if b.Config.CurrencyPairs.IsAssetEnabled(assetTypes[x]) == nil {
enabledAsset = true
}
err := b.CurrencyPairs.SetAssetEnabled(assetTypes[x], enabledAsset)
// Suppress error when assets are enabled by default and they are being
// enabled by config. A check for the inverse
// e.g. currency.ErrAssetAlreadyDisabled is not needed.
if err != nil && !errors.Is(err, currency.ErrAssetAlreadyEnabled) {
return err
}
cfgPS, err := b.Config.CurrencyPairs.Get(assetTypes[x])
if err != nil {
return err
}
if b.Config.CurrencyPairs.UseGlobalFormat {
err = b.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Available, false)
if err != nil {
return err
}
err = b.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Enabled, true)
if err != nil {
return err
}
continue
}
exchPS, err := b.CurrencyPairs.Get(assetTypes[x])
if err != nil {
return err
}
if exchPS.ConfigFormat != nil {
err = b.Config.CurrencyPairs.StoreFormat(assetTypes[x], exchPS.ConfigFormat, true)
if err != nil {
return err
}
}
if exchPS.RequestFormat != nil {
err = b.Config.CurrencyPairs.StoreFormat(assetTypes[x], exchPS.RequestFormat, false)
if err != nil {
return err
}
}
err = b.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Available, false)
if err != nil {
return err
}
err = b.CurrencyPairs.StorePairs(assetTypes[x], cfgPS.Enabled, true)
if err != nil {
return err
}
}
return nil
}
// GetName is a method that returns the name of the exchange base
func (b *Base) GetName() string {
return b.Name
}
// GetEnabledFeatures returns the exchanges enabled features
func (b *Base) GetEnabledFeatures() FeaturesEnabled {
return b.Features.Enabled
}
// GetSupportedFeatures returns the exchanges supported features
func (b *Base) GetSupportedFeatures() FeaturesSupported {
return b.Features.Supports
}
// GetPairFormat returns the pair format based on the exchange and asset type
func (b *Base) GetPairFormat(a asset.Item, r bool) (currency.PairFormat, error) {
return b.CurrencyPairs.GetFormat(a, r)
}
// GetEnabledPairs is a method that returns the enabled currency pairs of
// the exchange by asset type, if the asset type is disabled this will return no
// enabled pairs
func (b *Base) GetEnabledPairs(a asset.Item) (currency.Pairs, error) {
err := b.CurrencyPairs.IsAssetEnabled(a)
if err != nil {
return nil, err
}
format, err := b.GetPairFormat(a, false)
if err != nil {
return nil, err
}
enabledPairs, err := b.CurrencyPairs.GetPairs(a, true)
if err != nil {
return nil, err
}
return enabledPairs.Format(format), nil
}
// GetRequestFormattedPairAndAssetType is a method that returns the enabled currency pair of
// along with its asset type. Only use when there is no chance of the same name crossing over
func (b *Base) GetRequestFormattedPairAndAssetType(p string) (currency.Pair, asset.Item, error) {
assetTypes := b.GetAssetTypes(true)
for i := range assetTypes {
format, err := b.GetPairFormat(assetTypes[i], true)
if err != nil {
return currency.EMPTYPAIR, assetTypes[i], err
}
pairs, err := b.CurrencyPairs.GetPairs(assetTypes[i], true)
if err != nil {
return currency.EMPTYPAIR, assetTypes[i], err
}
for j := range pairs {
formattedPair := pairs[j].Format(format)
if strings.EqualFold(formattedPair.String(), p) {
return formattedPair, assetTypes[i], nil
}
}
}
return currency.EMPTYPAIR, asset.Empty, fmt.Errorf("%s %w", p, currency.ErrPairNotFound)
}
// GetAvailablePairs is a method that returns the available currency pairs
// of the exchange by asset type
func (b *Base) GetAvailablePairs(assetType asset.Item) (currency.Pairs, error) {
format, err := b.GetPairFormat(assetType, false)
if err != nil {
return nil, err
}
pairs, err := b.CurrencyPairs.GetPairs(assetType, false)
if err != nil {
return nil, err
}
return pairs.Format(format), nil
}
// SupportsPair returns true or not whether a currency pair exists in the
// exchange available currencies or not
func (b *Base) SupportsPair(p currency.Pair, enabledPairs bool, assetType asset.Item) error {
var pairs currency.Pairs
var err error
if enabledPairs {
pairs, err = b.GetEnabledPairs(assetType)
} else {
pairs, err = b.GetAvailablePairs(assetType)
}
if err != nil {
return err
}
if pairs.Contains(p, false) {
return nil
}
return fmt.Errorf("%w %v", currency.ErrCurrencyNotSupported, p)
}
// FormatExchangeCurrencies returns a string containing
// the exchanges formatted currency pairs
func (b *Base) FormatExchangeCurrencies(pairs []currency.Pair, assetType asset.Item) (string, error) {
var currencyItems strings.Builder
pairFmt, err := b.GetPairFormat(assetType, true)
if err != nil {
return "", err
}
for x := range pairs {
format, err := b.FormatExchangeCurrency(pairs[x], assetType)
if err != nil {
return "", err
}
currencyItems.WriteString(format.String())
if x == len(pairs)-1 {
continue
}
currencyItems.WriteString(pairFmt.Separator)
}
if currencyItems.Len() == 0 {
return "", errors.New("returned empty string")
}
return currencyItems.String(), nil
}
// FormatExchangeCurrency is a method that formats and returns a currency pair
// based on the user currency display preferences
func (b *Base) FormatExchangeCurrency(p currency.Pair, assetType asset.Item) (currency.Pair, error) {
if p.IsEmpty() {
return currency.EMPTYPAIR, currency.ErrCurrencyPairEmpty
}
pairFmt, err := b.GetPairFormat(assetType, true)
if err != nil {
return currency.EMPTYPAIR, err
}
return p.Format(pairFmt), nil
}
// SetEnabled is a method that sets if the exchange is enabled
func (b *Base) SetEnabled(enabled bool) {
b.settingsMutex.Lock()
b.Enabled = enabled
b.settingsMutex.Unlock()
}
// IsEnabled is a method that returns if the current exchange is enabled
func (b *Base) IsEnabled() bool {
if b == nil {
return false
}
b.settingsMutex.RLock()
defer b.settingsMutex.RUnlock()
return b.Enabled
}
// SetupDefaults sets the exchange settings based on the supplied config
func (b *Base) SetupDefaults(exch *config.Exchange) error {
err := exch.Validate()
if err != nil {
return err
}
b.Enabled = true
b.LoadedByConfig = true
b.Config = exch
b.Verbose = exch.Verbose
b.API.AuthenticatedSupport = exch.API.AuthenticatedSupport
b.API.AuthenticatedWebsocketSupport = exch.API.AuthenticatedWebsocketSupport
b.API.credentials.SubAccount = exch.API.Credentials.Subaccount
if b.API.AuthenticatedSupport || b.API.AuthenticatedWebsocketSupport {
b.SetCredentials(exch.API.Credentials.Key,
exch.API.Credentials.Secret,
exch.API.Credentials.ClientID,
exch.API.Credentials.Subaccount,
exch.API.Credentials.PEMKey,
exch.API.Credentials.OTPSecret,
)
}
if exch.HTTPTimeout <= time.Duration(0) {
exch.HTTPTimeout = DefaultHTTPTimeout
}
err = b.SetHTTPClientTimeout(exch.HTTPTimeout)
if err != nil {
return err
}
if exch.CurrencyPairs == nil {
exch.CurrencyPairs = &b.CurrencyPairs
a := exch.CurrencyPairs.GetAssetTypes(false)
for i := range a {
err = exch.CurrencyPairs.SetAssetEnabled(a[i], true)
if err != nil && !errors.Is(err, currency.ErrAssetAlreadyEnabled) {
return err
}
}
}
b.HTTPDebugging = exch.HTTPDebugging
b.BypassConfigFormatUpgrades = exch.CurrencyPairs.BypassConfigFormatUpgrades
err = b.SetHTTPClientUserAgent(exch.HTTPUserAgent)
if err != nil {
return err
}
err = b.SetCurrencyPairFormat()
if err != nil {
return err
}
err = b.SetConfigPairs()
if err != nil {
return err
}
b.SetFeatureDefaults()
if b.API.Endpoints == nil {
b.API.Endpoints = b.NewEndpoints()
}
err = b.SetAPIURL()
if err != nil {
return err
}
b.SetAPICredentialDefaults()
err = b.SetClientProxyAddress(exch.ProxyAddress)
if err != nil {
return err
}
b.BaseCurrencies = exch.BaseCurrencies
if exch.Orderbook.VerificationBypass {
log.Warnf(log.ExchangeSys,
"%s orderbook verification has been bypassed via config.",
b.Name)
}
b.CanVerifyOrderbook = !exch.Orderbook.VerificationBypass
b.States = currencystate.NewCurrencyStates()
return err
}
// SetPairs sets the exchange currency pairs for either enabledPairs or
// availablePairs
func (b *Base) SetPairs(pairs currency.Pairs, assetType asset.Item, enabled bool) error {
if len(pairs) == 0 {
return fmt.Errorf("%s SetPairs error - pairs is empty", b.Name)
}
pairFmt, err := b.GetPairFormat(assetType, false)
if err != nil {
return err
}
cPairs := make(currency.Pairs, len(pairs))
copy(cPairs, pairs)
for x := range pairs {
cPairs[x] = pairs[x].Format(pairFmt)
}
err = b.CurrencyPairs.StorePairs(assetType, cPairs, enabled)
if err != nil {
return err
}
return b.Config.CurrencyPairs.StorePairs(assetType, cPairs, enabled)
}
// EnsureOnePairEnabled not all assets have pairs, eg options
// search for an asset that does and enable one if none are enabled
// error if no currency pairs found for an entire exchange
func (b *Base) EnsureOnePairEnabled() error {
pair, item, err := b.CurrencyPairs.EnsureOnePairEnabled()
if err != nil {
return err
}
if !pair.IsEmpty() {
log.Warnf(log.ExchangeSys, "%v had no enabled pairs, %v %v pair has been enabled", b.Name, item, pair)
}
return nil
}
// UpdatePairs updates the exchange currency pairs for either enabledPairs or
// availablePairs
func (b *Base) UpdatePairs(incoming currency.Pairs, a asset.Item, enabled, force bool) error {
pFmt, err := b.GetPairFormat(a, false)
if err != nil {
return err
}
incoming, err = incoming.ValidateAndConform(pFmt, b.BypassConfigFormatUpgrades)
if err != nil {
return err
}
oldPairs, err := b.CurrencyPairs.GetPairs(a, enabled)
if err != nil {
return err
}
diff, err := oldPairs.FindDifferences(incoming, pFmt)
if err != nil {
return err
}
if force || len(diff.New) != 0 || len(diff.Remove) != 0 || diff.FormatDifference {
var updateType string
if enabled {
updateType = "enabled"
} else {
updateType = "available"
}
if force {
log.Debugf(log.ExchangeSys,
"%s forced update of %s [%v] pairs.",
b.Name,
updateType,
strings.ToUpper(a.String()))
} else {
if len(diff.New) > 0 {
log.Debugf(log.ExchangeSys,
"%s Updating %s pairs [%v] - Added: %s.\n",
b.Name,
updateType,
strings.ToUpper(a.String()),
diff.New)
}
if len(diff.Remove) > 0 {
log.Debugf(log.ExchangeSys,
"%s Updating %s pairs [%v] - Removed: %s.\n",
b.Name,
updateType,
strings.ToUpper(a.String()),
diff.Remove)
}
}
err = b.Config.CurrencyPairs.StorePairs(a, incoming, enabled)
if err != nil {
return err
}
err = b.CurrencyPairs.StorePairs(a, incoming, enabled)
if err != nil {
return err
}
}
if enabled {
return nil
}
// This section checks for differences after an available pairs adjustment
// which will remove currency pairs from enabled pairs that have been
// disabled by an exchange, adjust the entire list of enabled pairs if there
// is a required formatting change and it will also capture unintentional
// client inputs e.g. a client can enter `linkusd` via config and loaded
// into memory that might be unintentionally formatted too `lin-kusd` it
// will match that against the correct available pair in memory and apply
// correct formatting (LINK-USD) instead of being removed altogether which
// will require a shutdown and update of the config file to enable that
// asset.
enabledPairs, err := b.CurrencyPairs.GetPairs(a, true)
if err != nil &&
!errors.Is(err, currency.ErrPairNotContainedInAvailablePairs) &&
!errors.Is(err, currency.ErrPairDuplication) {
return err
}
if err == nil && !enabledPairs.HasFormatDifference(pFmt) {
return nil
}
diff, err = enabledPairs.FindDifferences(incoming, pFmt)
if err != nil {
return err
}
check := make(map[string]bool)
var target int
for x := range enabledPairs {
pairNoFmt := currency.EMPTYFORMAT.Format(enabledPairs[x])
if check[pairNoFmt] {
diff.Remove = diff.Remove.Add(enabledPairs[x])
continue
}
check[pairNoFmt] = true
if !diff.Remove.Contains(enabledPairs[x], true) {
enabledPairs[target] = enabledPairs[x].Format(pFmt)
} else {
var match currency.Pair
match, err = incoming.DeriveFrom(pairNoFmt)
if err != nil {
continue
}
diff.Remove = diff.Remove.Remove(enabledPairs[x])
enabledPairs[target] = match.Format(pFmt)
}
target++
}
enabledPairs = enabledPairs[:target]
if len(enabledPairs) == 0 && len(incoming) > 0 {
// NOTE: If enabled pairs are not populated for any reason.
var randomPair currency.Pair
randomPair, err = incoming.GetRandomPair()
if err != nil {
return err
}
log.Debugf(log.ExchangeSys, "%s Enabled pairs missing for %s. Added %s.\n",
b.Name,
strings.ToUpper(a.String()),
randomPair)
enabledPairs = currency.Pairs{randomPair}
}
if len(diff.Remove) > 0 {
log.Debugf(log.ExchangeSys, "%s Checked and updated enabled pairs [%v] - Removed: %s.\n",
b.Name,
strings.ToUpper(a.String()),
diff.Remove)
}
err = b.Config.CurrencyPairs.StorePairs(a, enabledPairs, true)
if err != nil {
return err
}
return b.CurrencyPairs.StorePairs(a, enabledPairs, true)
}
// SetAPIURL sets configuration API URL for an exchange
func (b *Base) SetAPIURL() error {
checkInsecureEndpoint := func(endpoint string) {
if strings.Contains(endpoint, "https") || strings.Contains(endpoint, "wss") {
return
}
log.Warnf(log.ExchangeSys,
"%s is using HTTP instead of HTTPS or WS instead of WSS [%s] for API functionality, an"+
" attacker could eavesdrop on this connection. Use at your"+
" own risk.",
b.Name, endpoint)
}
var err error
if b.Config.API.OldEndPoints != nil {
if b.Config.API.OldEndPoints.URL != "" && b.Config.API.OldEndPoints.URL != config.APIURLNonDefaultMessage {
err = b.API.Endpoints.SetRunning(RestSpot.String(), b.Config.API.OldEndPoints.URL)
if err != nil {
return err
}
checkInsecureEndpoint(b.Config.API.OldEndPoints.URL)
}
if b.Config.API.OldEndPoints.URLSecondary != "" && b.Config.API.OldEndPoints.URLSecondary != config.APIURLNonDefaultMessage {
err = b.API.Endpoints.SetRunning(RestSpotSupplementary.String(), b.Config.API.OldEndPoints.URLSecondary)
if err != nil {
return err
}
checkInsecureEndpoint(b.Config.API.OldEndPoints.URLSecondary)
}
if b.Config.API.OldEndPoints.WebsocketURL != "" && b.Config.API.OldEndPoints.WebsocketURL != config.WebsocketURLNonDefaultMessage {
err = b.API.Endpoints.SetRunning(WebsocketSpot.String(), b.Config.API.OldEndPoints.WebsocketURL)
if err != nil {
return err
}
checkInsecureEndpoint(b.Config.API.OldEndPoints.WebsocketURL)
}
b.Config.API.OldEndPoints = nil
} else if b.Config.API.Endpoints != nil {
for key, val := range b.Config.API.Endpoints {
if val == "" ||
val == config.APIURLNonDefaultMessage ||
val == config.WebsocketURLNonDefaultMessage {
continue
}
var u URL
u, err = getURLTypeFromString(key)
if err != nil {
return err
}
var defaultURL string
defaultURL, err = b.API.Endpoints.GetURL(u)
if err != nil {
log.Warnf(
log.ExchangeSys,
"%s: Config cannot match with default endpoint URL: [%s] with key: [%s], please remove or update core support endpoints.",
b.Name,
val,
u)
continue
}
if defaultURL == val {
continue
}
log.Warnf(
log.ExchangeSys,
"%s: Config is overwriting default endpoint URL values from: [%s] to: [%s] for: [%s]",
b.Name,
defaultURL,
val,
u)
checkInsecureEndpoint(val)
err = b.API.Endpoints.SetRunning(key, val)
if err != nil {
return err
}
}
}
runningMap := b.API.Endpoints.GetURLMap()
b.Config.API.Endpoints = runningMap
return nil
}
// SupportsREST returns whether or not the exchange supports
// REST
func (b *Base) SupportsREST() bool {
return b.Features.Supports.REST
}
// GetWithdrawPermissions passes through the exchange's withdraw permissions
func (b *Base) GetWithdrawPermissions() uint32 {
return b.Features.Supports.WithdrawPermissions
}
// SupportsWithdrawPermissions compares the supplied permissions with the exchange's to verify they're supported
func (b *Base) SupportsWithdrawPermissions(permissions uint32) bool {
exchangePermissions := b.GetWithdrawPermissions()
return permissions&exchangePermissions == permissions
}
// FormatWithdrawPermissions will return each of the exchange's compatible withdrawal methods in readable form
func (b *Base) FormatWithdrawPermissions() string {
var services []string
for i := range 32 {
var check uint32 = 1 << uint32(i)
if b.GetWithdrawPermissions()&check != 0 {
switch check {
case AutoWithdrawCrypto:
services = append(services, AutoWithdrawCryptoText)
case AutoWithdrawCryptoWithAPIPermission:
services = append(services, AutoWithdrawCryptoWithAPIPermissionText)
case AutoWithdrawCryptoWithSetup:
services = append(services, AutoWithdrawCryptoWithSetupText)
case WithdrawCryptoWith2FA:
services = append(services, WithdrawCryptoWith2FAText)
case WithdrawCryptoWithSMS:
services = append(services, WithdrawCryptoWithSMSText)
case WithdrawCryptoWithEmail:
services = append(services, WithdrawCryptoWithEmailText)
case WithdrawCryptoWithWebsiteApproval:
services = append(services, WithdrawCryptoWithWebsiteApprovalText)
case WithdrawCryptoWithAPIPermission:
services = append(services, WithdrawCryptoWithAPIPermissionText)
case AutoWithdrawFiat:
services = append(services, AutoWithdrawFiatText)
case AutoWithdrawFiatWithAPIPermission:
services = append(services, AutoWithdrawFiatWithAPIPermissionText)
case AutoWithdrawFiatWithSetup:
services = append(services, AutoWithdrawFiatWithSetupText)
case WithdrawFiatWith2FA:
services = append(services, WithdrawFiatWith2FAText)
case WithdrawFiatWithSMS:
services = append(services, WithdrawFiatWithSMSText)
case WithdrawFiatWithEmail:
services = append(services, WithdrawFiatWithEmailText)
case WithdrawFiatWithWebsiteApproval:
services = append(services, WithdrawFiatWithWebsiteApprovalText)
case WithdrawFiatWithAPIPermission:
services = append(services, WithdrawFiatWithAPIPermissionText)
case WithdrawCryptoViaWebsiteOnly:
services = append(services, WithdrawCryptoViaWebsiteOnlyText)
case WithdrawFiatViaWebsiteOnly:
services = append(services, WithdrawFiatViaWebsiteOnlyText)
case NoFiatWithdrawals:
services = append(services, NoFiatWithdrawalsText)
default:
services = append(services, fmt.Sprintf("%s[1<<%v]", UnknownWithdrawalTypeText, i))
}
}
}
if len(services) > 0 {
return strings.Join(services, " & ")
}
return NoAPIWithdrawalMethodsText
}
// SupportsAsset whether or not the supplied asset is supported by the exchange
func (b *Base) SupportsAsset(a asset.Item) bool {
return b.CurrencyPairs.IsAssetSupported(a)
}
// PrintEnabledPairs prints the exchanges enabled asset pairs
func (b *Base) PrintEnabledPairs() {
for k, v := range b.CurrencyPairs.Pairs {
log.Infof(log.ExchangeSys, "%s Asset type %v:\n\t Enabled pairs: %v",
b.Name, strings.ToUpper(k.String()), v.Enabled)
}
}
// GetBase returns the exchange base
func (b *Base) GetBase() *Base { return b }
// CheckTransientError catches transient errors and returns nil if found, used
// for validation of API credentials
func (b *Base) CheckTransientError(err error) error {
if _, ok := err.(net.Error); ok {
log.Warnf(log.ExchangeSys,
"%s net error captured, will not disable authentication %s",
b.Name,
err)
return nil
}
return err
}
// DisableRateLimiter disables the rate limiting system for the exchange
func (b *Base) DisableRateLimiter() error {