-
Notifications
You must be signed in to change notification settings - Fork 790
/
manager.go
567 lines (491 loc) · 13.9 KB
/
manager.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
package currency
import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
)
// Public errors
var (
ErrAssetAlreadyEnabled = errors.New("asset already enabled")
ErrAssetIsNil = errors.New("asset is nil")
ErrAssetNotFound = errors.New("asset type not found in pair store")
ErrPairAlreadyEnabled = errors.New("pair already enabled")
ErrPairFormatIsNil = errors.New("pair format is nil")
ErrPairManagerNotInitialised = errors.New("pair manager not initialised")
ErrPairNotContainedInAvailablePairs = errors.New("pair not contained in available pairs")
ErrPairNotEnabled = errors.New("pair not enabled")
ErrPairNotFound = errors.New("pair not found")
ErrSymbolStringEmpty = errors.New("symbol string is empty")
)
var (
errPairStoreIsNil = errors.New("pair store is nil")
errPairMatcherIsNil = errors.New("pair matcher is nil")
errPairConfigFormatNil = errors.New("pair config format is nil")
)
// GetAssetTypes returns a list of stored asset types
func (p *PairsManager) GetAssetTypes(enabled bool) asset.Items {
p.mutex.RLock()
defer p.mutex.RUnlock()
assetTypes := make(asset.Items, 0, len(p.Pairs))
for k, ps := range p.Pairs {
if enabled && (ps.AssetEnabled == nil || !*ps.AssetEnabled) {
continue
}
assetTypes = append(assetTypes, k)
}
return assetTypes
}
// Get gets the currency pair config based on the asset type
func (p *PairsManager) Get(a asset.Item) (*PairStore, error) {
if !a.IsValid() {
return nil, fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
p.mutex.RLock()
defer p.mutex.RUnlock()
c, ok := p.Pairs[a]
if !ok {
return nil, fmt.Errorf("cannot get pair store, %v %w", a, asset.ErrNotSupported)
}
return c.clone(), nil
}
// Match returns a currency pair based on the supplied symbol and asset type
func (p *PairsManager) Match(symbol string, a asset.Item) (Pair, error) {
if symbol == "" {
return EMPTYPAIR, ErrSymbolStringEmpty
}
symbol = strings.ToLower(symbol)
p.mutex.RLock()
defer p.mutex.RUnlock()
if p.matcher == nil {
return EMPTYPAIR, errPairMatcherIsNil
}
pair, ok := p.matcher[key{symbol, a}]
if !ok {
return EMPTYPAIR, fmt.Errorf("%w for %v %v", ErrPairNotFound, symbol, a)
}
return *pair, nil
}
// Store stores a new currency pair config based on its asset type
func (p *PairsManager) Store(a asset.Item, ps *PairStore) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
if ps == nil {
return errPairStoreIsNil
}
p.mutex.Lock()
defer p.mutex.Unlock()
if p.Pairs == nil {
p.Pairs = FullStore{}
}
p.Pairs[a] = ps.clone()
p.reindex()
return nil
}
// Delete deletes a map entry based on the supplied asset type
func (p *PairsManager) Delete(a asset.Item) {
p.mutex.Lock()
vals, ok := p.Pairs[a]
if !ok {
p.mutex.Unlock()
return
}
for x := range vals.Available {
delete(p.matcher, key{Symbol: vals.Available[x].Base.Lower().String() + vals.Available[x].Quote.Lower().String(), Asset: a})
}
delete(p.Pairs, a)
p.mutex.Unlock()
}
// GetPairs gets a list of stored pairs based on the asset type and whether
// they're enabled or not
func (p *PairsManager) GetPairs(a asset.Item, enabled bool) (Pairs, error) {
if !a.IsValid() {
return nil, fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
p.mutex.RLock()
defer p.mutex.RUnlock()
pairStore, ok := p.Pairs[a]
if !ok {
return nil, nil
}
if !enabled {
return slices.Clone(pairStore.Available), nil
}
lenCheck := len(pairStore.Enabled)
if lenCheck == 0 {
return nil, nil
}
// NOTE: enabledPairs is declared before the next check for comparison
// reasons within exchange update pairs functionality.
enabledPairs := slices.Clone(pairStore.Enabled)
err := pairStore.Available.ContainsAll(pairStore.Enabled, true)
if err != nil {
err = fmt.Errorf("%w of asset type %s", err, a)
}
return enabledPairs, err
}
// StoreFormat stores a new format for request or config format.
func (p *PairsManager) StoreFormat(a asset.Item, pFmt *PairFormat, config bool) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
if pFmt == nil {
return ErrPairFormatIsNil
}
p.mutex.Lock()
defer p.mutex.Unlock()
if p.Pairs == nil {
p.Pairs = make(map[asset.Item]*PairStore)
}
pairStore, ok := p.Pairs[a]
if !ok {
pairStore = new(PairStore)
p.Pairs[a] = pairStore
}
if config {
pairStore.ConfigFormat = pFmt.clone()
} else {
pairStore.RequestFormat = pFmt.clone()
}
return nil
}
// GetFormat returns the pair format in a concurrent safe manner
func (p *PairsManager) GetFormat(a asset.Item, request bool) (PairFormat, error) {
p.mutex.RLock()
defer p.mutex.RUnlock()
var pFmt *PairFormat
if p.UseGlobalFormat {
if request {
pFmt = p.RequestFormat
} else {
pFmt = p.ConfigFormat
}
} else {
ps, err := p.getPairStoreRequiresLock(a)
if err != nil {
return EMPTYFORMAT, err
}
if request {
pFmt = ps.RequestFormat
} else {
pFmt = ps.ConfigFormat
}
}
if pFmt == nil {
return EMPTYFORMAT, ErrPairFormatIsNil
}
return *pFmt, nil
}
// StorePairs stores a list of pairs based on the asset type and whether
// they're enabled or not
func (p *PairsManager) StorePairs(a asset.Item, pairs Pairs, enabled bool) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
p.mutex.Lock()
defer p.mutex.Unlock()
if p.Pairs == nil {
p.Pairs = make(map[asset.Item]*PairStore)
}
pairStore, ok := p.Pairs[a]
if !ok {
pairStore = new(PairStore)
p.Pairs[a] = pairStore
}
if enabled {
pairStore.Enabled = slices.Clone(pairs)
} else {
pairStore.Available = slices.Clone(pairs)
p.reindex()
}
return nil
}
// 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
// returns the asset and pair of a pair if it has been enabled
func (p *PairsManager) EnsureOnePairEnabled() (Pair, asset.Item, error) {
if p == nil {
return EMPTYPAIR, asset.Empty, common.ErrNilPointer
}
p.mutex.Lock()
defer p.mutex.Unlock()
for _, v := range p.Pairs {
if v.AssetEnabled == nil ||
!*v.AssetEnabled ||
len(v.Available) == 0 {
continue
}
if len(v.Enabled) > 0 {
return EMPTYPAIR, asset.Empty, nil
}
}
for k, v := range p.Pairs {
if v.AssetEnabled == nil ||
!*v.AssetEnabled ||
len(v.Available) == 0 {
continue
}
rp, err := v.Available.GetRandomPair()
if err != nil {
return EMPTYPAIR, asset.Empty, err
}
p.Pairs[k].Enabled = v.Enabled.Add(rp)
return rp, k, nil
}
return EMPTYPAIR, asset.Empty, ErrCurrencyPairsEmpty
}
// DisablePair removes the pair from the enabled pairs list if found
func (p *PairsManager) DisablePair(a asset.Item, pair Pair) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
if pair.IsEmpty() {
return ErrCurrencyPairEmpty
}
p.mutex.Lock()
defer p.mutex.Unlock()
pairStore, err := p.getPairStoreRequiresLock(a)
if err != nil {
return err
}
enabled, err := pairStore.Enabled.Remove(pair)
if err != nil {
return err
}
pairStore.Enabled = enabled
return nil
}
// EnablePair adds a pair to the list of enabled pairs if it exists in the list
// of available pairs and isn't already added
func (p *PairsManager) EnablePair(a asset.Item, pair Pair) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
if pair.IsEmpty() {
return ErrCurrencyPairEmpty
}
p.mutex.Lock()
defer p.mutex.Unlock()
pairStore, err := p.getPairStoreRequiresLock(a)
if err != nil {
return err
}
if pairStore.Enabled.Contains(pair, true) {
return fmt.Errorf("%s %w", pair, ErrPairAlreadyEnabled)
}
if !pairStore.Available.Contains(pair, true) {
return fmt.Errorf("%s %w in the list of available pairs",
pair, ErrPairNotFound)
}
pairStore.Enabled = pairStore.Enabled.Add(pair)
return nil
}
// IsPairAvailable checks if a pair is available for a given asset type
func (p *PairsManager) IsPairAvailable(pair Pair, a asset.Item) (bool, error) {
if !a.IsValid() {
return false, fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
if pair.IsEmpty() {
return false, ErrCurrencyPairEmpty
}
p.mutex.RLock()
defer p.mutex.RUnlock()
pairStore, err := p.getPairStoreRequiresLock(a)
if err != nil {
return false, err
}
if pairStore.AssetEnabled == nil {
return false, fmt.Errorf("%s %w", a, ErrAssetIsNil)
}
return *pairStore.AssetEnabled && pairStore.Available.Contains(pair, true), nil
}
// IsPairEnabled checks if a pair is enabled for an enabled asset type
func (p *PairsManager) IsPairEnabled(pair Pair, a asset.Item) (bool, error) {
if !a.IsValid() {
return false, fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
if pair.IsEmpty() {
return false, ErrCurrencyPairEmpty
}
p.mutex.RLock()
defer p.mutex.RUnlock()
pairStore, err := p.getPairStoreRequiresLock(a)
if err != nil {
return false, err
}
if pairStore.AssetEnabled == nil {
return false, fmt.Errorf("%s %w", a, ErrAssetIsNil)
}
return *pairStore.AssetEnabled && pairStore.Enabled.Contains(pair, true), nil
}
// IsAssetEnabled checks to see if an asset is enabled
func (p *PairsManager) IsAssetEnabled(a asset.Item) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
p.mutex.RLock()
defer p.mutex.RUnlock()
pairStore, err := p.getPairStoreRequiresLock(a)
if err != nil {
return err
}
if pairStore.AssetEnabled == nil {
return fmt.Errorf("%s %w", a, ErrAssetIsNil)
}
if !*pairStore.AssetEnabled {
return fmt.Errorf("%s %w", a, asset.ErrNotEnabled)
}
return nil
}
// IsAssetSupported returns if the asset is supported by an exchange
// Does not imply that the Asset is enabled
func (p *PairsManager) IsAssetSupported(a asset.Item) bool {
p.mutex.RLock()
defer p.mutex.RUnlock()
_, ok := p.Pairs[a]
return ok
}
// SetAssetEnabled sets if an asset is enabled or disabled for first run
func (p *PairsManager) SetAssetEnabled(a asset.Item, enabled bool) error {
if !a.IsValid() {
return fmt.Errorf("%s %w", a, asset.ErrNotSupported)
}
p.mutex.Lock()
defer p.mutex.Unlock()
pairStore, err := p.getPairStoreRequiresLock(a)
if err != nil {
return err
}
if pairStore.AssetEnabled == nil {
pairStore.AssetEnabled = convert.BoolPtr(enabled)
return nil
}
if !*pairStore.AssetEnabled && !enabled {
return errors.New("asset already disabled")
} else if *pairStore.AssetEnabled && enabled {
return ErrAssetAlreadyEnabled
}
*pairStore.AssetEnabled = enabled
return nil
}
// Load sets the pair manager from a seed without copying mutexes
func (p *PairsManager) Load(seed *PairsManager) {
p.mutex.Lock()
defer p.mutex.Unlock()
seed.mutex.RLock()
defer seed.mutex.RUnlock()
p.BypassConfigFormatUpgrades = seed.BypassConfigFormatUpgrades
p.UseGlobalFormat = seed.UseGlobalFormat
p.LastUpdated = seed.LastUpdated
p.Pairs = seed.Pairs.clone()
p.RequestFormat = seed.RequestFormat.clone()
p.ConfigFormat = seed.ConfigFormat.clone()
p.reindex()
}
// reindex re-indexes the matcher for Available pairs and all assets
// This method does not lock for concurrency
func (p *PairsManager) reindex() {
p.matcher = make(map[key]*Pair)
for a, fs := range p.Pairs {
for i, pair := range fs.Available {
k := key{Symbol: pair.Base.Lower().String() + pair.Quote.Lower().String(), Asset: a}
p.matcher[k] = &fs.Available[i]
}
}
}
func (p *PairsManager) getPairStoreRequiresLock(a asset.Item) (*PairStore, error) {
if p.Pairs == nil {
return nil, fmt.Errorf("%w when requesting %v pairs", ErrPairManagerNotInitialised, a)
}
pairStore, ok := p.Pairs[a]
if !ok {
return nil, fmt.Errorf("%w %w %v", ErrAssetNotFound, asset.ErrNotSupported, a)
}
if pairStore == nil {
return nil, errors.New("currency store is nil")
}
return pairStore, nil
}
// SetDelimitersFromConfig ensures that the pairs adhere to the configured delimiters
// Pairs.Unmarshal doesn't know what the delimiter is, so uses the first punctuation rune
func (p *PairsManager) SetDelimitersFromConfig() error {
for a, s := range p.Pairs {
cf := s.ConfigFormat
if cf == nil {
cf = p.ConfigFormat
}
if cf == nil {
return errPairConfigFormatNil
}
for i, p := range []Pairs{s.Enabled, s.Available} {
for j := range p {
if p[j].Delimiter == cf.Delimiter {
continue
}
nP, err := NewPairDelimiter(p[j].String(), cf.Delimiter)
if err != nil {
return fmt.Errorf("%s.%s.%s: %w", a, []string{"enabled", "available"}[i], p[j], err)
}
p[j] = nP
}
}
}
return nil
}
// UnmarshalJSON implements the unmarshal json interface so that the key can be
// correctly unmarshalled from a string into a uint.
func (fs *FullStore) UnmarshalJSON(d []byte) error {
var temp map[string]*PairStore
err := json.Unmarshal(d, &temp)
if err != nil {
return err
}
*fs = make(FullStore, len(temp))
for key, val := range temp {
ai, err := asset.New(key)
if err != nil {
return err
}
(*fs)[ai] = val
}
return nil
}
// MarshalJSON implements the marshal json interface so that the key can be
// correctly marshalled from a uint.
func (fs FullStore) MarshalJSON() ([]byte, error) {
temp := make(map[string]*PairStore, len(fs))
for key, val := range fs {
temp[key.String()] = val
}
return json.Marshal(temp)
}
// clone returns a deep clone of the PairStore
func (ps *PairStore) clone() *PairStore {
if ps == nil {
return nil
}
var assetEnabled *bool
if ps.AssetEnabled != nil {
assetEnabled = convert.BoolPtr(*ps.AssetEnabled)
}
return &PairStore{
AssetEnabled: assetEnabled,
Enabled: slices.Clone(ps.Enabled),
Available: slices.Clone(ps.Available),
RequestFormat: ps.RequestFormat.clone(),
ConfigFormat: ps.ConfigFormat.clone(),
}
}
func (fs FullStore) clone() FullStore {
c := FullStore{}
for a, pairStore := range fs {
c[a] = pairStore.clone()
}
return c
}