Files
gocryptotrader/currency/pairs.go
Ryan O'Hara-Reid 11da520dc8 Currency: Add additional functionality, refactor and improvements (#881)
* currency: Add method to derive pair

* currency: Add method to lower entire charset but used the slice copy and returned that. This will change the original, just gotta see if this is an issue, but the slice usually goes out of scope anyway.

* currency/pairs: add filter method

* currency: add function to derive select currencies from currency pairs

* currency/engine: slight adjustments

* currency: fix linter issue also shift burden of proof to caller instead of repair, more performant.

* currency: more linter

* pairs: optimize; reduce allocs/op and B/op

* currency: Add in function 'NewPairsFromString' for testing purposes

* currency: don't suppress error

* currency: stop panic on empty currency code

* currency: Add helper method to match currencies between exchanges

* currency: fixed my bad spelling

* currency: Implement stable coin checks, refactored base code methods, optimized upper and lower case strings for currency code/pairs

* currency: add pairs method to derive stable coins from internal list.

* Currency: Cleanup, fix tests.

* engine/exchanges/currency: fix whoops

* Currency: force govet no copy on Item datatype

* Currency: fix naughty linter issues

* exchange: revert change

* currency/config: fix config upgrade mistake

* currency: re-implement currency sub-systems

* *RetrieveConfigCurrencyPairs removed
*CheckCurrencyConfigValues to only provide warnings, add additional support when, disable when support is lost or not available and set default values.
*Drop Cryptocurrencies from configuration as this is not needed.
*Drop REST Poll delay field as this was unused.
*Update default values for currencyFileUpdateDuration & foreignExchangeUpdateDuration.
*Allow Role to be marshalled for file type.
*Refactor RunUpdater to verify and check config values and set default running foreign exchange provider.

* currency: cleanup

* currency: change match -> equal for comparison which is more of a standard and little easier to find

* currency: address nits

* currency: fix whoops

* currency: Add some more pairs methods

* currency: linter issues

* currency: RM unused field

* currency: rm verbose

* currency: fix word

* currency: gocritic

* currency: fix another whoopsie

* example_config: default to show log system name

* Currency: Force all support packages to use Equal method for comparison as there is a small comparison bug when checking upper and lower casing, this has a more of a pronounced impact between exchanges and client instances of currency generation

* currency: fix log name

* ordermanager: fix potential panic

* currency: small optim.

* engine: display correct bool and force shutdown

* currency: add function and fix regression
* Change ConvertCurrency -> ConvertFiat to be more precise
* ADD GetForeignExchangeRate to get specific exchange rate for fiat pair
* Fix currency display and formatting regression and tied in with config.Currency fields

* engine: fix tests

* currency: return the amount when no conversion needs to take place

* currency: reduce method name

* currency: Address nits glorious nits

* currency: fix linter

* currency: addr nits

* currency: check underlying role in test

* gct: change to EMPTYCODE and EMPTYPAIR across codebase

* currency: fix nits

* currency: this fixes test race but this issue has not been resolved. Please see: https://trello.com/c/54eizOIo/143-currency-package-upgrades

* currency: Add temp dir for testing

* Update engine/engine.go

Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>

* documentation: update and regen

* currency: Address niterinos

* currency: Add test case for config upgrade when falling over to exchange rate host as default from exchangeRates provider

* currency: addr nits

* currency: fix whoops

Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io>
Co-authored-by: Adrian Gallagher <adrian.gallagher@thrasher.io>
2022-02-17 16:24:57 +11:00

334 lines
7.9 KiB
Go

