forked from openware/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
884 lines (786 loc) · 26.1 KB
/
helpers.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
package engine
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/pquerna/otp/totp"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/dispatch"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/account"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/stats"
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
"github.com/thrasher-corp/gocryptotrader/log"
"github.com/thrasher-corp/gocryptotrader/portfolio"
)
var (
errCertExpired = errors.New("gRPC TLS certificate has expired")
errCertDataIsNil = errors.New("gRPC TLS certificate PEM data is nil")
errCertTypeInvalid = errors.New("gRPC TLS certificate type is invalid")
)
// GetSubsystemsStatus returns the status of various subsystems
func (bot *Engine) GetSubsystemsStatus() map[string]bool {
systems := make(map[string]bool)
systems["communications"] = bot.CommsManager.Started()
systems["internet_monitor"] = bot.ConnectionManager.Started()
systems["orders"] = bot.OrderManager.Started()
systems["portfolio"] = bot.PortfolioManager.Started()
systems["ntp_timekeeper"] = bot.NTPManager.Started()
systems["database"] = bot.DatabaseManager.Started()
systems["exchange_syncer"] = bot.Settings.EnableExchangeSyncManager
systems["grpc"] = bot.Settings.EnableGRPC
systems["grpc_proxy"] = bot.Settings.EnableGRPCProxy
systems["gctscript"] = bot.GctScriptManager.Started()
systems["deprecated_rpc"] = bot.Settings.EnableDeprecatedRPC
systems["websocket_rpc"] = bot.Settings.EnableWebsocketRPC
systems["dispatch"] = dispatch.IsRunning()
return systems
}
// RPCEndpoint stores an RPC endpoint status and addr
type RPCEndpoint struct {
Started bool
ListenAddr string
}
// GetRPCEndpoints returns a list of RPC endpoints and their listen addrs
func GetRPCEndpoints() map[string]RPCEndpoint {
endpoints := make(map[string]RPCEndpoint)
endpoints["grpc"] = RPCEndpoint{
Started: Bot.Settings.EnableGRPC,
ListenAddr: "grpc://" + Bot.Config.RemoteControl.GRPC.ListenAddress,
}
endpoints["grpc_proxy"] = RPCEndpoint{
Started: Bot.Settings.EnableGRPCProxy,
ListenAddr: "http://" + Bot.Config.RemoteControl.GRPC.GRPCProxyListenAddress,
}
endpoints["deprecated_rpc"] = RPCEndpoint{
Started: Bot.Settings.EnableDeprecatedRPC,
ListenAddr: "http://" + Bot.Config.RemoteControl.DeprecatedRPC.ListenAddress,
}
endpoints["websocket_rpc"] = RPCEndpoint{
Started: Bot.Settings.EnableWebsocketRPC,
ListenAddr: "ws://" + Bot.Config.RemoteControl.WebsocketRPC.ListenAddress,
}
return endpoints
}
// SetSubsystem enables or disables an engine subsystem
func (bot *Engine) SetSubsystem(subsys string, enable bool) error {
switch strings.ToLower(subsys) {
case "communications":
if enable {
return bot.CommsManager.Start()
}
return bot.CommsManager.Stop()
case "internet_monitor":
if enable {
return bot.ConnectionManager.Start(&bot.Config.ConnectionMonitor)
}
return bot.CommsManager.Stop()
case "orders":
if enable {
return bot.OrderManager.Start()
}
return bot.OrderManager.Stop()
case "portfolio":
if enable {
return bot.PortfolioManager.Start()
}
return bot.OrderManager.Stop()
case "ntp_timekeeper":
if enable {
return bot.NTPManager.Start()
}
return bot.NTPManager.Stop()
case "database":
if enable {
return bot.DatabaseManager.Start(bot)
}
return bot.DatabaseManager.Stop()
case "exchange_syncer":
if enable {
bot.ExchangeCurrencyPairManager.Start()
}
bot.ExchangeCurrencyPairManager.Stop()
case "dispatch":
if enable {
return dispatch.Start(bot.Settings.DispatchMaxWorkerAmount, bot.Settings.DispatchJobsLimit)
}
return dispatch.Stop()
case "gctscript":
if enable {
return bot.GctScriptManager.Start(&bot.ServicesWG)
}
return bot.GctScriptManager.Stop()
}
return errors.New("subsystem not found")
}
// GetExchangeOTPs returns OTP codes for all exchanges which have a otpsecret
// stored
func (bot *Engine) GetExchangeOTPs() (map[string]string, error) {
otpCodes := make(map[string]string)
for x := range bot.Config.Exchanges {
if otpSecret := bot.Config.Exchanges[x].API.Credentials.OTPSecret; otpSecret != "" {
exchName := bot.Config.Exchanges[x].Name
o, err := totp.GenerateCode(otpSecret, time.Now())
if err != nil {
log.Errorf(log.Global, "Unable to generate OTP code for exchange %s. Err: %s\n",
exchName, err)
continue
}
otpCodes[exchName] = o
}
}
if len(otpCodes) == 0 {
return nil, errors.New("no exchanges found which have a OTP secret stored")
}
return otpCodes, nil
}
// GetExchangeoOTPByName returns a OTP code for the desired exchange
// if it exists
func (bot *Engine) GetExchangeoOTPByName(exchName string) (string, error) {
for x := range bot.Config.Exchanges {
if !strings.EqualFold(bot.Config.Exchanges[x].Name, exchName) {
continue
}
if otpSecret := bot.Config.Exchanges[x].API.Credentials.OTPSecret; otpSecret != "" {
return totp.GenerateCode(otpSecret, time.Now())
}
}
return "", errors.New("exchange does not have a OTP secret stored")
}
// GetAuthAPISupportedExchanges returns a list of auth api enabled exchanges
func (bot *Engine) GetAuthAPISupportedExchanges() []string {
var exchangeNames []string
exchanges := bot.GetExchanges()
for x := range exchanges {
if !exchanges[x].GetAuthenticatedAPISupport(exchange.RestAuthentication) &&
!exchanges[x].GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
continue
}
exchangeNames = append(exchangeNames, exchanges[x].GetName())
}
return exchangeNames
}
// IsOnline returns whether or not the engine has Internet connectivity
func (bot *Engine) IsOnline() bool {
return bot.ConnectionManager.IsOnline()
}
// GetAvailableExchanges returns a list of enabled exchanges
func (bot *Engine) GetAvailableExchanges() []string {
var enExchanges []string
for x := range bot.Config.Exchanges {
if bot.Config.Exchanges[x].Enabled {
enExchanges = append(enExchanges, bot.Config.Exchanges[x].Name)
}
}
return enExchanges
}
// GetAllAvailablePairs returns a list of all available pairs on either enabled
// or disabled exchanges
func (bot *Engine) GetAllAvailablePairs(enabledExchangesOnly bool, assetType asset.Item) currency.Pairs {
var pairList currency.Pairs
for x := range bot.Config.Exchanges {
if enabledExchangesOnly && !bot.Config.Exchanges[x].Enabled {
continue
}
exchName := bot.Config.Exchanges[x].Name
pairs, err := bot.Config.GetAvailablePairs(exchName, assetType)
if err != nil {
continue
}
for y := range pairs {
if pairList.Contains(pairs[y], false) {
continue
}
pairList = append(pairList, pairs[y])
}
}
return pairList
}
// GetSpecificAvailablePairs returns a list of supported pairs based on specific
// parameters
func (bot *Engine) GetSpecificAvailablePairs(enabledExchangesOnly, fiatPairs, includeUSDT, cryptoPairs bool, assetType asset.Item) currency.Pairs {
var pairList currency.Pairs
supportedPairs := bot.GetAllAvailablePairs(enabledExchangesOnly, assetType)
for x := range supportedPairs {
if fiatPairs {
if supportedPairs[x].IsCryptoFiatPair() &&
!supportedPairs[x].ContainsCurrency(currency.USDT) ||
(includeUSDT &&
supportedPairs[x].ContainsCurrency(currency.USDT) &&
supportedPairs[x].IsCryptoPair()) {
if pairList.Contains(supportedPairs[x], false) {
continue
}
pairList = append(pairList, supportedPairs[x])
}
}
if cryptoPairs {
if supportedPairs[x].IsCryptoPair() {
if pairList.Contains(supportedPairs[x], false) {
continue
}
pairList = append(pairList, supportedPairs[x])
}
}
}
return pairList
}
// IsRelatablePairs checks to see if the two pairs are relatable
func IsRelatablePairs(p1, p2 currency.Pair, includeUSDT bool) bool {
if p1.EqualIncludeReciprocal(p2) {
return true
}
var relatablePairs = GetRelatableCurrencies(p1, true, includeUSDT)
if p1.IsCryptoFiatPair() {
for x := range relatablePairs {
relatablePairs = append(relatablePairs,
GetRelatableFiatCurrencies(relatablePairs[x])...)
}
}
return relatablePairs.Contains(p2, false)
}
// MapCurrenciesByExchange returns a list of currency pairs mapped to an
// exchange
func (bot *Engine) MapCurrenciesByExchange(p currency.Pairs, enabledExchangesOnly bool, assetType asset.Item) map[string]currency.Pairs {
currencyExchange := make(map[string]currency.Pairs)
for x := range p {
for y := range bot.Config.Exchanges {
if enabledExchangesOnly && !bot.Config.Exchanges[y].Enabled {
continue
}
exchName := bot.Config.Exchanges[y].Name
if !bot.Config.SupportsPair(exchName, p[x], assetType) {
continue
}
result, ok := currencyExchange[exchName]
if !ok {
var pairs []currency.Pair
pairs = append(pairs, p[x])
currencyExchange[exchName] = pairs
} else {
if result.Contains(p[x], false) {
continue
}
result = append(result, p[x])
currencyExchange[exchName] = result
}
}
}
return currencyExchange
}
// GetExchangeNamesByCurrency returns a list of exchanges supporting
// a currency pair based on whether the exchange is enabled or not
func (bot *Engine) GetExchangeNamesByCurrency(p currency.Pair, enabled bool, assetType asset.Item) []string {
var exchanges []string
for x := range bot.Config.Exchanges {
if enabled != bot.Config.Exchanges[x].Enabled {
continue
}
exchName := bot.Config.Exchanges[x].Name
if !bot.Config.SupportsPair(exchName, p, assetType) {
continue
}
exchanges = append(exchanges, exchName)
}
return exchanges
}
// GetRelatableCryptocurrencies returns a list of currency pairs if it can find
// any relatable currencies (e.g ETHBTC -> ETHLTC -> ETHUSDT -> ETHREP)
func GetRelatableCryptocurrencies(p currency.Pair) currency.Pairs {
var pairs currency.Pairs
cryptocurrencies := currency.GetCryptocurrencies()
for x := range cryptocurrencies {
newPair := currency.NewPair(p.Base, cryptocurrencies[x])
if newPair.IsInvalid() {
continue
}
if newPair.Base.Upper() == p.Base.Upper() &&
newPair.Quote.Upper() == p.Quote.Upper() {
continue
}
if pairs.Contains(newPair, false) {
continue
}
pairs = append(pairs, newPair)
}
return pairs
}
// GetRelatableFiatCurrencies returns a list of currency pairs if it can find
// any relatable currencies (e.g ETHUSD -> ETHAUD -> ETHGBP -> ETHJPY)
func GetRelatableFiatCurrencies(p currency.Pair) currency.Pairs {
var pairs currency.Pairs
fiatCurrencies := currency.GetFiatCurrencies()
for x := range fiatCurrencies {
newPair := currency.NewPair(p.Base, fiatCurrencies[x])
if newPair.Base.Upper() == newPair.Quote.Upper() {
continue
}
if newPair.Base.Upper() == p.Base.Upper() &&
newPair.Quote.Upper() == p.Quote.Upper() {
continue
}
if pairs.Contains(newPair, false) {
continue
}
pairs = append(pairs, newPair)
}
return pairs
}
// GetRelatableCurrencies returns a list of currency pairs if it can find
// any relatable currencies (e.g BTCUSD -> BTC USDT -> XBT USDT -> XBT USD)
// incOrig includes the supplied pair if desired
func GetRelatableCurrencies(p currency.Pair, incOrig, incUSDT bool) currency.Pairs {
var pairs currency.Pairs
addPair := func(p currency.Pair) {
if pairs.Contains(p, true) {
return
}
pairs = append(pairs, p)
}
buildPairs := func(p currency.Pair, incOrig bool) {
if incOrig {
addPair(p)
}
first := currency.GetTranslation(p.Base)
if first != p.Base {
addPair(currency.NewPair(first, p.Quote))
second := currency.GetTranslation(p.Quote)
if second != p.Quote {
addPair(currency.NewPair(first, second))
}
}
second := currency.GetTranslation(p.Quote)
if second != p.Quote {
addPair(currency.NewPair(p.Base, second))
}
}
buildPairs(p, incOrig)
buildPairs(p.Swap(), incOrig)
if !incUSDT {
pairs = pairs.RemovePairsByFilter(currency.USDT)
}
return pairs
}
// GetSpecificOrderbook returns a specific orderbook given the currency,
// exchangeName and assetType
func (bot *Engine) GetSpecificOrderbook(p currency.Pair, exchangeName string, assetType asset.Item) (*orderbook.Base, error) {
exch := bot.GetExchangeByName(exchangeName)
if exch == nil {
return nil, ErrExchangeNotFound
}
return exch.FetchOrderbook(p, assetType)
}
// GetSpecificTicker returns a specific ticker given the currency,
// exchangeName and assetType
func (bot *Engine) GetSpecificTicker(p currency.Pair, exchangeName string, assetType asset.Item) (*ticker.Price, error) {
exch := bot.GetExchangeByName(exchangeName)
if exch == nil {
return nil, ErrExchangeNotFound
}
return exch.FetchTicker(p, assetType)
}
// GetCollatedExchangeAccountInfoByCoin collates individual exchange account
// information and turns into into a map string of
// exchange.AccountCurrencyInfo
func GetCollatedExchangeAccountInfoByCoin(accounts []account.Holdings) map[currency.Code]account.Balance {
result := make(map[currency.Code]account.Balance)
for x := range accounts {
for y := range accounts[x].Accounts {
for z := range accounts[x].Accounts[y].Currencies {
currencyName := accounts[x].Accounts[y].Currencies[z].CurrencyName
avail := accounts[x].Accounts[y].Currencies[z].TotalValue
onHold := accounts[x].Accounts[y].Currencies[z].Hold
info, ok := result[currencyName]
if !ok {
accountInfo := account.Balance{
CurrencyName: currencyName,
Hold: onHold,
TotalValue: avail,
}
result[currencyName] = accountInfo
} else {
info.Hold += onHold
info.TotalValue += avail
result[currencyName] = info
}
}
}
}
return result
}
// GetExchangeHighestPriceByCurrencyPair returns the exchange with the highest
// price for a given currency pair and asset type
func GetExchangeHighestPriceByCurrencyPair(p currency.Pair, a asset.Item) (string, error) {
result := stats.SortExchangesByPrice(p, a, true)
if len(result) == 0 {
return "", fmt.Errorf("no stats for supplied currency pair and asset type")
}
return result[0].Exchange, nil
}
// GetExchangeLowestPriceByCurrencyPair returns the exchange with the lowest
// price for a given currency pair and asset type
func GetExchangeLowestPriceByCurrencyPair(p currency.Pair, assetType asset.Item) (string, error) {
result := stats.SortExchangesByPrice(p, assetType, false)
if len(result) == 0 {
return "", fmt.Errorf("no stats for supplied currency pair and asset type")
}
return result[0].Exchange, nil
}
// SeedExchangeAccountInfo seeds account info
func SeedExchangeAccountInfo(accounts []account.Holdings) {
if len(accounts) == 0 {
return
}
port := portfolio.GetPortfolio()
for x := range accounts {
exchangeName := accounts[x].Exchange
var currencies []account.Balance
for y := range accounts[x].Accounts {
for z := range accounts[x].Accounts[y].Currencies {
var update bool
for i := range currencies {
if accounts[x].Accounts[y].Currencies[z].CurrencyName == currencies[i].CurrencyName {
currencies[i].Hold += accounts[x].Accounts[y].Currencies[z].Hold
currencies[i].TotalValue += accounts[x].Accounts[y].Currencies[z].TotalValue
update = true
}
}
if update {
continue
}
currencies = append(currencies, account.Balance{
CurrencyName: accounts[x].Accounts[y].Currencies[z].CurrencyName,
TotalValue: accounts[x].Accounts[y].Currencies[z].TotalValue,
Hold: accounts[x].Accounts[y].Currencies[z].Hold,
})
}
}
for x := range currencies {
currencyName := currencies[x].CurrencyName
total := currencies[x].TotalValue
if !port.ExchangeAddressExists(exchangeName, currencyName) {
if total <= 0 {
continue
}
log.Debugf(log.PortfolioMgr, "Portfolio: Adding new exchange address: %s, %s, %f, %s\n",
exchangeName,
currencyName,
total,
portfolio.PortfolioAddressExchange)
port.Addresses = append(
port.Addresses,
portfolio.Address{Address: exchangeName,
CoinType: currencyName,
Balance: total,
Description: portfolio.PortfolioAddressExchange})
} else {
if total <= 0 {
log.Debugf(log.PortfolioMgr, "Portfolio: Removing %s %s entry.\n",
exchangeName,
currencyName)
port.RemoveExchangeAddress(exchangeName, currencyName)
} else {
balance, ok := port.GetAddressBalance(exchangeName,
portfolio.PortfolioAddressExchange,
currencyName)
if !ok {
continue
}
if balance != total {
log.Debugf(log.PortfolioMgr, "Portfolio: Updating %s %s entry with balance %f.\n",
exchangeName,
currencyName,
total)
port.UpdateExchangeAddressBalance(exchangeName,
currencyName,
total)
}
}
}
}
}
}
// GetCryptocurrenciesByExchange returns a list of cryptocurrencies the exchange supports
func (bot *Engine) GetCryptocurrenciesByExchange(exchangeName string, enabledExchangesOnly, enabledPairs bool, assetType asset.Item) ([]string, error) {
var cryptocurrencies []string
for x := range bot.Config.Exchanges {
if !strings.EqualFold(bot.Config.Exchanges[x].Name, exchangeName) {
continue
}
if enabledExchangesOnly && !bot.Config.Exchanges[x].Enabled {
continue
}
var err error
var pairs []currency.Pair
if enabledPairs {
pairs, err = bot.Config.GetEnabledPairs(exchangeName, assetType)
if err != nil {
return nil, err
}
} else {
pairs, err = bot.Config.GetAvailablePairs(exchangeName, assetType)
if err != nil {
return nil, err
}
}
for y := range pairs {
if pairs[y].Base.IsCryptocurrency() &&
!common.StringDataCompareInsensitive(cryptocurrencies, pairs[y].Base.String()) {
cryptocurrencies = append(cryptocurrencies, pairs[y].Base.String())
}
if pairs[y].Quote.IsCryptocurrency() &&
!common.StringDataCompareInsensitive(cryptocurrencies, pairs[y].Quote.String()) {
cryptocurrencies = append(cryptocurrencies, pairs[y].Quote.String())
}
}
}
return cryptocurrencies, nil
}
// GetCryptocurrencyDepositAddressesByExchange returns the cryptocurrency deposit addresses for a particular exchange
func (bot *Engine) GetCryptocurrencyDepositAddressesByExchange(exchName string) (map[string]string, error) {
if bot.DepositAddressManager != nil {
return bot.DepositAddressManager.GetDepositAddressesByExchange(exchName)
}
result := bot.GetExchangeCryptocurrencyDepositAddresses()
r, ok := result[exchName]
if !ok {
return nil, ErrExchangeNotFound
}
return r, nil
}
// GetExchangeCryptocurrencyDepositAddress returns the cryptocurrency deposit address for a particular
// exchange
func (bot *Engine) GetExchangeCryptocurrencyDepositAddress(exchName, accountID string, item currency.Code) (string, error) {
if bot.DepositAddressManager != nil {
return bot.DepositAddressManager.GetDepositAddressByExchange(exchName, item)
}
exch := bot.GetExchangeByName(exchName)
if exch == nil {
return "", ErrExchangeNotFound
}
return exch.GetDepositAddress(item, accountID)
}
// GetExchangeCryptocurrencyDepositAddresses obtains an exchanges deposit cryptocurrency list
func (bot *Engine) GetExchangeCryptocurrencyDepositAddresses() map[string]map[string]string {
result := make(map[string]map[string]string)
exchanges := bot.GetExchanges()
for x := range exchanges {
exchName := exchanges[x].GetName()
if !exchanges[x].GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if bot.Settings.Verbose {
log.Debugf(log.ExchangeSys, "GetExchangeCryptocurrencyDepositAddresses: Skippping %s due to disabled authenticated API support.\n", exchName)
}
continue
}
cryptoCurrencies, err := bot.GetCryptocurrenciesByExchange(exchName, true, true, asset.Spot)
if err != nil {
log.Debugf(log.ExchangeSys, "%s failed to get cryptocurrency deposit addresses. Err: %s\n", exchName, err)
continue
}
cryptoAddr := make(map[string]string)
for y := range cryptoCurrencies {
cryptocurrency := cryptoCurrencies[y]
depositAddr, err := exchanges[x].GetDepositAddress(currency.NewCode(cryptocurrency), "")
if err != nil {
log.Errorf(log.Global, "%s failed to get cryptocurrency deposit addresses. Err: %s\n", exchName, err)
continue
}
cryptoAddr[cryptocurrency] = depositAddr
}
result[exchName] = cryptoAddr
}
return result
}
// FormatCurrency is a method that formats and returns a currency pair
// based on the user currency display preferences
func FormatCurrency(p currency.Pair) currency.Pair {
return p.Format(Bot.Config.Currency.CurrencyPairFormat.Delimiter,
Bot.Config.Currency.CurrencyPairFormat.Uppercase)
}
// GetExchangeNames returns a list of enabled or disabled exchanges
func (bot *Engine) GetExchangeNames(enabledOnly bool) []string {
exchangeNames := bot.GetAvailableExchanges()
if enabledOnly {
return exchangeNames
}
exchangeNames = append(exchangeNames, bot.Config.GetDisabledExchanges()...)
return exchangeNames
}
// GetAllActiveTickers returns all enabled exchange tickers
func (bot *Engine) GetAllActiveTickers() []EnabledExchangeCurrencies {
var tickerData []EnabledExchangeCurrencies
exchanges := bot.GetExchanges()
for x := range exchanges {
assets := exchanges[x].GetAssetTypes()
exchName := exchanges[x].GetName()
var exchangeTicker EnabledExchangeCurrencies
exchangeTicker.ExchangeName = exchName
for y := range assets {
currencies, err := exchanges[x].GetEnabledPairs(assets[y])
if err != nil {
log.Errorf(log.ExchangeSys,
"Exchange %s could not retrieve enabled currencies. Err: %s\n",
exchName,
err)
continue
}
for z := range currencies {
tp, err := exchanges[x].FetchTicker(currencies[z], assets[y])
if err != nil {
log.Errorf(log.ExchangeSys, "Exchange %s failed to retrieve %s ticker. Err: %s\n", exchName,
currencies[z].String(),
err)
continue
}
exchangeTicker.ExchangeValues = append(exchangeTicker.ExchangeValues, *tp)
}
tickerData = append(tickerData, exchangeTicker)
}
}
return tickerData
}
// GetAllEnabledExchangeAccountInfo returns all the current enabled exchanges
func (bot *Engine) GetAllEnabledExchangeAccountInfo() AllEnabledExchangeAccounts {
var response AllEnabledExchangeAccounts
exchanges := bot.GetExchanges()
for x := range exchanges {
if exchanges[x] != nil && exchanges[x].IsEnabled() {
if !exchanges[x].GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if bot.Settings.Verbose {
log.Debugf(log.ExchangeSys,
"GetAllEnabledExchangeAccountInfo: Skipping %s due to disabled authenticated API support.\n",
exchanges[x].GetName())
}
continue
}
accountInfo, err := exchanges[x].FetchAccountInfo()
if err != nil {
log.Errorf(log.ExchangeSys,
"Error encountered retrieving exchange account info for %s. Error %s\n",
exchanges[x].GetName(),
err)
continue
}
response.Data = append(response.Data, accountInfo)
}
}
return response
}
func verifyCert(pemData []byte) error {
var pemBlock *pem.Block
pemBlock, _ = pem.Decode(pemData)
if pemBlock == nil {
return errCertDataIsNil
}
if pemBlock.Type != "CERTIFICATE" {
return errCertTypeInvalid
}
cert, err := x509.ParseCertificate(pemBlock.Bytes)
if err != nil {
return err
}
if time.Now().After(cert.NotAfter) {
return errCertExpired
}
return nil
}
func checkCerts(certDir string) error {
certFile := filepath.Join(certDir, "cert.pem")
keyFile := filepath.Join(certDir, "key.pem")
if !file.Exists(certFile) || !file.Exists(keyFile) {
log.Warnln(log.Global, "gRPC certificate/key file missing, recreating...")
return genCert(certDir)
}
pemData, err := ioutil.ReadFile(certFile)
if err != nil {
return fmt.Errorf("unable to open TLS cert file: %s", err)
}
if err = verifyCert(pemData); err != nil {
if err != errCertExpired {
return err
}
log.Warnln(log.Global, "gRPC certificate has expired, regenerating...")
return genCert(certDir)
}
log.Infoln(log.Global, "gRPC TLS certificate and key files exist, will use them.")
return nil
}
func genCert(targetDir string) error {
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("failed to generate ecdsa private key: %s", err)
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number: %s", err)
}
host, err := os.Hostname()
if err != nil {
return fmt.Errorf("failed to get hostname: %s", err)
}
dnsNames := []string{host}
if host != "localhost" {
dnsNames = append(dnsNames, "localhost")
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"gocryptotrader"},
CommonName: host,
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 365),
IsCA: true,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: []net.IP{
net.ParseIP("127.0.0.1"),
net.ParseIP("::1"),
},
DNSNames: dnsNames,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)
if err != nil {
return fmt.Errorf("failed to create certificate: %s", err)
}
certData := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if certData == nil {
return fmt.Errorf("cert data is nil")
}
b, err := x509.MarshalECPrivateKey(privKey)
if err != nil {
return fmt.Errorf("failed to marshal ECDSA private key: %s", err)
}
keyData := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
if keyData == nil {
return fmt.Errorf("key pem data is nil")
}
err = file.Write(filepath.Join(targetDir, "key.pem"), keyData)
if err != nil {
return fmt.Errorf("failed to write key.pem file %s", err)
}
err = file.Write(filepath.Join(targetDir, "cert.pem"), certData)
if err != nil {
return fmt.Errorf("failed to write cert.pem file %s", err)
}
log.Infof(log.Global, "gRPC TLS key.pem and cert.pem files written to %s\n", targetDir)
return nil
}