forked from thrasher-corp/gocryptotrader
/
config.go
1496 lines (1317 loc) · 47.9 KB
/
config.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 config
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/woshidama323/gocryptotrader/common"
"github.com/woshidama323/gocryptotrader/connchecker"
"github.com/woshidama323/gocryptotrader/currency"
"github.com/woshidama323/gocryptotrader/currency/forexprovider"
"github.com/woshidama323/gocryptotrader/currency/forexprovider/base"
log "github.com/woshidama323/gocryptotrader/logger"
"github.com/woshidama323/gocryptotrader/portfolio"
)
// Constants declared here are filename strings and test strings
const (
FXProviderFixer = "fixer"
EncryptedConfigFile = "config.dat"
ConfigFile = "config.json"
ConfigTestFile = "../testdata/configtest.json"
configFileEncryptionPrompt = 1
configFileEncryptionEnabled = 1
configFileEncryptionDisabled = -1
configPairsLastUpdatedWarningThreshold = 30 // 30 days
configDefaultHTTPTimeout = time.Second * 15
configDefaultWebsocketResponseCheckTimeout = time.Millisecond * 30
configDefaultWebsocketResponseMaxLimit = time.Second * 7
configDefaultWebsocketOrderbookBufferLimit = 5
configMaxAuthFailres = 3
defaultNTPAllowedDifference = 50000000
defaultNTPAllowedNegativeDifference = 50000000
)
// Constants here hold some messages
const (
ErrExchangeNameEmpty = "exchange #%d name is empty"
ErrExchangeAvailablePairsEmpty = "exchange %s available pairs is empty"
ErrExchangeEnabledPairsEmpty = "exchange %s enabled pairs is empty"
ErrExchangeBaseCurrenciesEmpty = "exchange %s base currencies is empty"
ErrExchangeNotFound = "exchange %s not found"
ErrNoEnabledExchanges = "no exchanges enabled"
ErrCryptocurrenciesEmpty = "cryptocurrencies variable is empty"
ErrFailureOpeningConfig = "fatal error opening %s file. Error: %s"
ErrCheckingConfigValues = "fatal error checking config values. Error: %s"
ErrSavingConfigBytesMismatch = "config file %q bytes comparison doesn't match, read %s expected %s"
WarningWebserverCredentialValuesEmpty = "webserver support disabled due to empty Username/Password values"
WarningWebserverListenAddressInvalid = "webserver support disabled due to invalid listen address"
WarningExchangeAuthAPIDefaultOrEmptyValues = "exchange %s authenticated API support disabled due to default/empty APIKey/Secret/ClientID values"
WarningPairsLastUpdatedThresholdExceeded = "exchange %s last manual update of available currency pairs has exceeded %d days. Manual update required!"
)
// Constants here define unset default values displayed in the config.json
// file
const (
APIURLNonDefaultMessage = "NON_DEFAULT_HTTP_LINK_TO_EXCHANGE_API"
WebsocketURLNonDefaultMessage = "NON_DEFAULT_HTTP_LINK_TO_WEBSOCKET_EXCHANGE_API"
DefaultUnsetAPIKey = "Key"
DefaultUnsetAPISecret = "Secret"
DefaultUnsetAccountPlan = "accountPlan"
DefaultForexProviderExchangeRatesAPI = "ExchangeRates"
)
// Variables here are used for configuration
var (
Cfg Config
IsInitialSetup bool
testBypass bool
m sync.Mutex
)
// WebserverConfig struct holds the prestart variables for the webserver.
type WebserverConfig struct {
Enabled bool `json:"enabled"`
AdminUsername string `json:"adminUsername"`
AdminPassword string `json:"adminPassword"`
ListenAddress string `json:"listenAddress"`
WebsocketConnectionLimit int `json:"websocketConnectionLimit"`
WebsocketMaxAuthFailures int `json:"websocketMaxAuthFailures"`
WebsocketAllowInsecureOrigin bool `json:"websocketAllowInsecureOrigin"`
}
// Post holds the bot configuration data
type Post struct {
Data Config `json:"data"`
}
// CurrencyPairFormatConfig stores the users preferred currency pair display
type CurrencyPairFormatConfig struct {
Uppercase bool `json:"uppercase"`
Delimiter string `json:"delimiter,omitempty"`
Separator string `json:"separator,omitempty"`
Index string `json:"index,omitempty"`
}
// Config is the overarching object that holds all the information for
// prestart management of Portfolio, Communications, Webserver and Enabled
// Exchanges
type Config struct {
Name string `json:"name"`
EncryptConfig int `json:"encryptConfig"`
GlobalHTTPTimeout time.Duration `json:"globalHTTPTimeout"`
Logging log.Logging `json:"logging"`
Profiler ProfilerConfig `json:"profiler"`
NTPClient NTPClientConfig `json:"ntpclient"`
Currency CurrencyConfig `json:"currencyConfig"`
Communications CommunicationsConfig `json:"communications"`
Portfolio portfolio.Base `json:"portfolioAddresses"`
Webserver WebserverConfig `json:"webserver"`
Exchanges []ExchangeConfig `json:"exchanges"`
BankAccounts []BankAccount `json:"bankAccounts"`
ConnectionMonitor ConnectionMonitorConfig `json:"connectionMonitor"`
// Deprecated config settings, will be removed at a future date
CurrencyPairFormat *CurrencyPairFormatConfig `json:"currencyPairFormat,omitempty"`
FiatDisplayCurrency currency.Code `json:"fiatDispayCurrency,omitempty"`
Cryptocurrencies currency.Currencies `json:"cryptocurrencies,omitempty"`
SMS *SMSGlobalConfig `json:"smsGlobal,omitempty"`
}
// ConnectionMonitorConfig defines the connection monitor variables to ensure
// that there is internet connectivity
type ConnectionMonitorConfig struct {
DNSList []string `json:"preferredDNSList"`
PublicDomainList []string `json:"preferredDomainList"`
CheckInterval time.Duration `json:"checkInterval"`
}
// ProfilerConfig defines the profiler configuration to enable pprof
type ProfilerConfig struct {
Enabled bool `json:"enabled"`
}
// NTPClientConfig defines a network time protocol configuration to allow for
// positive and negative differences
type NTPClientConfig struct {
Level int `json:"enabled"`
Pool []string `json:"pool"`
AllowedDifference *time.Duration `json:"allowedDifference"`
AllowedNegativeDifference *time.Duration `json:"allowedNegativeDifference"`
}
// ExchangeConfig holds all the information needed for each enabled Exchange.
type ExchangeConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
Websocket bool `json:"websocket"`
UseSandbox bool `json:"useSandbox"`
RESTPollingDelay time.Duration `json:"restPollingDelay"`
HTTPTimeout time.Duration `json:"httpTimeout"`
WebsocketResponseCheckTimeout time.Duration `json:"websocketResponseCheckTimeout"`
WebsocketResponseMaxLimit time.Duration `json:"websocketResponseMaxLimit"`
WebsocketOrderbookBufferLimit int `json:"websocketOrderbookBufferLimit"`
HTTPUserAgent string `json:"httpUserAgent"`
HTTPDebugging bool `json:"httpDebugging"`
AuthenticatedAPISupport bool `json:"authenticatedApiSupport"`
AuthenticatedWebsocketAPISupport bool `json:"authenticatedWebsocketApiSupport"`
APIKey string `json:"apiKey"`
APISecret string `json:"apiSecret"`
APIAuthPEMKeySupport bool `json:"apiAuthPemKeySupport,omitempty"`
APIAuthPEMKey string `json:"apiAuthPemKey,omitempty"`
APIURL string `json:"apiUrl"`
APIURLSecondary string `json:"apiUrlSecondary"`
ProxyAddress string `json:"proxyAddress"`
WebsocketURL string `json:"websocketUrl"`
ClientID string `json:"clientId,omitempty"`
AvailablePairs currency.Pairs `json:"availablePairs"`
EnabledPairs currency.Pairs `json:"enabledPairs"`
BaseCurrencies currency.Currencies `json:"baseCurrencies"`
AssetTypes string `json:"assetTypes"`
SupportsAutoPairUpdates bool `json:"supportsAutoPairUpdates"`
PairsLastUpdated int64 `json:"pairsLastUpdated,omitempty"`
ConfigCurrencyPairFormat *CurrencyPairFormatConfig `json:"configCurrencyPairFormat"`
RequestCurrencyPairFormat *CurrencyPairFormatConfig `json:"requestCurrencyPairFormat"`
BankAccounts []BankAccount `json:"bankAccounts"`
}
// BankAccount holds differing bank account details by supported funding
// currency
type BankAccount struct {
Enabled bool `json:"enabled,omitempty"`
BankName string `json:"bankName"`
BankAddress string `json:"bankAddress"`
AccountName string `json:"accountName"`
AccountNumber string `json:"accountNumber"`
SWIFTCode string `json:"swiftCode"`
IBAN string `json:"iban"`
BSBNumber string `json:"bsbNumber,omitempty"`
SupportedCurrencies string `json:"supportedCurrencies"`
SupportedExchanges string `json:"supportedExchanges,omitempty"`
}
// BankTransaction defines a related banking transaction
type BankTransaction struct {
ReferenceNumber string `json:"referenceNumber"`
TransactionNumber string `json:"transactionNumber"`
PaymentInstructions string `json:"paymentInstructions"`
}
// CurrencyConfig holds all the information needed for currency related manipulation
type CurrencyConfig struct {
ForexProviders []base.Settings `json:"forexProviders"`
CryptocurrencyProvider CryptocurrencyProvider `json:"cryptocurrencyProvider"`
Cryptocurrencies currency.Currencies `json:"cryptocurrencies"`
CurrencyPairFormat *CurrencyPairFormatConfig `json:"currencyPairFormat"`
FiatDisplayCurrency currency.Code `json:"fiatDisplayCurrency"`
CurrencyFileUpdateDuration time.Duration `json:"currencyFileUpdateDuration"`
ForeignExchangeUpdateDuration time.Duration `json:"foreignExchangeUpdateDuration"`
}
// CryptocurrencyProvider defines coinmarketcap tools
type CryptocurrencyProvider struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
APIkey string `json:"apiKey"`
AccountPlan string `json:"accountPlan"`
}
// CommunicationsConfig holds all the information needed for each
// enabled communication package
type CommunicationsConfig struct {
SlackConfig SlackConfig `json:"slack"`
SMSGlobalConfig SMSGlobalConfig `json:"smsGlobal"`
SMTPConfig SMTPConfig `json:"smtp"`
TelegramConfig TelegramConfig `json:"telegram"`
}
// SlackConfig holds all variables to start and run the Slack package
type SlackConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
TargetChannel string `json:"targetChannel"`
VerificationToken string `json:"verificationToken"`
}
// SMSContact stores the SMS contact info
type SMSContact struct {
Name string `json:"name"`
Number string `json:"number"`
Enabled bool `json:"enabled"`
}
// SMSGlobalConfig structure holds all the variables you need for instant
// messaging and broadcast used by SMSGlobal
type SMSGlobalConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
Username string `json:"username"`
Password string `json:"password"`
Contacts []SMSContact `json:"contacts"`
}
// SMTPConfig holds all variables to start and run the SMTP package
type SMTPConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
Host string `json:"host"`
Port string `json:"port"`
AccountName string `json:"accountName"`
AccountPassword string `json:"accountPassword"`
RecipientList string `json:"recipientList"`
}
// TelegramConfig holds all variables to start and run the Telegram package
type TelegramConfig struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Verbose bool `json:"verbose"`
VerificationToken string `json:"verificationToken"`
}
// GetCurrencyConfig returns currency configurations
func (c *Config) GetCurrencyConfig() CurrencyConfig {
return c.Currency
}
// GetExchangeBankAccounts returns banking details associated with an exchange
// for depositing funds
func (c *Config) GetExchangeBankAccounts(exchangeName, depositingCurrency string) (BankAccount, error) {
m.Lock()
defer m.Unlock()
for x := range c.Exchanges {
if strings.EqualFold(c.Exchanges[x].Name, exchangeName) {
for y := range c.Exchanges[x].BankAccounts {
if common.StringContains(c.Exchanges[x].BankAccounts[y].SupportedCurrencies,
depositingCurrency) {
return c.Exchanges[x].BankAccounts[y], nil
}
}
}
}
return BankAccount{}, fmt.Errorf("exchange %s bank details not found for %s",
exchangeName,
depositingCurrency)
}
// UpdateExchangeBankAccounts updates the configuration for the associated
// exchange bank
func (c *Config) UpdateExchangeBankAccounts(exchangeName string, bankCfg []BankAccount) error {
m.Lock()
defer m.Unlock()
for i := range c.Exchanges {
if strings.EqualFold(c.Exchanges[i].Name, exchangeName) {
c.Exchanges[i].BankAccounts = bankCfg
return nil
}
}
return fmt.Errorf("exchange %s not found",
exchangeName)
}
// GetClientBankAccounts returns banking details used for a given exchange
// and currency
func (c *Config) GetClientBankAccounts(exchangeName, targetCurrency string) (BankAccount, error) {
m.Lock()
defer m.Unlock()
for x := range c.BankAccounts {
if (common.StringContains(c.BankAccounts[x].SupportedExchanges, exchangeName) ||
c.BankAccounts[x].SupportedExchanges == "ALL") &&
common.StringContains(c.BankAccounts[x].SupportedCurrencies, targetCurrency) {
return c.BankAccounts[x], nil
}
}
return BankAccount{}, fmt.Errorf("client banking details not found for %s and currency %s",
exchangeName,
targetCurrency)
}
// UpdateClientBankAccounts updates the configuration for a bank
func (c *Config) UpdateClientBankAccounts(bankCfg *BankAccount) error {
m.Lock()
defer m.Unlock()
for i := range c.BankAccounts {
if c.BankAccounts[i].BankName == bankCfg.BankName && c.BankAccounts[i].AccountNumber == bankCfg.AccountNumber {
c.BankAccounts[i] = *bankCfg
return nil
}
}
return fmt.Errorf("client banking details for %s not found, update not applied",
bankCfg.BankName)
}
// CheckClientBankAccounts checks client bank details
func (c *Config) CheckClientBankAccounts() error {
m.Lock()
defer m.Unlock()
if len(c.BankAccounts) == 0 {
c.BankAccounts = append(c.BankAccounts,
BankAccount{
BankName: "test",
BankAddress: "test",
AccountName: "TestAccount",
AccountNumber: "0234",
SWIFTCode: "91272837",
IBAN: "98218738671897",
SupportedCurrencies: "USD",
SupportedExchanges: "ANX,Kraken",
},
)
return nil
}
for i := range c.BankAccounts {
if c.BankAccounts[i].Enabled {
if c.BankAccounts[i].BankName == "" || c.BankAccounts[i].BankAddress == "" {
return fmt.Errorf("banking details for %s is enabled but variables not set correctly",
c.BankAccounts[i].BankName)
}
if c.BankAccounts[i].AccountName == "" || c.BankAccounts[i].AccountNumber == "" {
return fmt.Errorf("banking account details for %s variables not set correctly",
c.BankAccounts[i].BankName)
}
if c.BankAccounts[i].IBAN == "" && c.BankAccounts[i].SWIFTCode == "" && c.BankAccounts[i].BSBNumber == "" {
return fmt.Errorf("critical banking numbers not set for %s in %s account",
c.BankAccounts[i].BankName,
c.BankAccounts[i].AccountName)
}
if c.BankAccounts[i].SupportedExchanges == "" {
c.BankAccounts[i].SupportedExchanges = "ALL"
}
}
}
return nil
}
// GetCommunicationsConfig returns the communications configuration
func (c *Config) GetCommunicationsConfig() CommunicationsConfig {
m.Lock()
defer m.Unlock()
return c.Communications
}
// UpdateCommunicationsConfig sets a new updated version of a Communications
// configuration
func (c *Config) UpdateCommunicationsConfig(config *CommunicationsConfig) {
m.Lock()
c.Communications = *config
m.Unlock()
}
// GetCryptocurrencyProviderConfig returns the communications configuration
func (c *Config) GetCryptocurrencyProviderConfig() CryptocurrencyProvider {
m.Lock()
defer m.Unlock()
return c.Currency.CryptocurrencyProvider
}
// UpdateCryptocurrencyProviderConfig returns the communications configuration
func (c *Config) UpdateCryptocurrencyProviderConfig(config CryptocurrencyProvider) {
m.Lock()
c.Currency.CryptocurrencyProvider = config
m.Unlock()
}
// CheckCommunicationsConfig checks to see if the variables are set correctly
// from config.json
func (c *Config) CheckCommunicationsConfig() {
m.Lock()
defer m.Unlock()
// If the communications config hasn't been populated, populate
// with example settings
if c.Communications.SlackConfig.Name == "" {
c.Communications.SlackConfig = SlackConfig{
Name: "Slack",
TargetChannel: "general",
VerificationToken: "testtest",
}
}
if c.Communications.SMSGlobalConfig.Name == "" {
if c.SMS != nil {
if c.SMS.Contacts != nil {
c.Communications.SMSGlobalConfig = SMSGlobalConfig{
Name: "SMSGlobal",
Enabled: c.SMS.Enabled,
Verbose: c.SMS.Verbose,
Username: c.SMS.Username,
Password: c.SMS.Password,
Contacts: c.SMS.Contacts,
}
// flush old SMS config
c.SMS = nil
} else {
c.Communications.SMSGlobalConfig = SMSGlobalConfig{
Name: "SMSGlobal",
Username: "main",
Password: "test",
Contacts: []SMSContact{
{
Name: "bob",
Number: "1234",
Enabled: false,
},
},
}
}
} else {
c.Communications.SMSGlobalConfig = SMSGlobalConfig{
Name: "SMSGlobal",
Username: "main",
Password: "test",
Contacts: []SMSContact{
{
Name: "bob",
Number: "1234",
Enabled: false,
},
},
}
}
} else {
if c.SMS != nil {
// flush old SMS config
c.SMS = nil
}
}
if c.Communications.SMTPConfig.Name == "" {
c.Communications.SMTPConfig = SMTPConfig{
Name: "SMTP",
Host: "smtp.google.com",
Port: "537",
AccountName: "some",
AccountPassword: "password",
RecipientList: "lol123@gmail.com",
}
}
if c.Communications.TelegramConfig.Name == "" {
c.Communications.TelegramConfig = TelegramConfig{
Name: "Telegram",
VerificationToken: "testest",
}
}
if c.Communications.SlackConfig.Name != "Slack" ||
c.Communications.SMSGlobalConfig.Name != "SMSGlobal" ||
c.Communications.SMTPConfig.Name != "SMTP" ||
c.Communications.TelegramConfig.Name != "Telegram" {
log.Warn("Communications config name/s not set correctly")
}
if c.Communications.SlackConfig.Enabled {
if c.Communications.SlackConfig.TargetChannel == "" ||
c.Communications.SlackConfig.VerificationToken == "" ||
c.Communications.SlackConfig.VerificationToken == "testtest" {
c.Communications.SlackConfig.Enabled = false
log.Warn("Slack enabled in config but variable data not set, disabling.")
}
}
if c.Communications.SMSGlobalConfig.Enabled {
if c.Communications.SMSGlobalConfig.Username == "" ||
c.Communications.SMSGlobalConfig.Password == "" ||
len(c.Communications.SMSGlobalConfig.Contacts) == 0 {
c.Communications.SMSGlobalConfig.Enabled = false
log.Warn("SMSGlobal enabled in config but variable data not set, disabling.")
}
}
if c.Communications.SMTPConfig.Enabled {
if c.Communications.SMTPConfig.Host == "" ||
c.Communications.SMTPConfig.Port == "" ||
c.Communications.SMTPConfig.AccountName == "" ||
c.Communications.SMTPConfig.AccountPassword == "" {
c.Communications.SMTPConfig.Enabled = false
log.Warn("SMTP enabled in config but variable data not set, disabling.")
}
}
if c.Communications.TelegramConfig.Enabled {
if c.Communications.TelegramConfig.VerificationToken == "" {
c.Communications.TelegramConfig.Enabled = false
log.Warn("Telegram enabled in config but variable data not set, disabling.")
}
}
}
// CheckPairConsistency checks to see if the enabled pair exists in the
// available pairs list
func (c *Config) CheckPairConsistency(exchName string) error {
enabledPairs, err := c.GetEnabledPairs(exchName)
if err != nil {
return err
}
availPairs, err := c.GetAvailablePairs(exchName)
if err != nil {
return err
}
var pairs, pairsRemoved currency.Pairs
update := false
for x := range enabledPairs {
if !availPairs.Contains(enabledPairs[x], true) {
update = true
pairsRemoved = append(pairsRemoved, enabledPairs[x])
continue
}
pairs = append(pairs, enabledPairs[x])
}
if !update {
return nil
}
exchCfg, err := c.GetExchangeConfig(exchName)
if err != nil {
return err
}
if len(pairs) == 0 {
exchCfg.EnabledPairs = append(exchCfg.EnabledPairs,
availPairs.GetRandomPair())
log.Debugf("Exchange %s: No enabled pairs found in available pairs, randomly added %v\n",
exchName,
exchCfg.EnabledPairs)
} else {
exchCfg.EnabledPairs = pairs
}
err = c.UpdateExchangeConfig(&exchCfg)
if err != nil {
return err
}
log.Debugf("Exchange %s: Removing enabled pair(s) %v from enabled pairs as it isn't an available pair",
exchName,
pairsRemoved.Strings())
return nil
}
// SupportsPair returns true or not whether the exchange supports the supplied
// pair
func (c *Config) SupportsPair(exchName string, p currency.Pair) (bool, error) {
pairs, err := c.GetAvailablePairs(exchName)
if err != nil {
return false, err
}
return pairs.Contains(p, false), nil
}
// GetAvailablePairs returns a list of currency pairs for a specifc exchange
func (c *Config) GetAvailablePairs(exchName string) (currency.Pairs, error) {
exchCfg, err := c.GetExchangeConfig(exchName)
if err != nil {
return nil, err
}
return exchCfg.AvailablePairs.Format(exchCfg.ConfigCurrencyPairFormat.Delimiter,
exchCfg.ConfigCurrencyPairFormat.Index,
exchCfg.ConfigCurrencyPairFormat.Uppercase), nil
}
// GetEnabledPairs returns a list of currency pairs for a specifc exchange
func (c *Config) GetEnabledPairs(exchName string) (currency.Pairs, error) {
exchCfg, err := c.GetExchangeConfig(exchName)
if err != nil {
return nil, err
}
return exchCfg.EnabledPairs.Format(exchCfg.ConfigCurrencyPairFormat.Delimiter,
exchCfg.ConfigCurrencyPairFormat.Index,
exchCfg.ConfigCurrencyPairFormat.Uppercase), nil
}
// GetEnabledExchanges returns a list of enabled exchanges
func (c *Config) GetEnabledExchanges() []string {
var enabledExchs []string
for i := range c.Exchanges {
if c.Exchanges[i].Enabled {
enabledExchs = append(enabledExchs, c.Exchanges[i].Name)
}
}
return enabledExchs
}
// GetDisabledExchanges returns a list of disabled exchanges
func (c *Config) GetDisabledExchanges() []string {
var disabledExchs []string
for i := range c.Exchanges {
if !c.Exchanges[i].Enabled {
disabledExchs = append(disabledExchs, c.Exchanges[i].Name)
}
}
return disabledExchs
}
// CountEnabledExchanges returns the number of exchanges that are enabled.
func (c *Config) CountEnabledExchanges() int {
counter := 0
for i := range c.Exchanges {
if c.Exchanges[i].Enabled {
counter++
}
}
return counter
}
// GetConfigCurrencyPairFormat returns the config currency pair format
// for a specific exchange
func (c *Config) GetConfigCurrencyPairFormat(exchName string) (*CurrencyPairFormatConfig, error) {
exchCfg, err := c.GetExchangeConfig(exchName)
if err != nil {
return nil, err
}
return exchCfg.ConfigCurrencyPairFormat, nil
}
// GetRequestCurrencyPairFormat returns the request currency pair format
// for a specific exchange
func (c *Config) GetRequestCurrencyPairFormat(exchName string) (*CurrencyPairFormatConfig, error) {
exchCfg, err := c.GetExchangeConfig(exchName)
if err != nil {
return nil, err
}
return exchCfg.RequestCurrencyPairFormat, nil
}
// GetCurrencyPairDisplayConfig retrieves the currency pair display preference
func (c *Config) GetCurrencyPairDisplayConfig() *CurrencyPairFormatConfig {
return c.Currency.CurrencyPairFormat
}
// GetAllExchangeConfigs returns all exchange configurations
func (c *Config) GetAllExchangeConfigs() []ExchangeConfig {
m.Lock()
defer m.Unlock()
return c.Exchanges
}
// GetExchangeConfig returns exchange configurations by its indivdual name
func (c *Config) GetExchangeConfig(name string) (ExchangeConfig, error) {
m.Lock()
defer m.Unlock()
for i := range c.Exchanges {
if strings.EqualFold(c.Exchanges[i].Name, name) {
return c.Exchanges[i], nil
}
}
return ExchangeConfig{}, fmt.Errorf(ErrExchangeNotFound, name)
}
// GetForexProviderConfig returns a forex provider configuration by its name
func (c *Config) GetForexProviderConfig(name string) (base.Settings, error) {
m.Lock()
defer m.Unlock()
for i := range c.Currency.ForexProviders {
if strings.EqualFold(c.Currency.ForexProviders[i].Name, name) {
return c.Currency.ForexProviders[i], nil
}
}
return base.Settings{}, errors.New("provider not found")
}
// GetPrimaryForexProvider returns the primary forex provider
func (c *Config) GetPrimaryForexProvider() string {
m.Lock()
defer m.Unlock()
for i := range c.Currency.ForexProviders {
if c.Currency.ForexProviders[i].PrimaryProvider {
return c.Currency.ForexProviders[i].Name
}
}
return ""
}
// UpdateExchangeConfig updates exchange configurations
func (c *Config) UpdateExchangeConfig(e *ExchangeConfig) error {
m.Lock()
defer m.Unlock()
for i := range c.Exchanges {
if strings.EqualFold(c.Exchanges[i].Name, e.Name) {
c.Exchanges[i] = *e
return nil
}
}
return fmt.Errorf(ErrExchangeNotFound, e.Name)
}
// CheckExchangeConfigValues returns configuation values for all enabled
// exchanges
func (c *Config) CheckExchangeConfigValues() error {
exchanges := 0
for i := range c.Exchanges {
if strings.EqualFold(c.Exchanges[i].Name, "GDAX") {
c.Exchanges[i].Name = "CoinbasePro"
}
if c.Exchanges[i].WebsocketURL != WebsocketURLNonDefaultMessage {
if c.Exchanges[i].WebsocketURL == "" {
c.Exchanges[i].WebsocketURL = WebsocketURLNonDefaultMessage
}
}
if c.Exchanges[i].APIURL != APIURLNonDefaultMessage {
if c.Exchanges[i].APIURL == "" {
// Set default if nothing set
c.Exchanges[i].APIURL = APIURLNonDefaultMessage
}
}
if c.Exchanges[i].APIURLSecondary != APIURLNonDefaultMessage {
if c.Exchanges[i].APIURLSecondary == "" {
// Set default if nothing set
c.Exchanges[i].APIURLSecondary = APIURLNonDefaultMessage
}
}
if c.Exchanges[i].Enabled {
if c.Exchanges[i].Name == "" {
return fmt.Errorf(ErrExchangeNameEmpty, i)
}
if len(c.Exchanges[i].AvailablePairs) == 0 {
return fmt.Errorf(ErrExchangeAvailablePairsEmpty, c.Exchanges[i].Name)
}
if len(c.Exchanges[i].EnabledPairs) == 0 {
return fmt.Errorf(ErrExchangeEnabledPairsEmpty, c.Exchanges[i].Name)
}
if len(c.Exchanges[i].BaseCurrencies) == 0 {
return fmt.Errorf(ErrExchangeBaseCurrenciesEmpty, c.Exchanges[i].Name)
}
var areAuthenticatedCredentialsValid bool
if c.Exchanges[i].AuthenticatedWebsocketAPISupport || c.Exchanges[i].AuthenticatedAPISupport {
areAuthenticatedCredentialsValid = c.areAuthenticatedCredentialsValid(i)
}
if c.Exchanges[i].AuthenticatedWebsocketAPISupport {
c.Exchanges[i].AuthenticatedWebsocketAPISupport = areAuthenticatedCredentialsValid
}
if c.Exchanges[i].AuthenticatedAPISupport {
c.Exchanges[i].AuthenticatedAPISupport = areAuthenticatedCredentialsValid
}
if !c.Exchanges[i].SupportsAutoPairUpdates {
lastUpdated := common.UnixTimestampToTime(c.Exchanges[i].PairsLastUpdated)
lastUpdated = lastUpdated.AddDate(0, 0, configPairsLastUpdatedWarningThreshold)
if lastUpdated.Unix() <= time.Now().Unix() {
log.Warnf(WarningPairsLastUpdatedThresholdExceeded, c.Exchanges[i].Name, configPairsLastUpdatedWarningThreshold)
}
}
if c.Exchanges[i].HTTPTimeout <= 0 {
log.Warnf("Exchange %s HTTP Timeout value not set, defaulting to %v.", c.Exchanges[i].Name, configDefaultHTTPTimeout)
c.Exchanges[i].HTTPTimeout = configDefaultHTTPTimeout
}
if c.Exchanges[i].WebsocketResponseCheckTimeout <= 0 {
log.Warnf("Exchange %s Websocket response check timeout value not set, defaulting to %v.", c.Exchanges[i].Name, configDefaultWebsocketResponseCheckTimeout)
c.Exchanges[i].WebsocketResponseCheckTimeout = configDefaultWebsocketResponseCheckTimeout
}
if c.Exchanges[i].WebsocketResponseMaxLimit <= 0 {
log.Warnf("Exchange %s Websocket response max limit value not set, defaulting to %v.", c.Exchanges[i].Name, configDefaultWebsocketResponseMaxLimit)
c.Exchanges[i].WebsocketResponseMaxLimit = configDefaultWebsocketResponseMaxLimit
}
if c.Exchanges[i].WebsocketOrderbookBufferLimit <= 0 {
log.Warnf("Exchange %s Websocket orderbook buffer limit value not set, defaulting to %v.", c.Exchanges[i].Name, configDefaultWebsocketOrderbookBufferLimit)
c.Exchanges[i].WebsocketOrderbookBufferLimit = configDefaultWebsocketOrderbookBufferLimit
}
err := c.CheckPairConsistency(c.Exchanges[i].Name)
if err != nil {
log.Errorf("Exchange %s: CheckPairConsistency error: %s", c.Exchanges[i].Name, err)
}
if len(c.Exchanges[i].BankAccounts) == 0 {
c.Exchanges[i].BankAccounts = append(c.Exchanges[i].BankAccounts, BankAccount{})
} else {
for y := range c.Exchanges[i].BankAccounts {
bankAccount := &c.Exchanges[i].BankAccounts[y]
if bankAccount.Enabled {
if bankAccount.BankName == "" || bankAccount.BankAddress == "" {
log.Warnf("banking details for %s is enabled but variables not set",
c.Exchanges[i].Name)
bankAccount.Enabled = false
}
if bankAccount.AccountName == "" || bankAccount.AccountNumber == "" {
log.Warnf("banking account details for %s variables not set",
c.Exchanges[i].Name)
bankAccount.Enabled = false
}
if bankAccount.SupportedCurrencies == "" {
log.Warnf("banking account details for %s acceptable funding currencies not set",
c.Exchanges[i].Name)
bankAccount.Enabled = false
}
if bankAccount.BSBNumber == "" && bankAccount.IBAN == "" &&
bankAccount.SWIFTCode == "" {
log.Warnf("banking account details for %s critical banking numbers not set",
c.Exchanges[i].Name)
bankAccount.Enabled = false
}
}
}
}
exchanges++
}
}
if exchanges == 0 {
return errors.New(ErrNoEnabledExchanges)
}
return nil
}
func (c *Config) areAuthenticatedCredentialsValid(i int) bool {
if c.Exchanges == nil {
log.Error("Config: Failed to check exchange authenticated credentials due to c.Exchanges not setup")
return false
}
if i < 0 || c.Exchanges == nil || len(c.Exchanges) < i {
log.Error("Config: Failed to check exchange authenticated credentials due to invalid index")
return false
}
resp := true
if c.Exchanges[i].APIKey == "" || c.Exchanges[i].APIKey == DefaultUnsetAPIKey {
resp = false
}
if (c.Exchanges[i].APISecret == "" || c.Exchanges[i].APISecret == DefaultUnsetAPISecret) &&
c.Exchanges[i].Name != "COINUT" {
resp = false
}
if (c.Exchanges[i].ClientID == "ClientID" || c.Exchanges[i].ClientID == "") &&
(c.Exchanges[i].Name == "ITBIT" || c.Exchanges[i].Name == "Bitstamp" || c.Exchanges[i].Name == "COINUT" || c.Exchanges[i].Name == "CoinbasePro") {
resp = false
}
// non-fatal error
if !resp {
log.Warnf(WarningExchangeAuthAPIDefaultOrEmptyValues, c.Exchanges[i].Name)
}
return resp
}
// CheckWebserverConfigValues checks information before webserver starts and
// returns an error if values are incorrect.
func (c *Config) CheckWebserverConfigValues() error {
if c.Webserver.AdminUsername == "" || c.Webserver.AdminPassword == "" {
return errors.New(WarningWebserverCredentialValuesEmpty)
}
if !common.StringContains(c.Webserver.ListenAddress, ":") {
return errors.New(WarningWebserverListenAddressInvalid)
}
portStr := common.SplitStrings(c.Webserver.ListenAddress, ":")[1]
port, err := strconv.Atoi(portStr)
if err != nil {
return errors.New(WarningWebserverListenAddressInvalid)
}
if port < 1 || port > 65355 {
return errors.New(WarningWebserverListenAddressInvalid)
}
if c.Webserver.WebsocketConnectionLimit <= 0 {
c.Webserver.WebsocketConnectionLimit = 1
}
if c.Webserver.WebsocketMaxAuthFailures <= 0 {
c.Webserver.WebsocketMaxAuthFailures = 3
}
return nil
}
// CheckCurrencyConfigValues checks to see if the currency config values are correct or not
func (c *Config) CheckCurrencyConfigValues() error {
fxProviders := forexprovider.GetAvailableForexProviders()
if len(fxProviders) == 0 {
return errors.New("no forex providers available")
}
if len(fxProviders) != len(c.Currency.ForexProviders) {
for x := range fxProviders {
_, err := c.GetForexProviderConfig(fxProviders[x])
if err != nil {
log.Warnf("%s forex provider not found, adding to config..", fxProviders[x])
c.Currency.ForexProviders = append(c.Currency.ForexProviders, base.Settings{
Name: fxProviders[x],
RESTPollingDelay: 600,
APIKey: DefaultUnsetAPIKey,
APIKeyLvl: -1,
})
}
}
}
count := 0
for i := range c.Currency.ForexProviders {
if c.Currency.ForexProviders[i].Enabled {
if c.Currency.ForexProviders[i].APIKey == DefaultUnsetAPIKey && c.Currency.ForexProviders[i].Name != DefaultForexProviderExchangeRatesAPI {
log.Warnf("%s enabled forex provider API key not set. Please set this in your config.json file", c.Currency.ForexProviders[i].Name)
c.Currency.ForexProviders[i].Enabled = false
c.Currency.ForexProviders[i].PrimaryProvider = false
continue
}
if c.Currency.ForexProviders[i].Name == "CurrencyConverter" {
if c.Currency.ForexProviders[i].Enabled &&
c.Currency.ForexProviders[i].PrimaryProvider &&
(c.Currency.ForexProviders[i].APIKey == "" ||
c.Currency.ForexProviders[i].APIKey == DefaultUnsetAPIKey) {
log.Warnf("CurrencyConverter forex provider no longer supports unset API key requests. Switching to ExchangeRates FX provider..")
c.Currency.ForexProviders[i].Enabled = false
c.Currency.ForexProviders[i].PrimaryProvider = false
c.Currency.ForexProviders[i].APIKey = DefaultUnsetAPIKey
c.Currency.ForexProviders[i].APIKeyLvl = -1
continue
}
}