package currency
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"strings"
"github.com/thrasher-corp/gocryptotrader/log"
)
var (
errSymbolEmpty = errors.New("symbol is empty")
errPairsEmpty = errors.New("pairs are empty")
errNoDelimiter = errors.New("no delimiter was supplied")
)
// NewPairsFromStrings takes in currency pair strings and returns a currency
// pair list
func NewPairsFromStrings(pairs []string) (Pairs, error) {
allThePairs := make(Pairs, len(pairs))
var err error
for i := range pairs {
allThePairs[i], err = NewPairFromString(pairs[i])
if err != nil {
return nil, err
}
}
return allThePairs, nil
}
// NewPairsFromString takes in a delimiter string and returns a Pairs
// type
func NewPairsFromString(pairs, delimiter string) (Pairs, error) {
if delimiter == "" {
return nil, errNoDelimiter
}
return NewPairsFromStrings(strings.Split(pairs, delimiter))
}
// Strings returns a slice of strings referring to each currency pair
func (p Pairs) Strings() []string {
list := make([]string, len(p))
for i := range p {
list[i] = p[i].String()
}
return list
}
// Join returns a comma separated list of currency pairs
func (p Pairs) Join() string {
return strings.Join(p.Strings(), ",")
}
// Format formats the pair list to the exchange format configuration
func (p Pairs) Format(delimiter, index string, uppercase bool) Pairs {
pairs := make(Pairs, 0, len(p))
var err error
for _, format := range p {
if index != "" {
format, err = NewPairFromIndex(format.String(), index)
if err != nil {
log.Errorf(log.Global,
"failed to create NewPairFromIndex. Err: %s\n", err)
continue
}
}
format.Delimiter = delimiter
if uppercase {
pairs = append(pairs, format.Upper())
} else {
pairs = append(pairs, format.Lower())
}
}
return pairs
}
// UnmarshalJSON comforms type to the umarshaler interface
func (p *Pairs) UnmarshalJSON(d []byte) error {
var pairs string
err := json.Unmarshal(d, &pairs)
if err != nil {
return err
}
// If no pairs enabled in config just continue
if pairs == "" {
return nil
}
*p, err = NewPairsFromString(pairs, ",")
return err
}
// MarshalJSON conforms type to the marshaler interface
func (p Pairs) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Join())
}
// Upper updates the original pairs and returns the pairs for convenience if
// needed.
func (p Pairs) Upper() Pairs {
for i := range p {
p[i] = p[i].Upper()
}
return p
}
// Lower updates the original pairs and returns the pairs for convenience if
// needed.
func (p Pairs) Lower() Pairs {
for i := range p {
p[i] = p[i].Lower()
}
return p
}
// Contains checks to see if a specified pair exists inside a currency pair
// array
func (p Pairs) Contains(check Pair, exact bool) bool {
for i := range p {
if exact {
if p[i].Equal(check) {
return true
}
} else {
if p[i].EqualIncludeReciprocal(check) {
return true
}
}
}
return false
}
// RemovePairsByFilter checks to see if a pair contains a specific currency
// and removes it from the list of pairs
func (p Pairs) RemovePairsByFilter(filter Code) Pairs {
pairs := make(Pairs, 0, len(p))
for i := range p {
if p[i].Contains(filter) {
continue
}
pairs = append(pairs, p[i])
}
return pairs
}
// GetPairsByFilter returns all pairs that have at least one match base or quote
// to the filter code.
func (p Pairs) GetPairsByFilter(filter Code) Pairs {
pairs := make(Pairs, 0, len(p))
for i := range p {
if !p[i].Contains(filter) {
continue
}
pairs = append(pairs, p[i])
}
return pairs
}
// Remove removes the specified pair from the list of pairs if it exists
func (p Pairs) Remove(pair Pair) Pairs {
pairs := make(Pairs, 0, len(p))
for x := range p {
if p[x].Equal(pair) {
continue
}
pairs = append(pairs, p[x])
}
return pairs
}
// Add adds a specified pair to the list of pairs if it doesn't exist
func (p Pairs) Add(pair Pair) Pairs {
if p.Contains(pair, true) {
return p
}
p = append(p, pair)
return p
}
// GetMatch returns either the pair that is equal including the reciprocal for
// when currencies are constructed from different exchange pairs e.g. Exchange
// one USDT-DAI to exchange two DAI-USDT enabled/available pairs.
func (p Pairs) GetMatch(pair Pair) (Pair, error) {
for x := range p {
if p[x].EqualIncludeReciprocal(pair) {
return p[x], nil
}
}
return EMPTYPAIR, ErrPairNotFound
}
// FindDifferences returns pairs which are new or have been removed
func (p Pairs) FindDifferences(pairs Pairs) (newPairs, removedPairs Pairs) {
for x := range pairs {
if pairs[x].String() == "" {
continue
}
if !p.Contains(pairs[x], true) {
newPairs = append(newPairs, pairs[x])
}
}
for x := range p {
if p[x].String() == "" {
continue
}
if !pairs.Contains(p[x], true) {
removedPairs = append(removedPairs, p[x])
}
}
return
}
// GetRandomPair returns a random pair from a list of pairs
func (p Pairs) GetRandomPair() Pair {
if pairsLen := len(p); pairsLen != 0 {
return p[rand.Intn(pairsLen)] // nolint:gosec // basic number generation required, no need for crypo/rand
}
return EMPTYPAIR
}
// DeriveFrom matches symbol string to the available pairs list when no
// delimiter is supplied.
func (p Pairs) DeriveFrom(symbol string) (Pair, error) {
if len(p) == 0 {
return EMPTYPAIR, errPairsEmpty
}
if symbol == "" {
return EMPTYPAIR, errSymbolEmpty
}
symbol = strings.ToLower(symbol)
pairs:
for x := range p {
if p[x].Len() != len(symbol) {
continue
}
base := p[x].Base.Lower().String()
baseLength := len(base)
for y := 0; y < baseLength; y++ {
if base[y] != symbol[y] {
continue pairs
}
}
quote := p[x].Quote.Lower().String()
for y := 0; y < len(quote); y++ {
if quote[y] != symbol[baseLength+y] {
continue pairs
}
}
return p[x], nil
}
return EMPTYPAIR, fmt.Errorf("%w for symbol string %s", ErrPairNotFound, symbol)
}
// GetCrypto returns all the cryptos contained in the list.
func (p Pairs) GetCrypto() Currencies {
m := make(map[*Item]bool)
for x := range p {
if p[x].Base.IsCryptocurrency() {
m[p[x].Base.Item] = p[x].Base.UpperCase
}
if p[x].Quote.IsCryptocurrency() {
m[p[x].Quote.Item] = p[x].Quote.UpperCase
}
}
return currencyConstructor(m)
}
// GetFiat returns all the cryptos contained in the list.
func (p Pairs) GetFiat() Currencies {
m := make(map[*Item]bool)
for x := range p {
if p[x].Base.IsFiatCurrency() {
m[p[x].Base.Item] = p[x].Base.UpperCase
}
if p[x].Quote.IsFiatCurrency() {
m[p[x].Quote.Item] = p[x].Quote.UpperCase
}
}
return currencyConstructor(m)
}
// GetCurrencies returns the full currency code list contained derived from the
// pairs list.
func (p Pairs) GetCurrencies() Currencies {
m := make(map[*Item]bool)
for x := range p {
m[p[x].Base.Item] = p[x].Base.UpperCase
m[p[x].Quote.Item] = p[x].Quote.UpperCase
}
return currencyConstructor(m)
}
// GetStables returns the stable currency code list derived from the pairs list.
func (p Pairs) GetStables() Currencies {
m := make(map[*Item]bool)
for x := range p {
if p[x].Base.IsStableCurrency() {
m[p[x].Base.Item] = p[x].Base.UpperCase
}
if p[x].Quote.IsStableCurrency() {
m[p[x].Quote.Item] = p[x].Quote.UpperCase
}
}
return currencyConstructor(m)
}
// currencyConstructor takes in an item map and returns the currencies with
// the same formatting.
func currencyConstructor(m map[*Item]bool) Currencies {
var cryptos = make([]Code, len(m))
var target int
for code, upper := range m {
cryptos[target].Item = code
cryptos[target].UpperCase = upper
target++
}
return cryptos
}
// GetStablesMatch returns all stable pairs matched with code
func (p Pairs) GetStablesMatch(code Code) Pairs {
stablePairs := make([]Pair, 0, len(p))
for x := range p {
if p[x].Base.IsStableCurrency() && p[x].Quote.Equal(code) ||
p[x].Quote.IsStableCurrency() && p[x].Base.Equal(code) {
stablePairs = append(stablePairs, p[x])
}
}
return stablePairs
}