forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
768 lines (666 loc) · 19.8 KB
/
storage.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
package currency
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"path/filepath"
"time"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/currency/coinmarketcap"
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider"
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/log"
)
func init() {
storage.SetDefaults()
}
// SetDefaults sets storage defaults for basic package functionality
func (s *Storage) SetDefaults() {
s.defaultBaseCurrency = USD
s.baseCurrency = s.defaultBaseCurrency
var fiatCurrencies []Code
for item := range symbols {
if item == USDT.Item {
continue
}
fiatCurrencies = append(fiatCurrencies, Code{Item: item, UpperCase: true})
}
err := s.SetDefaultFiatCurrencies(fiatCurrencies...)
if err != nil {
log.Errorf(log.Global, "Currency Storage: Setting default fiat currencies error: %s", err)
}
err = s.SetDefaultCryptocurrencies(BTC, LTC, ETH, DOGE, DASH, XRP, XMR, USDT, UST)
if err != nil {
log.Errorf(log.Global, "Currency Storage: Setting default cryptocurrencies error: %s", err)
}
s.SetupConversionRates()
s.fiatExchangeMarkets = forexprovider.NewDefaultFXProvider()
}
// RunUpdater runs the foreign exchange updater service. This will set up a JSON
// dump file and keep foreign exchange rates updated as fast as possible without
// triggering rate limiters, it will also run a full cryptocurrency check
// through coin market cap and expose analytics for exchange services
func (s *Storage) RunUpdater(overrides BotOverrides, settings *MainConfiguration, filePath string) error {
s.mtx.Lock()
s.shutdown = make(chan struct{})
if !settings.Cryptocurrencies.HasData() {
s.mtx.Unlock()
return errors.New("currency storage error, no cryptocurrencies loaded")
}
s.cryptocurrencies = settings.Cryptocurrencies
if settings.FiatDisplayCurrency.IsEmpty() {
s.mtx.Unlock()
return errors.New("currency storage error, no fiat display currency set in config")
}
s.baseCurrency = settings.FiatDisplayCurrency
log.Debugf(log.Global,
"Fiat display currency: %s.\n",
s.baseCurrency)
if settings.CryptocurrencyProvider.Enabled {
log.Debugln(log.Global,
"Setting up currency analysis system with Coinmarketcap...")
c := &coinmarketcap.Coinmarketcap{}
c.SetDefaults()
err := c.Setup(coinmarketcap.Settings{
Name: settings.CryptocurrencyProvider.Name,
Enabled: settings.CryptocurrencyProvider.Enabled,
AccountPlan: settings.CryptocurrencyProvider.AccountPlan,
APIkey: settings.CryptocurrencyProvider.APIkey,
Verbose: settings.CryptocurrencyProvider.Verbose,
})
if err != nil {
log.Errorf(log.Global,
"Unable to setup CoinMarketCap analysis. Error: %s", err)
settings.CryptocurrencyProvider.Enabled = false
} else {
s.currencyAnalysis = c
}
}
if filePath == "" {
s.mtx.Unlock()
return errors.New("currency package runUpdater error filepath not set")
}
s.path = filepath.Join(filePath, DefaultStorageFile)
if settings.CurrencyDelay.Nanoseconds() == 0 {
s.currencyFileUpdateDelay = DefaultCurrencyFileDelay
} else {
s.currencyFileUpdateDelay = settings.CurrencyDelay
}
if settings.FxRateDelay.Nanoseconds() == 0 {
s.foreignExchangeUpdateDelay = DefaultForeignExchangeDelay
} else {
s.foreignExchangeUpdateDelay = settings.FxRateDelay
}
var fxSettings []base.Settings
for i := range settings.ForexProviders {
switch settings.ForexProviders[i].Name {
case "CurrencyConverter":
if overrides.FxCurrencyConverter ||
settings.ForexProviders[i].Enabled {
settings.ForexProviders[i].Enabled = true
fxSettings = append(fxSettings,
base.Settings(settings.ForexProviders[i]))
}
case "CurrencyLayer":
if overrides.FxCurrencyLayer || settings.ForexProviders[i].Enabled {
settings.ForexProviders[i].Enabled = true
fxSettings = append(fxSettings,
base.Settings(settings.ForexProviders[i]))
}
case "Fixer":
if overrides.FxFixer || settings.ForexProviders[i].Enabled {
settings.ForexProviders[i].Enabled = true
fxSettings = append(fxSettings,
base.Settings(settings.ForexProviders[i]))
}
case "OpenExchangeRates":
if overrides.FxOpenExchangeRates ||
settings.ForexProviders[i].Enabled {
settings.ForexProviders[i].Enabled = true
fxSettings = append(fxSettings,
base.Settings(settings.ForexProviders[i]))
}
case "ExchangeRates":
// TODO ADD OVERRIDE
if settings.ForexProviders[i].Enabled {
settings.ForexProviders[i].Enabled = true
fxSettings = append(fxSettings,
base.Settings(settings.ForexProviders[i]))
}
case "ExchangeRateHost":
if overrides.FxExchangeRateHost || settings.ForexProviders[i].Enabled {
settings.ForexProviders[i].Enabled = true
fxSettings = append(fxSettings,
base.Settings(settings.ForexProviders[i]))
}
}
}
if len(fxSettings) != 0 {
var err error
s.fiatExchangeMarkets, err = forexprovider.StartFXService(fxSettings)
if err != nil {
s.mtx.Unlock()
return err
}
log.Debugf(log.Global,
"Primary foreign exchange conversion provider %s enabled\n",
s.fiatExchangeMarkets.Primary.Provider.GetName())
for i := range s.fiatExchangeMarkets.Support {
log.Debugf(log.Global,
"Support forex conversion provider %s enabled\n",
s.fiatExchangeMarkets.Support[i].Provider.GetName())
}
// Mutex present in this go routine to lock down retrieving rate data
// until this system initially updates
go s.ForeignExchangeUpdater()
} else {
log.Warnln(log.Global,
"No foreign exchange providers enabled in config.json")
s.mtx.Unlock()
}
return nil
}
// SetupConversionRates sets default conversion rate values
func (s *Storage) SetupConversionRates() {
s.fxRates = ConversionRates{
m: make(map[*Item]map[*Item]*float64),
}
}
// SetDefaultFiatCurrencies assigns the default fiat currency list and adds it
// to the running list
func (s *Storage) SetDefaultFiatCurrencies(c ...Code) error {
for i := range c {
err := s.currencyCodes.UpdateCurrency("", c[i].String(), "", 0, Fiat)
if err != nil {
return err
}
}
s.defaultFiatCurrencies = append(s.defaultFiatCurrencies, c...)
s.fiatCurrencies = append(s.fiatCurrencies, c...)
return nil
}
// SetDefaultCryptocurrencies assigns the default cryptocurrency list and adds
// it to the running list
func (s *Storage) SetDefaultCryptocurrencies(c ...Code) error {
for i := range c {
err := s.currencyCodes.UpdateCurrency("",
c[i].String(),
"",
0,
Cryptocurrency)
if err != nil {
return err
}
}
s.defaultCryptoCurrencies = append(s.defaultCryptoCurrencies, c...)
s.cryptocurrencies = append(s.cryptocurrencies, c...)
return nil
}
// SetupForexProviders sets up a new instance of the forex providers
func (s *Storage) SetupForexProviders(setting ...base.Settings) error {
addr, err := forexprovider.StartFXService(setting)
if err != nil {
return err
}
s.fiatExchangeMarkets = addr
return nil
}
// ForeignExchangeUpdater is a routine that seeds foreign exchange rate and keeps
// updated as fast as possible
func (s *Storage) ForeignExchangeUpdater() {
log.Debugln(log.Global,
"Foreign exchange updater started, seeding FX rate list..")
s.wg.Add(1)
defer s.wg.Done()
err := s.SeedCurrencyAnalysisData()
if err != nil {
log.Errorln(log.Global, err)
}
err = s.SeedForeignExchangeRates()
if err != nil {
log.Errorln(log.Global, err)
}
// Unlock main rate retrieval mutex so all routines waiting can get access
// to data
s.mtx.Unlock()
// Set tickers to client defined rates or defaults
SeedForeignExchangeTick := time.NewTicker(s.foreignExchangeUpdateDelay)
SeedCurrencyAnalysisTick := time.NewTicker(s.currencyFileUpdateDelay)
defer SeedForeignExchangeTick.Stop()
defer SeedCurrencyAnalysisTick.Stop()
for {
select {
case <-s.shutdown:
return
case <-SeedForeignExchangeTick.C:
go func() {
err := s.SeedForeignExchangeRates()
if err != nil {
log.Errorln(log.Global, err)
}
}()
case <-SeedCurrencyAnalysisTick.C:
go func() {
err := s.SeedCurrencyAnalysisData()
if err != nil {
log.Errorln(log.Global, err)
}
}()
}
}
}
// SeedCurrencyAnalysisData sets a new instance of a coinmarketcap data.
func (s *Storage) SeedCurrencyAnalysisData() error {
if s.currencyCodes.LastMainUpdate.IsZero() {
b, err := ioutil.ReadFile(s.path)
if err != nil {
return s.FetchCurrencyAnalysisData()
}
var f *File
err = json.Unmarshal(b, &f)
if err != nil {
return err
}
err = s.LoadFileCurrencyData(f)
if err != nil {
return err
}
}
// Based on update delay update the file
if time.Now().After(s.currencyCodes.LastMainUpdate.Add(s.currencyFileUpdateDelay)) ||
s.currencyCodes.LastMainUpdate.IsZero() {
err := s.FetchCurrencyAnalysisData()
if err != nil {
return err
}
}
return nil
}
// FetchCurrencyAnalysisData fetches a new fresh batch of currency data and
// loads it into memory
func (s *Storage) FetchCurrencyAnalysisData() error {
if s.currencyAnalysis == nil {
log.Warnln(log.Global,
"Currency analysis system offline, please set api keys for coinmarketcap if you wish to use this feature.")
return errors.New("currency analysis system offline")
}
return s.UpdateCurrencies()
}
// WriteCurrencyDataToFile writes the full currency data to a designated file
func (s *Storage) WriteCurrencyDataToFile(path string, mainUpdate bool) error {
data, err := s.currencyCodes.GetFullCurrencyData()
if err != nil {
return err
}
if mainUpdate {
t := time.Now()
data.LastMainUpdate = t.Unix()
s.currencyCodes.LastMainUpdate = t
}
var encoded []byte
encoded, err = json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return file.Write(path, encoded)
}
// LoadFileCurrencyData loads currencies into the currency codes
func (s *Storage) LoadFileCurrencyData(f *File) error {
for i := range f.Contracts {
contract := f.Contracts[i]
contract.Role = Contract
err := s.currencyCodes.LoadItem(&contract)
if err != nil {
return err
}
}
for i := range f.Cryptocurrency {
crypto := f.Cryptocurrency[i]
crypto.Role = Cryptocurrency
err := s.currencyCodes.LoadItem(&crypto)
if err != nil {
return err
}
}
for i := range f.Token {
token := f.Token[i]
token.Role = Token
err := s.currencyCodes.LoadItem(&token)
if err != nil {
return err
}
}
for i := range f.FiatCurrency {
fiat := f.FiatCurrency[i]
fiat.Role = Fiat
err := s.currencyCodes.LoadItem(&fiat)
if err != nil {
return err
}
}
for i := range f.UnsetCurrency {
unset := f.UnsetCurrency[i]
unset.Role = Unset
err := s.currencyCodes.LoadItem(&unset)
if err != nil {
return err
}
}
switch t := f.LastMainUpdate.(type) {
case string:
parseT, err := time.Parse(time.RFC3339Nano, t)
if err != nil {
return err
}
s.currencyCodes.LastMainUpdate = parseT
case float64:
s.currencyCodes.LastMainUpdate = time.Unix(int64(t), 0)
default:
return errors.New("unhandled type conversion for LastMainUpdate time")
}
return nil
}
// UpdateCurrencies updates currency role and information using coin market cap
func (s *Storage) UpdateCurrencies() error {
m, err := s.currencyAnalysis.GetCryptocurrencyIDMap()
if err != nil {
return err
}
for x := range m {
if m[x].IsActive != 1 {
continue
}
if m[x].Platform.Symbol != "" {
err = s.currencyCodes.UpdateCurrency(m[x].Name,
m[x].Symbol,
m[x].Platform.Symbol,
m[x].ID,
Token)
if err != nil {
return err
}
continue
}
err = s.currencyCodes.UpdateCurrency(m[x].Name,
m[x].Symbol,
"",
m[x].ID,
Cryptocurrency)
if err != nil {
return err
}
}
return nil
}
// SeedForeignExchangeRatesByCurrencies seeds the foreign exchange rates by
// currencies supplied
func (s *Storage) SeedForeignExchangeRatesByCurrencies(c Currencies) error {
s.fxRates.mtx.Lock()
defer s.fxRates.mtx.Unlock()
rates, err := s.fiatExchangeMarkets.GetCurrencyData(s.baseCurrency.String(),
c.Strings())
if err != nil {
return err
}
return s.updateExchangeRates(rates)
}
// SeedForeignExchangeRate returns a singular exchange rate
func (s *Storage) SeedForeignExchangeRate(from, to Code) (map[string]float64, error) {
return s.fiatExchangeMarkets.GetCurrencyData(from.String(),
[]string{to.String()})
}
// GetDefaultForeignExchangeRates returns foreign exchange rates based off
// default fiat currencies.
func (s *Storage) GetDefaultForeignExchangeRates() (Conversions, error) {
if !s.updaterRunning {
err := s.SeedDefaultForeignExchangeRates()
if err != nil {
return nil, err
}
}
return s.fxRates.GetFullRates(), nil
}
// SeedDefaultForeignExchangeRates seeds the default foreign exchange rates
func (s *Storage) SeedDefaultForeignExchangeRates() error {
s.fxRates.mtx.Lock()
defer s.fxRates.mtx.Unlock()
rates, err := s.fiatExchangeMarkets.GetCurrencyData(
s.defaultBaseCurrency.String(),
s.defaultFiatCurrencies.Strings())
if err != nil {
return err
}
return s.updateExchangeRates(rates)
}
// GetExchangeRates returns storage seeded exchange rates
func (s *Storage) GetExchangeRates() (Conversions, error) {
if !s.updaterRunning {
err := s.SeedForeignExchangeRates()
if err != nil {
return nil, err
}
}
return s.fxRates.GetFullRates(), nil
}
// SeedForeignExchangeRates seeds the foreign exchange rates from storage config
// currencies
func (s *Storage) SeedForeignExchangeRates() error {
s.fxRates.mtx.Lock()
defer s.fxRates.mtx.Unlock()
rates, err := s.fiatExchangeMarkets.GetCurrencyData(s.baseCurrency.String(),
s.fiatCurrencies.Strings())
if err != nil {
return err
}
return s.updateExchangeRates(rates)
}
// UpdateForeignExchangeRates sets exchange rates on the FX map
func (s *Storage) updateExchangeRates(m map[string]float64) error {
return s.fxRates.Update(m)
}
// SetupCryptoProvider sets congiguration parameters and starts a new instance
// of the currency analyser
func (s *Storage) SetupCryptoProvider(settings coinmarketcap.Settings) error {
if settings.APIkey == "" ||
settings.APIkey == "key" ||
settings.AccountPlan == "" ||
settings.AccountPlan == "accountPlan" {
return errors.New("currencyprovider error api key or plan not set in config.json")
}
s.currencyAnalysis = new(coinmarketcap.Coinmarketcap)
s.currencyAnalysis.SetDefaults()
return s.currencyAnalysis.Setup(settings)
}
// GetTotalMarketCryptocurrencies returns the total seeded market
// cryptocurrencies
func (s *Storage) GetTotalMarketCryptocurrencies() (Currencies, error) {
if !s.currencyCodes.HasData() {
return nil, errors.New("market currency codes not populated")
}
return s.currencyCodes.GetCurrencies(), nil
}
// IsDefaultCurrency returns if a currency is a default currency
func (s *Storage) IsDefaultCurrency(c Code) bool {
for i := range s.defaultFiatCurrencies {
if s.defaultFiatCurrencies[i].Match(c) ||
s.defaultFiatCurrencies[i].Match(GetTranslation(c)) {
return true
}
}
return false
}
// IsDefaultCryptocurrency returns if a cryptocurrency is a default
// cryptocurrency
func (s *Storage) IsDefaultCryptocurrency(c Code) bool {
for i := range s.defaultCryptoCurrencies {
if s.defaultCryptoCurrencies[i].Match(c) ||
s.defaultCryptoCurrencies[i].Match(GetTranslation(c)) {
return true
}
}
return false
}
// IsFiatCurrency returns if a currency is part of the enabled fiat currency
// list
func (s *Storage) IsFiatCurrency(c Code) bool {
if c.Item.Role != Unset {
return c.Item.Role == Fiat
}
if c == USDT {
return false
}
for i := range s.fiatCurrencies {
if s.fiatCurrencies[i].Match(c) ||
s.fiatCurrencies[i].Match(GetTranslation(c)) {
return true
}
}
return false
}
// IsCryptocurrency returns if a cryptocurrency is part of the enabled
// cryptocurrency list
func (s *Storage) IsCryptocurrency(c Code) bool {
if c.Item.Role != Unset {
return c.Item.Role == Cryptocurrency
}
if c == USD {
return false
}
for i := range s.cryptocurrencies {
if s.cryptocurrencies[i].Match(c) ||
s.cryptocurrencies[i].Match(GetTranslation(c)) {
return true
}
}
return false
}
// ValidateCode validates string against currency list and returns a currency
// code
func (s *Storage) ValidateCode(newCode string) Code {
return s.currencyCodes.Register(newCode)
}
// ValidateFiatCode validates a fiat currency string and returns a currency
// code
func (s *Storage) ValidateFiatCode(newCode string) Code {
c := s.currencyCodes.RegisterFiat(newCode)
if !s.fiatCurrencies.Contains(c) {
s.fiatCurrencies = append(s.fiatCurrencies, c)
}
return c
}
// ValidateCryptoCode validates a cryptocurrency string and returns a currency
// code
// TODO: Update and add in RegisterCrypto member func
func (s *Storage) ValidateCryptoCode(newCode string) Code {
c := s.currencyCodes.Register(newCode)
if !s.cryptocurrencies.Contains(c) {
s.cryptocurrencies = append(s.cryptocurrencies, c)
}
return c
}
// UpdateBaseCurrency changes base currency
func (s *Storage) UpdateBaseCurrency(c Code) error {
if c.IsFiatCurrency() {
s.baseCurrency = c
return nil
}
return fmt.Errorf("currency %s not fiat failed to set currency", c)
}
// GetCryptocurrencies returns the cryptocurrency list
func (s *Storage) GetCryptocurrencies() Currencies {
return s.cryptocurrencies
}
// GetDefaultCryptocurrencies returns a list of default cryptocurrencies
func (s *Storage) GetDefaultCryptocurrencies() Currencies {
return s.defaultCryptoCurrencies
}
// GetFiatCurrencies returns the fiat currencies list
func (s *Storage) GetFiatCurrencies() Currencies {
return s.fiatCurrencies
}
// GetDefaultFiatCurrencies returns the default fiat currencies list
func (s *Storage) GetDefaultFiatCurrencies() Currencies {
return s.defaultFiatCurrencies
}
// GetDefaultBaseCurrency returns the default base currency
func (s *Storage) GetDefaultBaseCurrency() Code {
return s.defaultBaseCurrency
}
// GetBaseCurrency returns the current storage base currency
func (s *Storage) GetBaseCurrency() Code {
return s.baseCurrency
}
// UpdateEnabledCryptoCurrencies appends new cryptocurrencies to the enabled
// currency list
func (s *Storage) UpdateEnabledCryptoCurrencies(c Currencies) {
for i := range c {
if !s.cryptocurrencies.Contains(c[i]) {
s.cryptocurrencies = append(s.cryptocurrencies, c[i])
}
}
}
// UpdateEnabledFiatCurrencies appends new fiat currencies to the enabled
// currency list
func (s *Storage) UpdateEnabledFiatCurrencies(c Currencies) {
for i := range c {
if !s.fiatCurrencies.Contains(c[i]) &&
!s.cryptocurrencies.Contains(c[i]) {
s.fiatCurrencies = append(s.fiatCurrencies, c[i])
}
}
}
// ConvertCurrency for example converts $1 USD to the equivalent Japanese Yen
// or vice versa.
func (s *Storage) ConvertCurrency(amount float64, from, to Code) (float64, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if !s.fxRates.HasData() {
err := s.SeedDefaultForeignExchangeRates()
if err != nil {
return 0, err
}
}
r, err := s.fxRates.GetRate(from, to)
if err != nil {
return 0, err
}
return r * amount, nil
}
// GetStorageRate returns the rate of the conversion value
func (s *Storage) GetStorageRate(from, to Code) (float64, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if !s.fxRates.HasData() {
err := s.SeedDefaultForeignExchangeRates()
if err != nil {
return 0, err
}
}
return s.fxRates.GetRate(from, to)
}
// NewConversion returns a new conversion object that has a pointer to a related
// rate with its inversion.
func (s *Storage) NewConversion(from, to Code) (Conversion, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
if !s.fxRates.HasData() {
err := storage.SeedDefaultForeignExchangeRates()
if err != nil {
return Conversion{}, err
}
}
return s.fxRates.Register(from, to)
}
// IsVerbose returns if the storage is in verbose mode
func (s *Storage) IsVerbose() bool {
return s.Verbose
}
// Shutdown shuts down the currency storage system and saves to currency.json
func (s *Storage) Shutdown() error {
s.mtx.Lock()
defer s.mtx.Unlock()
close(s.shutdown)
s.wg.Wait()
return s.WriteCurrencyDataToFile(s.path, true)
}