Engine: Protocol Features, coverage, types, BTC markets websocket (#368)

* Attempts to update orderbook so it doesn't need to sort

* Reverts the ws ob stuff. Gets rid of sorting because it happens later. Adds some exchange features

* update existing feature lists. Expands list definition to match my emotions

* Adds bithumb bitmex and bitstamp. adds a couple more types

* Features for you, features for me, features for bittrex, btcmarkets, btse, coinbasepro, coinut, exmo, gateio and gemini

* Features for hitbtc, huobi, itbit, kraken, lakebtc, lbank, localbitcoins, okcoin, okex, poloniex, yobit, zb

* Who can forget good old alphapoint?

* Adds btcmarksets websocket :glitch_crab: fixes alphapoint features

* Adds extra data not in the documentation :/

* Replaces websocket features by using protocol features. However, it breaks it due to import cycles. I'm not sure what I'll do just yet

* Removes import cycle via duplicate structs.

* Increases coverage of config with `TestCheckCurrencyConfigValues`. Moves all currency pair package types into their own files or places it at the bottom of files if necessary

* Increase coverage in code.go

* One way of determining a test has failed, is when to it fails. Removed redundant explanation

* Increases code coverage of conversion

* Lint fixes

* Fixes orderbook tests

* Re-adds sorting because its important to still have the internal pre-processed orderbook to be representative of a real orderbook

* Secret lints that did not show up via Windows linting

* Adds protocol package to contain exchange features

* Fixes protocol implementation

* Fixes ws tests

* Addresses the following: Removes st-st-stutters in config types, changes GetAvailableForexProviders -> GetSupportedForexProviders, removes errors from tests where error is nil, removes orderbook setup when not necessary, removes import newlines, removes false bools from declaration, changes should of to should have

* imports and casing

* Fixes two more nil error checks
This commit is contained in:
Scott
2019-10-22 10:56:20 +11:00
committed by Adrian Gallagher
parent ec0ed1c1e5
commit ccfcdf26aa
156 changed files with 5228 additions and 4337 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -8,31 +8,31 @@ import (
func TestRoleString(t *testing.T) {
if Unset.String() != UnsetRollString {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
UnsetRollString,
Unset)
}
if Fiat.String() != FiatCurrencyString {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
FiatCurrencyString,
Fiat)
}
if Cryptocurrency.String() != CryptocurrencyString {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
CryptocurrencyString,
Cryptocurrency)
}
if Token.String() != TokenString {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
TokenString,
Token)
}
if Contract.String() != ContractString {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
ContractString,
Contract)
}
@@ -40,7 +40,7 @@ func TestRoleString(t *testing.T) {
var random Role = 1 << 7
if random.String() != "UNKNOWN" {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
"UNKNOWN",
random)
}
@@ -49,17 +49,18 @@ func TestRoleString(t *testing.T) {
func TestRoleMarshalJSON(t *testing.T) {
d, err := common.JSONEncode(Fiat)
if err != nil {
t.Error("Test Failed - Role MarshalJSON() error", err)
t.Error("Role MarshalJSON() error", err)
}
expected := `"fiatCurrency"`
if string(d) != expected {
t.Errorf("Test Failed - Role MarshalJSON() error expected %s but received %s",
t.Errorf("Role MarshalJSON() error expected %s but received %s",
expected,
string(d))
}
}
// TestRoleUnmarshalJSON logic test
func TestRoleUnmarshalJSON(t *testing.T) {
type AllTheRoles struct {
RoleOne Role `json:"RoleOne"`
@@ -80,136 +81,158 @@ func TestRoleUnmarshalJSON(t *testing.T) {
e, err := common.JSONEncode(1337)
if err != nil {
t.Fatal("Test Failed - Role UnmarshalJSON() error", err)
t.Fatal("Role UnmarshalJSON() error", err)
}
var incoming AllTheRoles
err = common.JSONDecode(e, &incoming)
if err == nil {
t.Fatal("Test Failed - Role UnmarshalJSON() error", err)
t.Fatal("Role UnmarshalJSON() Expected error")
}
e, err = common.JSONEncode(outgoing)
if err != nil {
t.Fatal("Test Failed - Role UnmarshalJSON() error", err)
t.Fatal("Role UnmarshalJSON() error", err)
}
err = common.JSONDecode(e, &incoming)
if err != nil {
t.Fatal("Test Failed - Role UnmarshalJSON() error", err)
t.Fatal("Role UnmarshalJSON() error", err)
}
if incoming.RoleOne != Unset {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
Unset,
incoming.RoleOne)
}
if incoming.RoleTwo != Cryptocurrency {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
Cryptocurrency,
incoming.RoleTwo)
}
if incoming.RoleThree != Fiat {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
Fiat,
incoming.RoleThree)
}
if incoming.RoleFour != Token {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
Token,
incoming.RoleFour)
}
if incoming.RoleFive != Contract {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
Contract,
incoming.RoleFive)
}
if incoming.RoleUnknown != Unset {
t.Errorf("Test Failed - Role String() error expected %s but received %s",
t.Errorf("Role String() error expected %s but received %s",
incoming.RoleFive,
incoming.RoleUnknown)
}
var unhandled Role
err = unhandled.UnmarshalJSON([]byte("\"ThisIsntReal\""))
if err == nil {
t.Error("Expected unmarshall error")
}
}
func TestBaseCode(t *testing.T) {
var main BaseCodes
if main.HasData() {
t.Errorf("Test Failed - BaseCode HasData() error expected false but received %v",
t.Errorf("BaseCode HasData() error expected false but received %v",
main.HasData())
}
catsCode := main.Register("CATS")
if !main.HasData() {
t.Errorf("Test Failed - BaseCode HasData() error expected true but received %v",
t.Errorf("BaseCode HasData() error expected true but received %v",
main.HasData())
}
if !main.Register("CATS").Match(catsCode) {
t.Errorf("Test Failed - BaseCode Match() error expected true but received %v",
t.Errorf("BaseCode Match() error expected true but received %v",
false)
}
if main.Register("DOGS").Match(catsCode) {
t.Errorf("Test Failed - BaseCode Match() error expected false but received %v",
t.Errorf("BaseCode Match() error expected false but received %v",
true)
}
loadedCurrencies := main.GetCurrencies()
if loadedCurrencies.Contains(main.Register("OWLS")) {
t.Errorf("Test Failed - BaseCode Contains() error expected false but received %v",
t.Errorf("BaseCode Contains() error expected false but received %v",
true)
}
if !loadedCurrencies.Contains(catsCode) {
t.Errorf("Test Failed - BaseCode Contains() error expected true but received %v",
t.Errorf("BaseCode Contains() error expected true but received %v",
false)
}
err := main.UpdateContract("Bitcoin Perpetual", "XBTUSD", "Bitmex")
if err != nil {
t.Error("Test Failed - BaseCode UpdateContract error", err)
t.Error("BaseCode UpdateContract error", err)
}
err = main.UpdateCryptocurrency("Bitcoin", "BTC", 1337)
if err != nil {
t.Error("Test Failed - BaseCode UpdateContract error", err)
t.Error("BaseCode UpdateContract error", err)
}
err = main.UpdateFiatCurrency("Unreal Dollar", "AUD", 1111)
if err != nil {
t.Error("BaseCode UpdateContract error", err)
}
if main.Items[5].FullName != "Unreal Dollar" {
t.Error("Expected fullname to update for AUD")
}
err = main.UpdateFiatCurrency("Australian Dollar", "AUD", 1336)
if err != nil {
t.Error("Test Failed - BaseCode UpdateContract error", err)
t.Error("BaseCode UpdateContract error", err)
}
main.Items[5].Role = Unset
err = main.UpdateFiatCurrency("Australian Dollar", "AUD", 1336)
if err != nil {
t.Error("BaseCode UpdateContract error", err)
}
if main.Items[5].Role != Fiat {
t.Error("Expected role to change to Fiat")
}
err = main.UpdateToken("Populous", "PPT", "ETH", 1335)
if err != nil {
t.Error("Test Failed - BaseCode UpdateContract error", err)
t.Error("BaseCode UpdateContract error", err)
}
contract := main.Register("XBTUSD")
if contract.IsFiatCurrency() {
t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but received %v",
t.Errorf("BaseCode IsFiatCurrency() error expected false but received %v",
true)
}
if contract.IsCryptocurrency() {
t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but received %v",
t.Errorf("BaseCode IsFiatCurrency() error expected false but received %v",
true)
}
if contract.IsDefaultFiatCurrency() {
t.Errorf("Test Failed - BaseCode IsDefaultFiatCurrency() error expected false but received %v",
t.Errorf("BaseCode IsDefaultFiatCurrency() error expected false but received %v",
true)
}
if contract.IsDefaultFiatCurrency() {
t.Errorf("Test Failed - BaseCode IsFiatCurrency() error expected false but received %v",
t.Errorf("BaseCode IsFiatCurrency() error expected false but received %v",
true)
}
@@ -220,50 +243,101 @@ func TestBaseCode(t *testing.T) {
Symbol: "ADA",
})
if err != nil {
t.Error("Test Failed - BaseCode LoadItem() error", err)
t.Error("BaseCode LoadItem() error", err)
}
full, err := main.GetFullCurrencyData()
if err != nil {
t.Error("Test Failed - BaseCode GetFullCurrencyData error", err)
t.Error("BaseCode GetFullCurrencyData error", err)
}
if len(full.Contracts) != 1 {
t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v",
t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v",
len(full.Contracts))
}
if len(full.Cryptocurrency) != 2 {
t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v",
t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v",
len(full.Cryptocurrency))
}
if len(full.FiatCurrency) != 1 {
t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v",
t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v",
len(full.FiatCurrency))
}
if len(full.Token) != 1 {
t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 1 but received %v",
t.Errorf("BaseCode GetFullCurrencyData() error expected 1 but received %v",
len(full.Token))
}
if len(full.UnsetCurrency) != 3 {
t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 3 but received %v",
t.Errorf("BaseCode GetFullCurrencyData() error expected 3 but received %v",
len(full.UnsetCurrency))
}
if !full.LastMainUpdate.IsZero() {
t.Errorf("Test Failed - BaseCode GetFullCurrencyData() error expected 0 but received %s",
t.Errorf("BaseCode GetFullCurrencyData() error expected 0 but received %s",
full.LastMainUpdate)
}
err = main.LoadItem(&Item{
ID: 0,
FullName: "Cardano",
Role: Role(99),
Symbol: "ADA",
})
if err != nil {
t.Error("BaseCode LoadItem() error", err)
}
_, err = main.GetFullCurrencyData()
if err == nil {
t.Error("Expected 'Role undefined'")
}
main.Items[0].FullName = "Hello"
err = main.UpdateCryptocurrency("MEWOW", "CATS", 1338)
if err != nil {
t.Error("BaseCode UpdateContract error", err)
}
if main.Items[0].FullName != "MEWOW" {
t.Error("Fullname not updated")
}
err = main.UpdateCryptocurrency("MEWOW", "CATS", 1338)
if err != nil {
t.Error("BaseCode UpdateContract error", err)
}
main.Items[0].Role = Cryptocurrency
err = main.UpdateCryptocurrency("MEWOW", "CATS", 3)
if err != nil {
t.Error("BaseCode UpdateContract error", err)
}
if main.Items[0].ID != 3 {
t.Error("ID not updated")
}
main.Items[0].Role = Unset
err = main.UpdateCryptocurrency("MEWOW", "CATS", 1338)
if err != nil {
t.Error("BaseCode UpdateContract error", err)
}
if main.Items[0].ID != 1338 {
t.Error("ID not updated")
}
main.Items[0].Role = Token
err = main.UpdateCryptocurrency("MEWOW", "CATS", 3)
if err == nil {
t.Error("Expecting cryptocurrency to already exist")
}
}
func TestCodeString(t *testing.T) {
expected := "TEST"
cc := NewCode("TEST")
if cc.String() != expected {
t.Errorf("Test Failed - Currency Code String() error expected %s but received %s",
t.Errorf("Currency Code String() error expected %s but received %s",
expected, cc)
}
}
@@ -272,7 +346,7 @@ func TestCodeLower(t *testing.T) {
expected := "test"
cc := NewCode("TEST")
if cc.Lower().String() != expected {
t.Errorf("Test Failed - Currency Code Lower() error expected %s but received %s",
t.Errorf("Currency Code Lower() error expected %s but received %s",
expected,
cc.Lower())
}
@@ -282,7 +356,7 @@ func TestCodeUpper(t *testing.T) {
expected := "TEST"
cc := NewCode("test")
if cc.Upper().String() != expected {
t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s",
t.Errorf("Currency Code Upper() error expected %s but received %s",
expected,
cc.Upper())
}
@@ -293,21 +367,21 @@ func TestCodeUnmarshalJSON(t *testing.T) {
expected := "BRO"
encoded, err := common.JSONEncode(expected)
if err != nil {
t.Fatal("Test Failed - Currency Code UnmarshalJSON error", err)
t.Fatal("Currency Code UnmarshalJSON error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Currency Code UnmarshalJSON error", err)
t.Fatal("Currency Code UnmarshalJSON error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Currency Code UnmarshalJSON error", err)
t.Fatal("Currency Code UnmarshalJSON error", err)
}
if unmarshalHere.String() != expected {
t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s",
t.Errorf("Currency Code Upper() error expected %s but received %s",
expected,
unmarshalHere)
}
@@ -324,11 +398,11 @@ func TestCodeMarshalJSON(t *testing.T) {
encoded, err := common.JSONEncode(quickstruct)
if err != nil {
t.Fatal("Test Failed - Currency Code UnmarshalJSON error", err)
t.Fatal("Currency Code UnmarshalJSON error", err)
}
if string(encoded) != expectedJSON {
t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s",
t.Errorf("Currency Code Upper() error expected %s but received %s",
expectedJSON,
string(encoded))
}
@@ -341,42 +415,42 @@ func TestCodeMarshalJSON(t *testing.T) {
encoded, err = common.JSONEncode(quickstruct)
if err != nil {
t.Fatal("Test Failed - Currency Code UnmarshalJSON error", err)
t.Fatal("Currency Code UnmarshalJSON error", err)
}
newExpectedJSON := `{"sweetCodes":""}`
if string(encoded) != newExpectedJSON {
t.Errorf("Test Failed - Currency Code Upper() error expected %s but received %s",
t.Errorf("Currency Code Upper() error expected %s but received %s",
newExpectedJSON, string(encoded))
}
}
func TestIsDefaultCurrency(t *testing.T) {
if !USD.IsDefaultFiatCurrency() {
t.Errorf("Test Failed. TestIsDefaultCurrency Cannot match currency %s.",
t.Errorf("TestIsDefaultCurrency Cannot match currency %s.",
USD)
}
if !AUD.IsDefaultFiatCurrency() {
t.Errorf("Test Failed. TestIsDefaultCurrency Cannot match currency, %s.",
t.Errorf("TestIsDefaultCurrency Cannot match currency, %s.",
AUD)
}
if LTC.IsDefaultFiatCurrency() {
t.Errorf("Test Failed. TestIsDefaultCurrency Function return is incorrect with, %s.",
t.Errorf("TestIsDefaultCurrency Function return is incorrect with, %s.",
LTC)
}
}
func TestIsDefaultCryptocurrency(t *testing.T) {
if !BTC.IsDefaultCryptocurrency() {
t.Errorf("Test Failed. TestIsDefaultCryptocurrency cannot match currency, %s.",
t.Errorf("TestIsDefaultCryptocurrency cannot match currency, %s.",
BTC)
}
if !LTC.IsDefaultCryptocurrency() {
t.Errorf("Test Failed. TestIsDefaultCryptocurrency cannot match currency, %s.",
t.Errorf("TestIsDefaultCryptocurrency cannot match currency, %s.",
LTC)
}
if AUD.IsDefaultCryptocurrency() {
t.Errorf("Test Failed. TestIsDefaultCryptocurrency function return is incorrect with, %s.",
t.Errorf("TestIsDefaultCryptocurrency function return is incorrect with, %s.",
AUD)
}
}
@@ -384,30 +458,30 @@ func TestIsDefaultCryptocurrency(t *testing.T) {
func TestIsFiatCurrency(t *testing.T) {
if !USD.IsFiatCurrency() {
t.Errorf(
"Test Failed. TestIsFiatCurrency cannot match currency, %s.", USD)
"TestIsFiatCurrency cannot match currency, %s.", USD)
}
if !CNY.IsFiatCurrency() {
t.Errorf(
"Test Failed. TestIsFiatCurrency cannot match currency, %s.", CNY)
"TestIsFiatCurrency cannot match currency, %s.", CNY)
}
if LINO.IsFiatCurrency() {
t.Errorf(
"Test Failed. TestIsFiatCurrency cannot match currency, %s.", LINO,
"TestIsFiatCurrency cannot match currency, %s.", LINO,
)
}
}
func TestIsCryptocurrency(t *testing.T) {
if !BTC.IsCryptocurrency() {
t.Errorf("Test Failed. TestIsFiatCurrency cannot match currency, %s.",
t.Errorf("TestIsFiatCurrency cannot match currency, %s.",
BTC)
}
if !LTC.IsCryptocurrency() {
t.Errorf("Test Failed. TestIsFiatCurrency cannot match currency, %s.",
t.Errorf("TestIsFiatCurrency cannot match currency, %s.",
LTC)
}
if AUD.IsCryptocurrency() {
t.Errorf("Test Failed. TestIsFiatCurrency cannot match currency, %s.",
t.Errorf("TestIsFiatCurrency cannot match currency, %s.",
AUD)
}
}
@@ -419,7 +493,7 @@ func TestItemString(t *testing.T) {
}
if newItem.String() != expected {
t.Errorf("Test Failed - Item String() error expected %s but received %s",
t.Errorf("Item String() error expected %s but received %s",
expected,
&newItem)
}

1655
currency/code_types.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -18,53 +18,6 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// Coinmarketcap account plan bitmasks, url and enpoint consts
const (
Basic uint8 = 1 << iota
Hobbyist
Startup
Standard
Professional
Enterprise
baseURL = "https://pro-api.coinmarketcap.com"
sandboxURL = "https://sandbox-api.coinmarketcap.com"
version = "/v1/"
endpointCryptocurrencyInfo = "cryptocurrency/info"
endpointCryptocurrencyMap = "cryptocurrency/map"
endpointCryptocurrencyHistoricalListings = "cryptocurrency/listings/historical"
endpointCryptocurrencyLatestListings = "cryptocurrency/listings/latest"
endpointCryptocurrencyMarketPairs = "cryptocurrency/market-pairs/latest"
endpointOHLCVHistorical = "cryptocurrency/ohlcv/historical"
endpointOHLCVLatest = "cryptocurrency/ohlcv/latest"
endpointGetMarketQuotesHistorical = "cryptocurrency/quotes/historical"
endpointGetMarketQuotesLatest = "cryptocurrency/quotes/latest"
endpointExchangeInfo = "exchange/info"
endpointExchangeMap = "exchange/map"
endpointExchangeMarketPairsLatest = "exchange/market-pairs/latest"
endpointExchangeMarketQuoteHistorical = "exchange/quotes/historical"
endpointExchangeMarketQuoteLatest = "exchange/quotes/latest"
endpointGlobalQuoteHistorical = "global-metrics/quotes/historical"
endpointGlobalQuoteLatest = "global-metrics/quotes/latest"
endpointPriceConversion = "tools/price-conversion"
authrate = 0
defaultTimeOut = time.Second * 15
)
// Coinmarketcap is the overarching type across this package
type Coinmarketcap struct {
Verbose bool
Enabled bool
Name string
APIkey string
APIUrl string
APIVersion string
Plan uint8
Requester *request.Requester
}
// SetDefaults sets default values for the exchange
func (c *Coinmarketcap) SetDefaults() {
c.Name = "CoinMarketCap"

View File

@@ -58,32 +58,32 @@ func TestCheckAccountPlan(t *testing.T) {
if areAPICredtionalsSet(Basic) {
err := c.CheckAccountPlan(Enterprise)
if err == nil {
t.Error("Test Failed - CheckAccountPlan() error cannot be nil")
t.Error("CheckAccountPlan() error cannot be nil")
}
err = c.CheckAccountPlan(Professional)
if err == nil {
t.Error("Test Failed - CheckAccountPlan() error cannot be nil")
t.Error("CheckAccountPlan() error cannot be nil")
}
err = c.CheckAccountPlan(Standard)
if err == nil {
t.Error("Test Failed - CheckAccountPlan() error cannot be nil")
t.Error("CheckAccountPlan() error cannot be nil")
}
err = c.CheckAccountPlan(Hobbyist)
if err == nil {
t.Error("Test Failed - CheckAccountPlan() error cannot be nil")
t.Error("CheckAccountPlan() error cannot be nil")
}
err = c.CheckAccountPlan(Startup)
if err == nil {
t.Error("Test Failed - CheckAccountPlan() error cannot be nil")
t.Error("CheckAccountPlan() error cannot be nil")
}
err = c.CheckAccountPlan(Basic)
if err != nil {
t.Error("Test Failed - CheckAccountPlan() error", err)
t.Error("CheckAccountPlan() error", err)
}
}
}
@@ -94,11 +94,11 @@ func TestGetCryptocurrencyInfo(t *testing.T) {
_, err := c.GetCryptocurrencyInfo(1)
if areAPICredtionalsSet(Basic) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyInfo() error", err)
t.Error("GetCryptocurrencyInfo() error", err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyInfo() error cannot be nil")
t.Error("GetCryptocurrencyInfo() error cannot be nil")
}
}
}
@@ -109,11 +109,11 @@ func TestGetCryptocurrencyIDMap(t *testing.T) {
_, err := c.GetCryptocurrencyIDMap()
if areAPICredtionalsSet(Basic) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyIDMap() error", err)
t.Error("GetCryptocurrencyIDMap() error", err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyIDMap() error cannot be nil")
t.Error("GetCryptocurrencyIDMap() error cannot be nil")
}
}
}
@@ -123,7 +123,7 @@ func TestGetCryptocurrencyHistoricalListings(t *testing.T) {
TestSetup(t)
_, err := c.GetCryptocurrencyHistoricalListings()
if err == nil {
t.Error("Test Failed - GetCryptocurrencyHistoricalListings() error cannot be nil")
t.Error("GetCryptocurrencyHistoricalListings() error cannot be nil")
}
}
@@ -133,11 +133,11 @@ func TestGetCryptocurrencyLatestListing(t *testing.T) {
_, err := c.GetCryptocurrencyLatestListing(0, 0)
if areAPICredtionalsSet(Basic) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyLatestListing() error", err)
t.Error("GetCryptocurrencyLatestListing() error", err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyLatestListing() error cannot be nil")
t.Error("GetCryptocurrencyLatestListing() error cannot be nil")
}
}
}
@@ -148,12 +148,12 @@ func TestGetCryptocurrencyLatestMarketPairs(t *testing.T) {
_, err := c.GetCryptocurrencyLatestMarketPairs(1, 0, 0)
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyLatestMarketPairs() error",
t.Error("GetCryptocurrencyLatestMarketPairs() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyLatestMarketPairs() error cannot be nil")
t.Error("GetCryptocurrencyLatestMarketPairs() error cannot be nil")
}
}
}
@@ -164,12 +164,12 @@ func TestGetCryptocurrencyOHLCHistorical(t *testing.T) {
_, err := c.GetCryptocurrencyOHLCHistorical(1, time.Now(), time.Now())
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyOHLCHistorical() error",
t.Error("GetCryptocurrencyOHLCHistorical() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyOHLCHistorical() error cannot be nil")
t.Error("GetCryptocurrencyOHLCHistorical() error cannot be nil")
}
}
}
@@ -180,12 +180,12 @@ func TestGetCryptocurrencyOHLCLatest(t *testing.T) {
_, err := c.GetCryptocurrencyOHLCLatest(1)
if areAPICredtionalsSet(Startup) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyOHLCLatest() error",
t.Error("GetCryptocurrencyOHLCLatest() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyOHLCLatest() error cannot be nil")
t.Error("GetCryptocurrencyOHLCLatest() error cannot be nil")
}
}
}
@@ -196,12 +196,12 @@ func TestGetCryptocurrencyLatestQuotes(t *testing.T) {
_, err := c.GetCryptocurrencyLatestQuotes(1)
if areAPICredtionalsSet(Basic) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyLatestQuotes() error",
t.Error("GetCryptocurrencyLatestQuotes() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyLatestQuotes() error cannot be nil")
t.Error("GetCryptocurrencyLatestQuotes() error cannot be nil")
}
}
}
@@ -212,12 +212,12 @@ func TestGetCryptocurrencyHistoricalQuotes(t *testing.T) {
_, err := c.GetCryptocurrencyHistoricalQuotes(1, time.Now(), time.Now())
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetCryptocurrencyHistoricalQuotes() error",
t.Error("GetCryptocurrencyHistoricalQuotes() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetCryptocurrencyHistoricalQuotes() error cannot be nil")
t.Error("GetCryptocurrencyHistoricalQuotes() error cannot be nil")
}
}
}
@@ -228,12 +228,12 @@ func TestGetExchangeInfo(t *testing.T) {
_, err := c.GetExchangeInfo(1)
if areAPICredtionalsSet(Startup) {
if err != nil {
t.Error("Test Failed - GetExchangeInfo() error",
t.Error("GetExchangeInfo() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetExchangeInfo() error cannot be nil")
t.Error("GetExchangeInfo() error cannot be nil")
}
}
}
@@ -244,12 +244,12 @@ func TestGetExchangeMap(t *testing.T) {
_, err := c.GetExchangeMap(0, 0)
if areAPICredtionalsSet(Startup) {
if err != nil {
t.Error("Test Failed - GetExchangeMap() error",
t.Error("GetExchangeMap() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetExchangeMap() error cannot be nil")
t.Error("GetExchangeMap() error cannot be nil")
}
}
}
@@ -260,7 +260,7 @@ func TestGetExchangeHistoricalListings(t *testing.T) {
_, err := c.GetExchangeHistoricalListings()
if err == nil {
// TODO: update this once the feature above is implemented
t.Error("Test Failed - GetExchangeHistoricalListings() error cannot be nil")
t.Error("GetExchangeHistoricalListings() error cannot be nil")
}
}
@@ -270,7 +270,7 @@ func TestGetExchangeLatestListings(t *testing.T) {
_, err := c.GetExchangeLatestListings()
if err == nil {
// TODO: update this once the feature above is implemented
t.Error("Test Failed - GetExchangeHistoricalListings() error cannot be nil")
t.Error("GetExchangeHistoricalListings() error cannot be nil")
}
}
@@ -280,12 +280,12 @@ func TestGetExchangeLatestMarketPairs(t *testing.T) {
_, err := c.GetExchangeLatestMarketPairs(1, 0, 0)
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetExchangeLatestMarketPairs() error",
t.Error("GetExchangeLatestMarketPairs() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetExchangeLatestMarketPairs() error cannot be nil")
t.Error("GetExchangeLatestMarketPairs() error cannot be nil")
}
}
}
@@ -296,12 +296,12 @@ func TestGetExchangeLatestQuotes(t *testing.T) {
_, err := c.GetExchangeLatestQuotes(1)
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetExchangeLatestQuotes() error",
t.Error("GetExchangeLatestQuotes() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetExchangeLatestQuotes() error cannot be nil")
t.Error("GetExchangeLatestQuotes() error cannot be nil")
}
}
}
@@ -312,12 +312,12 @@ func TestGetExchangeHistoricalQuotes(t *testing.T) {
_, err := c.GetExchangeHistoricalQuotes(1, time.Now(), time.Now())
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetExchangeHistoricalQuotes() error",
t.Error("GetExchangeHistoricalQuotes() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetExchangeHistoricalQuotes() error cannot be nil")
t.Error("GetExchangeHistoricalQuotes() error cannot be nil")
}
}
}
@@ -328,12 +328,12 @@ func TestGetGlobalMeticLatestQuotes(t *testing.T) {
_, err := c.GetGlobalMeticLatestQuotes()
if areAPICredtionalsSet(Basic) {
if err != nil {
t.Error("Test Failed - GetGlobalMeticLatestQuotes() error",
t.Error("GetGlobalMeticLatestQuotes() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetGlobalMeticLatestQuotes() error cannot be nil")
t.Error("GetGlobalMeticLatestQuotes() error cannot be nil")
}
}
}
@@ -344,12 +344,12 @@ func TestGetGlobalMeticHistoricalQuotes(t *testing.T) {
_, err := c.GetGlobalMeticHistoricalQuotes(time.Now(), time.Now())
if areAPICredtionalsSet(Standard) {
if err != nil {
t.Error("Test Failed - GetGlobalMeticHistoricalQuotes() error",
t.Error("GetGlobalMeticHistoricalQuotes() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetGlobalMeticHistoricalQuotes() error cannot be nil")
t.Error("GetGlobalMeticHistoricalQuotes() error cannot be nil")
}
}
}
@@ -360,12 +360,12 @@ func TestGetPriceConversion(t *testing.T) {
_, err := c.GetPriceConversion(0, 1, time.Now())
if areAPICredtionalsSet(Hobbyist) {
if err != nil {
t.Error("Test Failed - GetPriceConversion() error",
t.Error("GetPriceConversion() error",
err)
}
} else {
if err == nil {
t.Error("Test Failed - GetPriceConversion() error cannot be nil")
t.Error("GetPriceConversion() error cannot be nil")
}
}
}
@@ -375,38 +375,38 @@ func TestSetAccountPlan(t *testing.T) {
for _, plan := range accPlans {
err := c.SetAccountPlan(plan)
if err != nil {
t.Error("Test Failed - SetAccountPlan() error", err)
t.Error("SetAccountPlan() error", err)
}
switch plan {
case "basic":
if c.Plan != Basic {
t.Error("Test Failed - SetAccountPlan() error basic plan not set correctly")
t.Error("SetAccountPlan() error basic plan not set correctly")
}
case "startup":
if c.Plan != Startup {
t.Error("Test Failed - SetAccountPlan() error startup plan not set correctly")
t.Error("SetAccountPlan() error startup plan not set correctly")
}
case "hobbyist":
if c.Plan != Hobbyist {
t.Error("Test Failed - SetAccountPlan() error hobbyist plan not set correctly")
t.Error("SetAccountPlan() error hobbyist plan not set correctly")
}
case "standard":
if c.Plan != Standard {
t.Error("Test Failed - SetAccountPlan() error standard plan not set correctly")
t.Error("SetAccountPlan() error standard plan not set correctly")
}
case "professional":
if c.Plan != Professional {
t.Error("Test Failed - SetAccountPlan() error professional plan not set correctly")
t.Error("SetAccountPlan() error professional plan not set correctly")
}
case "enterprise":
if c.Plan != Enterprise {
t.Error("Test Failed - SetAccountPlan() error enterprise plan not set correctly")
t.Error("SetAccountPlan() error enterprise plan not set correctly")
}
}
}
if err := c.SetAccountPlan("bra"); err == nil {
t.Error("Test Failed - SetAccountPlan() error cannot be nil")
t.Error("SetAccountPlan() error cannot be nil")
}
}

View File

@@ -1,6 +1,57 @@
package coinmarketcap
import "time"
import (
"time"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// Coinmarketcap account plan bitmasks, url and enpoint consts
const (
Basic uint8 = 1 << iota
Hobbyist
Startup
Standard
Professional
Enterprise
baseURL = "https://pro-api.coinmarketcap.com"
sandboxURL = "https://sandbox-api.coinmarketcap.com"
version = "/v1/"
endpointCryptocurrencyInfo = "cryptocurrency/info"
endpointCryptocurrencyMap = "cryptocurrency/map"
endpointCryptocurrencyHistoricalListings = "cryptocurrency/listings/historical"
endpointCryptocurrencyLatestListings = "cryptocurrency/listings/latest"
endpointCryptocurrencyMarketPairs = "cryptocurrency/market-pairs/latest"
endpointOHLCVHistorical = "cryptocurrency/ohlcv/historical"
endpointOHLCVLatest = "cryptocurrency/ohlcv/latest"
endpointGetMarketQuotesHistorical = "cryptocurrency/quotes/historical"
endpointGetMarketQuotesLatest = "cryptocurrency/quotes/latest"
endpointExchangeInfo = "exchange/info"
endpointExchangeMap = "exchange/map"
endpointExchangeMarketPairsLatest = "exchange/market-pairs/latest"
endpointExchangeMarketQuoteHistorical = "exchange/quotes/historical"
endpointExchangeMarketQuoteLatest = "exchange/quotes/latest"
endpointGlobalQuoteHistorical = "global-metrics/quotes/historical"
endpointGlobalQuoteLatest = "global-metrics/quotes/latest"
endpointPriceConversion = "tools/price-conversion"
authrate = 0
defaultTimeOut = time.Second * 15
)
// Coinmarketcap is the overarching type across this package
type Coinmarketcap struct {
Verbose bool
Enabled bool
Name string
APIkey string
APIUrl string
APIVersion string
Plan uint8
Requester *request.Requester
}
// Settings defines the current settings from configuration file
type Settings struct {

View File

@@ -254,11 +254,6 @@ func (c *ConversionRates) GetFullRates() Conversions {
// Conversions define a list of conversion data
type Conversions []Conversion
// Slice exposes the underlying Conversion slice type
func (c Conversions) Slice() []Conversion {
return c
}
// NewConversionFromString splits a string from a foreign exchange provider
func NewConversionFromString(p string) (Conversion, error) {
return NewConversionFromStrings(p[:3], p[3:])
@@ -302,7 +297,7 @@ func (c Conversion) String() string {
return c.From.String() + c.To.String()
}
// GetRate returns system rate if availabled
// GetRate returns system rate if available
func (c Conversion) GetRate() (float64, error) {
c.mtx.Lock()
defer c.mtx.Unlock()

View File

@@ -1,6 +1,7 @@
package currency
import (
"fmt"
"strings"
"testing"
)
@@ -9,10 +10,10 @@ func TestNewConversionFromString(t *testing.T) {
expected := "AUDUSD"
conv, err := NewConversionFromString(expected)
if err != nil {
t.Error("Test Failed - NewConversionFromString() error", err)
t.Error(err)
}
if conv.String() != expected {
t.Errorf("Test Failed - NewConversion() error expected %s but received %s",
t.Errorf("NewConversion() error expected %s but received %s",
expected,
conv)
}
@@ -20,10 +21,10 @@ func TestNewConversionFromString(t *testing.T) {
newexpected := strings.ToLower(expected)
conv, err = NewConversionFromString(newexpected)
if err != nil {
t.Error("Test Failed - NewConversionFromString() error", err)
t.Error(err)
}
if conv.String() != newexpected {
t.Errorf("Test Failed - NewConversion() error expected %s but received %s",
t.Errorf("NewConversion() error expected %s but received %s",
newexpected,
conv)
}
@@ -36,11 +37,11 @@ func TestNewConversionFromStrings(t *testing.T) {
conv, err := NewConversionFromStrings(from, to)
if err != nil {
t.Error("Test Failed - NewConversionFromString() error", err)
t.Error(err)
}
if conv.String() != expected {
t.Errorf("Test Failed - NewConversion() error expected %s but received %s",
t.Errorf("NewConversion() error expected %s but received %s",
expected,
conv)
}
@@ -53,11 +54,11 @@ func TestNewConversion(t *testing.T) {
conv, err := NewConversion(from, to)
if err != nil {
t.Error("Test Failed - NewConversionFromCode() error", err)
t.Error(err)
}
if conv.String() != expected {
t.Errorf("Test Failed - NewConversion() error expected %s but received %s",
t.Errorf("NewConversion() error expected %s but received %s",
expected,
conv)
}
@@ -69,18 +70,18 @@ func TestConversionIsInvalid(t *testing.T) {
conv, err := NewConversion(from, to)
if err != nil {
t.Fatal("Test Failed - NewConversion() error", err)
t.Fatal(err)
}
if conv.IsInvalid() {
t.Errorf("Test Failed - IsInvalid() error expected false but received %v",
t.Errorf("IsInvalid() error expected false but received %v",
conv.IsInvalid())
}
to = AUD
conv, err = NewConversion(from, to)
if err == nil {
t.Fatal("Test Failed - NewConversion() error", err)
t.Error("Expected error")
}
}
@@ -90,18 +91,18 @@ func TestConversionIsFiatPair(t *testing.T) {
conv, err := NewConversion(from, to)
if err != nil {
t.Fatal("Test Failed - NewConversion() error", err)
t.Fatal(err)
}
if !conv.IsFiat() {
t.Errorf("Test Failed - IsFiatPair() error expected true but received %v",
t.Errorf("IsFiatPair() error expected true but received %v",
conv.IsFiat())
}
to = LTC
conv, err = NewConversion(from, to)
if err == nil {
t.Fatal("Test Failed - NewConversion() error", err)
t.Error("Expected error")
}
}
@@ -109,7 +110,7 @@ func TestConversionsRatesSystem(t *testing.T) {
var SuperDuperConversionSystem ConversionRates
if SuperDuperConversionSystem.HasData() {
t.Fatalf("Test Failed - HasData() error expected false but received %v",
t.Fatalf("HasData() error expected false but received %v",
SuperDuperConversionSystem.HasData())
}
@@ -141,16 +142,16 @@ func TestConversionsRatesSystem(t *testing.T) {
err := SuperDuperConversionSystem.Update(testmap)
if err != nil {
t.Fatal("Test Failed - Update() error", err)
t.Fatal(err)
}
err = SuperDuperConversionSystem.Update(nil)
if err == nil {
t.Fatal("Test Failed - Update() error cannot be nil")
t.Fatal("Update() error cannot be nil")
}
if !SuperDuperConversionSystem.HasData() {
t.Fatalf("Test Failed - HasData() error expected true but received %v",
t.Fatalf("HasData() error expected true but received %v",
SuperDuperConversionSystem.HasData())
}
@@ -161,7 +162,7 @@ func TestConversionsRatesSystem(t *testing.T) {
r := *p * 1000
expectedRate := 1396.9317581
if r != expectedRate {
t.Errorf("Test Failed - Convert() error expected %.13f but received %.13f",
t.Errorf("Convert() error expected %.13f but received %.13f",
expectedRate,
r)
}
@@ -169,8 +170,78 @@ func TestConversionsRatesSystem(t *testing.T) {
inverseR := *pi * expectedRate
expectedInverseRate := float64(1000)
if inverseR != expectedInverseRate {
t.Errorf("Test Failed - Convert() error expected %.13f but received %.13f",
t.Errorf("Convert() error expected %.13f but received %.13f",
expectedInverseRate,
inverseR)
}
}
func TestGetRate(t *testing.T) {
from := NewCode("AUD")
to := NewCode("USD")
c, err := NewConversion(from, to)
if err != nil {
t.Error(err)
}
rate, err := c.GetRate()
if err != nil {
t.Error(err)
}
if rate == 0 {
t.Error("Rate not set")
}
inv, err := c.GetInversionRate()
if err != nil {
t.Error(err)
}
if inv == 0 {
t.Error("Inverted rate not set")
}
conv, err := c.Convert(1)
if err != nil {
t.Error(err)
}
if rate != conv {
t.Errorf("Incorrect rate %v %v", rate, conv)
}
invConv, err := c.ConvertInverse(1)
if err != nil {
t.Error(err)
}
if inv != invConv {
t.Errorf("Incorrect rate %v %v", conv, invConv)
}
var convs ConversionRates
var convRate float64
_, err = convs.GetRate(BTC, USDT)
if err == nil {
t.Errorf("Expected %s", fmt.Errorf("rate not found for from %s to %s conversion",
BTC,
USD))
}
convRate, err = convs.GetRate(USDT, USD)
if err != nil {
t.Error(err)
}
if convRate != 1 {
t.Errorf("Expected rate to be 1")
}
convRate, err = convs.GetRate(RUR, RUB)
if err != nil {
t.Error(err)
}
if convRate != 1 {
t.Errorf("Expected rate to be 1")
}
convRate, err = convs.GetRate(RUB, RUR)
if err != nil {
t.Error(err)
}
if convRate != 1 {
t.Errorf("Expected rate to be 1")
}
}

View File

@@ -88,11 +88,6 @@ func (c Currencies) Match(other Currencies) bool {
return true
}
// Slice exposes the underlying type
func (c Currencies) Slice() []Code {
return c
}
// HasData checks to see if Currencies type has actual currencies
func (c Currencies) HasData() bool {
return len(c) != 0

View File

@@ -11,21 +11,21 @@ func TestCurrenciesUnmarshalJSON(t *testing.T) {
expected := "btc,usd,ltc,bro,things"
encoded, err := common.JSONEncode(expected)
if err != nil {
t.Fatal("Test Failed - Currencies UnmarshalJSON() error", err)
t.Fatal("Currencies UnmarshalJSON() error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Currencies UnmarshalJSON() error", err)
t.Fatal("Currencies UnmarshalJSON() error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Currencies UnmarshalJSON() error", err)
t.Fatal("Currencies UnmarshalJSON() error", err)
}
if unmarshalHere.Join() != expected {
t.Errorf("Test Failed - Currencies UnmarshalJSON() error expected %s but received %s",
t.Errorf("Currencies UnmarshalJSON() error expected %s but received %s",
expected, unmarshalHere.Join())
}
}
@@ -39,12 +39,12 @@ func TestCurrenciesMarshalJSON(t *testing.T) {
encoded, err := common.JSONEncode(quickStruct)
if err != nil {
t.Fatal("Test Failed - Currencies MarshalJSON() error", err)
t.Fatal("Currencies MarshalJSON() error", err)
}
expected := `{"amazingCurrencies":"btc,usd,ltc,bro,things"}`
if string(encoded) != expected {
t.Errorf("Test Failed - Currencies MarshalJSON() error expected %s but received %s",
t.Errorf("Currencies MarshalJSON() error expected %s but received %s",
expected, string(encoded))
}
}

View File

@@ -7,12 +7,12 @@ import (
func TestGetDefaultExchangeRates(t *testing.T) {
rates, err := GetDefaultExchangeRates()
if err != nil {
t.Error("Test failed - GetDefaultExchangeRates() err", err)
t.Error("GetDefaultExchangeRates() err", err)
}
for _, val := range rates {
if !val.IsFiat() {
t.Errorf("Test failed - GetDefaultExchangeRates() %s is not fiat pair",
t.Errorf("GetDefaultExchangeRates() %s is not fiat pair",
val)
}
}
@@ -21,12 +21,12 @@ func TestGetDefaultExchangeRates(t *testing.T) {
func TestGetExchangeRates(t *testing.T) {
rates, err := GetExchangeRates()
if err != nil {
t.Error("Test failed - GetExchangeRates() err", err)
t.Error("GetExchangeRates() err", err)
}
for _, val := range rates {
if !val.IsFiat() {
t.Errorf("Test failed - GetExchangeRates() %s is not fiat pair",
t.Errorf("GetExchangeRates() %s is not fiat pair",
val)
}
}
@@ -35,23 +35,23 @@ func TestGetExchangeRates(t *testing.T) {
func TestUpdateBaseCurrency(t *testing.T) {
err := UpdateBaseCurrency(AUD)
if err != nil {
t.Error("Test failed - UpdateBaseCurrency() err", err)
t.Error("UpdateBaseCurrency() err", err)
}
err = UpdateBaseCurrency(LTC)
if err == nil {
t.Error("Test failed - UpdateBaseCurrency() cannot be nil")
t.Error("UpdateBaseCurrency() error cannot be nil")
}
if GetBaseCurrency() != AUD {
t.Errorf("Test failed - GetBaseCurrency() expected %s but received %s",
t.Errorf("GetBaseCurrency() expected %s but received %s",
AUD, GetBaseCurrency())
}
}
func TestGetDefaultBaseCurrency(t *testing.T) {
if GetDefaultBaseCurrency() != USD {
t.Errorf("Test failed - GetDefaultBaseCurrency() expected %s but received %s",
t.Errorf("GetDefaultBaseCurrency() expected %s but received %s",
USD, GetDefaultBaseCurrency())
}
}
@@ -59,7 +59,7 @@ func TestGetDefaultBaseCurrency(t *testing.T) {
func TestGetDefaulCryptoCurrencies(t *testing.T) {
expected := Currencies{BTC, LTC, ETH, DOGE, DASH, XRP, XMR}
if !GetDefaultCryptocurrencies().Match(expected) {
t.Errorf("Test failed - GetDefaultCryptocurrencies() expected %s but received %s",
t.Errorf("GetDefaultCryptocurrencies() expected %s but received %s",
expected, GetDefaultCryptocurrencies())
}
}
@@ -67,7 +67,7 @@ func TestGetDefaulCryptoCurrencies(t *testing.T) {
func TestGetDefaultFiatCurrencies(t *testing.T) {
expected := Currencies{USD, AUD, EUR, CNY}
if !GetDefaultFiatCurrencies().Match(expected) {
t.Errorf("Test failed - GetDefaultFiatCurrencies() expected %s but received %s",
t.Errorf("GetDefaultFiatCurrencies() expected %s but received %s",
expected, GetDefaultFiatCurrencies())
}
}
@@ -77,14 +77,14 @@ func TestUpdateCurrencies(t *testing.T) {
UpdateCurrencies(fiat, false)
rFiat := GetFiatCurrencies()
if !rFiat.Contains(HKN) || !rFiat.Contains(JPY) {
t.Error("Test failed - UpdateCurrencies() currencies did not update")
t.Error("UpdateCurrencies() currencies did not update")
}
crypto := Currencies{ZAR, ZCAD, B2}
UpdateCurrencies(crypto, true)
rCrypto := GetCryptocurrencies()
if !rCrypto.Contains(ZAR) || !rCrypto.Contains(ZCAD) || !rCrypto.Contains(B2) {
t.Error("Test failed - UpdateCurrencies() currencies did not update")
t.Error("UpdateCurrencies() currencies did not update")
}
}
@@ -100,7 +100,7 @@ func TestConvertCurrency(t *testing.T) {
}
if r != 100 {
t.Errorf("Test Failed - ConvertCurrency error, incorrect rate return %2.f but received %2.f",
t.Errorf("ConvertCurrency error, incorrect rate return %2.f but received %2.f",
100.00, r)
}

View File

@@ -4,6 +4,21 @@ import (
"time"
)
// GetName returns name of provider
func (b *Base) GetName() string {
return b.Name
}
// IsEnabled returns true if enabled
func (b *Base) IsEnabled() bool {
return b.Enabled
}
// IsPrimaryProvider returns true if primary provider
func (b *Base) IsPrimaryProvider() bool {
return b.PrimaryProvider
}
// DefaultTimeOut is the default timeout for foreign exchange providers
const DefaultTimeOut = time.Second * 15
@@ -22,18 +37,3 @@ type Settings struct {
type Base struct {
Settings `json:"settings"`
}
// GetName returns name of provider
func (b *Base) GetName() string {
return b.Name
}
// IsEnabled returns true if enabled
func (b *Base) IsEnabled() bool {
return b.Enabled
}
// IsPrimaryProvider returns true if primary provider
func (b *Base) IsPrimaryProvider() bool {
return b.PrimaryProvider
}

View File

@@ -14,29 +14,6 @@ import (
log "github.com/thrasher-corp/gocryptotrader/logger"
)
// const declarations consist of endpoints
const (
APIEndpointURL = "https://currencyconverterapi.com/api/"
APIEndpointFreeURL = "https://free.currencyconverterapi.com/api/"
APIEndpointVersion = "v5"
APIEndpointConvert = "convert"
APIEndpointCurrencies = "currencies"
APIEndpointCountries = "countries"
APIEndpointUsage = "usage"
defaultAPIKey = "Key"
authRate = 0
unAuthRate = 0
)
// CurrencyConverter stores the struct for the CurrencyConverter API
type CurrencyConverter struct {
base.Base
Requester *request.Requester
}
// Setup sets appropriate values for CurrencyLayer
func (c *CurrencyConverter) Setup(config base.Settings) error {
c.Name = config.Name

View File

@@ -65,7 +65,7 @@ func TestConvertMany(t *testing.T) {
currencies = []string{"USD_AUD", "USD_EUR", "USD_GBP"}
_, err = c.ConvertMany(currencies)
if err == nil {
t.Fatal("non error on supplying 3 or more currencies using the free API")
t.Fatal("Expected error from on supplying 3 or more currencies using the free API")
}
}

View File

@@ -1,5 +1,33 @@
package currencyconverter
import (
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// const declarations consist of endpoints
const (
APIEndpointURL = "https://currencyconverterapi.com/api/"
APIEndpointFreeURL = "https://free.currencyconverterapi.com/api/"
APIEndpointVersion = "v5"
APIEndpointConvert = "convert"
APIEndpointCurrencies = "currencies"
APIEndpointCountries = "countries"
APIEndpointUsage = "usage"
defaultAPIKey = "Key"
authRate = 0
unAuthRate = 0
)
// CurrencyConverter stores the struct for the CurrencyConverter API
type CurrencyConverter struct {
base.Base
Requester *request.Requester
}
// Error stores the error message
type Error struct {
Status int `json:"status"`

View File

@@ -26,34 +26,6 @@ import (
log "github.com/thrasher-corp/gocryptotrader/logger"
)
// const declarations consist of endpoints and APIKey privileges
const (
AccountFree = iota
AccountBasic
AccountPro
AccountEnterprise
APIEndpointURL = "http://apilayer.net/api/"
APIEndpointURLSSL = "https://apilayer.net/api/"
APIEndpointList = "list"
APIEndpointLive = "live"
APIEndpointHistorical = "historical"
APIEndpointConversion = "convert"
APIEndpointTimeframe = "timeframe"
APIEndpointChange = "change"
authRate = 0
unAuthRate = 0
)
// CurrencyLayer is a foreign exchange rate provider at
// https://currencylayer.com NOTE default base currency is USD when using a free
// account. Has automatic upgrade to a SSL connection.
type CurrencyLayer struct {
base.Base
Requester *request.Requester
}
// Setup sets appropriate values for CurrencyLayer
func (c *CurrencyLayer) Setup(config base.Settings) error {
if config.APIKeyLvl < 0 || config.APIKeyLvl > 3 {

View File

@@ -48,7 +48,7 @@ func areAPIKeysSet() bool {
func TestGetRates(t *testing.T) {
err := setup()
if err != nil {
t.Skip("Test Failed - CurrencyLayer GetRates error", err)
t.Skip("CurrencyLayer GetRates error", err)
}
_, err = c.GetRates("USD", "AUD")
if areAPIKeysSet() && err != nil {
@@ -61,7 +61,7 @@ func TestGetRates(t *testing.T) {
func TestGetSupportedCurrencies(t *testing.T) {
err := setup()
if err != nil {
t.Fatal("Test Failed - CurrencyLayer GetSupportedCurrencies error", err)
t.Fatal("CurrencyLayer GetSupportedCurrencies error", err)
}
_, err = c.GetSupportedCurrencies()
if areAPIKeysSet() && err != nil {
@@ -74,7 +74,7 @@ func TestGetSupportedCurrencies(t *testing.T) {
func TestGetliveData(t *testing.T) {
err := setup()
if err != nil {
t.Fatal("Test Failed - CurrencyLayer GetliveData error", err)
t.Fatal("CurrencyLayer GetliveData error", err)
}
_, err = c.GetliveData("AUD", "USD")
if areAPIKeysSet() && err != nil {
@@ -87,7 +87,7 @@ func TestGetliveData(t *testing.T) {
func TestGetHistoricalData(t *testing.T) {
err := setup()
if err != nil {
t.Fatal("Test Failed - CurrencyLayer GetHistoricalData error", err)
t.Fatal("CurrencyLayer GetHistoricalData error", err)
}
_, err = c.GetHistoricalData("2016-12-15", []string{"AUD"}, "USD")
if areAPIKeysSet() && err != nil {
@@ -100,7 +100,7 @@ func TestGetHistoricalData(t *testing.T) {
func TestConvert(t *testing.T) {
err := setup()
if err != nil {
t.Fatal("Test Failed - CurrencyLayer Convert error", err)
t.Fatal("CurrencyLayer Convert error", err)
}
_, err = c.Convert("USD", "AUD", "", 1)
if areAPIKeysSet() && err != nil && c.APIKeyLvl >= AccountBasic {
@@ -113,7 +113,7 @@ func TestConvert(t *testing.T) {
func TestQueryTimeFrame(t *testing.T) {
err := setup()
if err != nil {
t.Fatal("Test Failed - CurrencyLayer QueryTimeFrame error", err)
t.Fatal("CurrencyLayer QueryTimeFrame error", err)
}
_, err = c.QueryTimeFrame("2010-12-0", "2010-12-5", "USD", []string{"AUD"})
if areAPIKeysSet() && err != nil && c.APIKeyLvl >= AccountPro {
@@ -126,7 +126,7 @@ func TestQueryTimeFrame(t *testing.T) {
func TestQueryCurrencyChange(t *testing.T) {
err := setup()
if err != nil {
t.Fatal("Test Failed - CurrencyLayer QueryCurrencyChange() error", err)
t.Fatal("CurrencyLayer QueryCurrencyChange() error", err)
}
_, err = c.QueryCurrencyChange("2010-12-0", "2010-12-5", "USD", []string{"AUD"})
if areAPIKeysSet() && err != nil && c.APIKeyLvl == AccountEnterprise {

View File

@@ -1,5 +1,38 @@
package currencylayer
import (
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// const declarations consist of endpoints and APIKey privileges
const (
AccountFree = iota
AccountBasic
AccountPro
AccountEnterprise
APIEndpointURL = "http://apilayer.net/api/"
APIEndpointURLSSL = "https://apilayer.net/api/"
APIEndpointList = "list"
APIEndpointLive = "live"
APIEndpointHistorical = "historical"
APIEndpointConversion = "convert"
APIEndpointTimeframe = "timeframe"
APIEndpointChange = "change"
authRate = 0
unAuthRate = 0
)
// CurrencyLayer is a foreign exchange rate provider at
// https://currencylayer.com NOTE default base currency is USD when using a free
// account. Has automatic upgrade to a SSL connection.
type CurrencyLayer struct {
base.Base
Requester *request.Requester
}
// Error Defines the response error if an error occurred
type Error struct {
Code int `json:"code"`

View File

@@ -14,24 +14,6 @@ import (
log "github.com/thrasher-corp/gocryptotrader/logger"
)
const (
exchangeRatesAPI = "https://api.exchangeratesapi.io"
exchangeRatesLatest = "latest"
exchangeRatesHistory = "history"
exchangeRatesSupportedCurrencies = "EUR,CHF,USD,BRL,ISK,PHP,KRW,BGN,MXN," +
"RON,CAD,SGD,NZD,THB,HKD,JPY,NOK,HRK,ILS,GBP,DKK,HUF,MYR,RUB,TRY,IDR," +
"ZAR,INR,AUD,CZK,SEK,CNY,PLN"
authRate = 0
unAuthRate = 0
)
// ExchangeRates stores the struct for the ExchangeRatesAPI API
type ExchangeRates struct {
base.Base
Requester *request.Requester
}
// Setup sets appropriate values for CurrencyLayer
func (e *ExchangeRates) Setup(config base.Settings) error {
e.Name = config.Name

View File

@@ -1,5 +1,28 @@
package exchangerates
import (
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
const (
exchangeRatesAPI = "https://api.exchangeratesapi.io"
exchangeRatesLatest = "latest"
exchangeRatesHistory = "history"
exchangeRatesSupportedCurrencies = "EUR,CHF,USD,BRL,ISK,PHP,KRW,BGN,MXN," +
"RON,CAD,SGD,NZD,THB,HKD,JPY,NOK,HRK,ILS,GBP,DKK,HUF,MYR,RUB,TRY,IDR," +
"ZAR,INR,AUD,CZK,SEK,CNY,PLN"
authRate = 0
unAuthRate = 0
)
// ExchangeRates stores the struct for the ExchangeRatesAPI API
type ExchangeRates struct {
base.Base
Requester *request.Requester
}
// Rates holds the latest forex rates info
type Rates struct {
Base string `json:"base"`

View File

@@ -22,32 +22,6 @@ import (
log "github.com/thrasher-corp/gocryptotrader/logger"
)
const (
fixerAPIFree = iota
fixerAPIBasic
fixerAPIProfessional
fixerAPIProfessionalPlus
fixerAPIEnterprise
fixerAPI = "http://data.fixer.io/api/"
fixerAPISSL = "https://data.fixer.io/api/"
fixerAPILatest = "latest"
fixerAPIConvert = "convert"
fixerAPITimeSeries = "timeseries"
fixerAPIFluctuation = "fluctuation"
fixerSupportedCurrencies = "symbols"
authRate = 0
unAuthRate = 0
)
// Fixer is a foreign exchange rate provider at https://fixer.io/
// NOTE DEFAULT BASE CURRENCY IS EUR upgrade to basic to change
type Fixer struct {
base.Base
Requester *request.Requester
}
// Setup sets appropriate values for fixer object
func (f *Fixer) Setup(config base.Settings) error {
if config.APIKeyLvl < 0 || config.APIKeyLvl > 4 {

View File

@@ -22,7 +22,7 @@ func setup(t *testing.T) {
if !isSetup {
err := f.Setup(base.Settings{})
if err != nil {
t.Fatal("Test Failed - Setup error", err)
t.Fatal("Setup error", err)
}
isSetup = true
}
@@ -32,7 +32,7 @@ func TestGetRates(t *testing.T) {
setup(t)
_, err := f.GetRates("EUR", "AUD")
if err == nil {
t.Error("test failed - fixer GetRates() error", err)
t.Error("fixer GetRates() Expected error")
}
}
@@ -40,7 +40,7 @@ func TestGetLatestRates(t *testing.T) {
setup(t)
_, err := f.GetLatestRates("EUR", "AUD")
if err == nil {
t.Error("test failed - fixer GetLatestRates() error", err)
t.Error("fixer GetLatestRates() Expected error")
}
}
@@ -48,7 +48,7 @@ func TestGetHistoricalRates(t *testing.T) {
setup(t)
_, err := f.GetHistoricalRates("2013-12-24", "EUR", []string{"AUD,KRW"})
if err == nil {
t.Error("test failed - fixer GetHistoricalRates() error", err)
t.Error("fixer GetHistoricalRates() Expected error")
}
}
@@ -56,7 +56,7 @@ func TestConvertCurrency(t *testing.T) {
setup(t)
_, err := f.ConvertCurrency("AUD", "EUR", "", 1337)
if err == nil {
t.Error("test failed - fixer ConvertCurrency() error", err)
t.Error("fixer ConvertCurrency() Expected error")
}
}
@@ -64,7 +64,7 @@ func TestGetTimeSeriesData(t *testing.T) {
setup(t)
_, err := f.GetTimeSeriesData("2013-12-24", "2013-12-25", "EUR", []string{"AUD,KRW"})
if err == nil {
t.Error("test failed - fixer GetTimeSeriesData() error", err)
t.Error("fixer GetTimeSeriesData() Expected error")
}
}
@@ -72,6 +72,6 @@ func TestGetFluctuationData(t *testing.T) {
setup(t)
_, err := f.GetFluctuationData("2013-12-24", "2013-12-25", "EUR", []string{"AUD,KRW"})
if err == nil {
t.Error("test failed - fixer GetFluctuationData() error", err)
t.Error("fixer GetFluctuationData() Expected error")
}
}

View File

@@ -1,5 +1,36 @@
package fixer
import (
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
const (
fixerAPIFree = iota
fixerAPIBasic
fixerAPIProfessional
fixerAPIProfessionalPlus
fixerAPIEnterprise
fixerAPI = "http://data.fixer.io/api/"
fixerAPISSL = "https://data.fixer.io/api/"
fixerAPILatest = "latest"
fixerAPIConvert = "convert"
fixerAPITimeSeries = "timeseries"
fixerAPIFluctuation = "fluctuation"
fixerSupportedCurrencies = "symbols"
authRate = 0
unAuthRate = 0
)
// Fixer is a foreign exchange rate provider at https://fixer.io/
// NOTE DEFAULT BASE CURRENCY IS EUR upgrade to basic to change
type Fixer struct {
base.Base
Requester *request.Requester
}
// Rates contains the data fields for the currencies you have requested.
type Rates struct {
Success bool `json:"success"`

View File

@@ -13,13 +13,8 @@ import (
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/openexchangerates"
)
// ForexProviders is a foreign exchange handler type
type ForexProviders struct {
base.FXHandler
}
// GetAvailableForexProviders returns a list of supported forex providers
func GetAvailableForexProviders() []string {
// GetSupportedForexProviders returns a list of supported forex providers
func GetSupportedForexProviders() []string {
return []string{"CurrencyConverter",
"CurrencyLayer",
"ExchangeRates",
@@ -135,3 +130,8 @@ func StartFXService(fxProviders []base.Settings) (*ForexProviders, error) {
return handler, nil
}
// ForexProviders is a foreign exchange handler type
type ForexProviders struct {
base.FXHandler
}

View File

@@ -23,45 +23,6 @@ import (
log "github.com/thrasher-corp/gocryptotrader/logger"
)
// These consts contain endpoint information
const (
APIDeveloperAccess = iota
APIEnterpriseAccess
APIUnlimitedAccess
APIURL = "https://openexchangerates.org/api/"
APIEndpointLatest = "latest.json"
APIEndpointHistorical = "historical/%s.json"
APIEndpointCurrencies = "currencies.json"
APIEndpointTimeSeries = "time-series.json"
APIEndpointConvert = "convert/%s/%s/%s"
APIEndpointOHLC = "ohlc.json"
APIEndpointUsage = "usage.json"
oxrSupportedCurrencies = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD," +
"BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTC,BTN,BWP,BYN,BYR,BZD,CAD,CDF," +
"CHF,CLF,CLP,CNH,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EEK,EGP," +
"ERN,ETB,EUR,FJD,FKP,GBP,GEL,GGP,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK," +
"HTG,HUF,IDR,ILS,IMP,INR,IQD,IRR,ISK,JEP,JMD,JOD,JPY,KES,KGS,KHR,KMF," +
"KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT," +
"MOP,MRO,MRU,MTL,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR," +
"PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK," +
"SGD,SHP,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY," +
"TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XAG,XAU,XCD,XDR," +
"XOF,XPD,XPF,XPT,YER,ZAR,ZMK,ZMW"
authRate = 0
unAuthRate = 0
)
// OXR is a foreign exchange rate provider at https://openexchangerates.org/
// this is the overarching type across this package
// DOCs : https://docs.openexchangerates.org/docs
type OXR struct {
base.Base
Requester *request.Requester
}
// Setup sets values for the OXR object
func (o *OXR) Setup(config base.Settings) error {
if config.APIKeyLvl < 0 || config.APIKeyLvl > 2 {

View File

@@ -31,7 +31,7 @@ func TestGetRates(t *testing.T) {
}
_, err := o.GetRates("USD", "AUD")
if err == nil {
t.Error("test failed - GetRates() error", err)
t.Error("GetRates() Expected error")
}
}
@@ -41,7 +41,7 @@ func TestGetLatest(t *testing.T) {
}
_, err := o.GetLatest("USD", "AUD", false, false)
if err == nil {
t.Error("test failed - GetLatest() error", err)
t.Error("GetLatest() Expected error")
}
}
@@ -51,7 +51,7 @@ func TestGetHistoricalRates(t *testing.T) {
}
_, err := o.GetHistoricalRates("2017-12-01", "USD", []string{"CNH", "AUD", "ANG"}, false, false)
if err == nil {
t.Error("test failed - GetRates() error", err)
t.Error("GetRates() Expected error")
}
}
@@ -61,7 +61,7 @@ func TestGetCurrencies(t *testing.T) {
}
_, err := o.GetCurrencies(true, true, true)
if err != nil {
t.Error("test failed - GetCurrencies() error", err)
t.Error("GetCurrencies() error", err)
}
}
@@ -71,7 +71,7 @@ func TestGetTimeSeries(t *testing.T) {
}
_, err := o.GetTimeSeries("USD", "2017-12-01", "2017-12-02", []string{"CNH", "AUD", "ANG"}, false, false)
if err == nil {
t.Error("test failed - GetTimeSeries() error", err)
t.Error("GetTimeSeries() Expected error")
}
}
@@ -81,7 +81,7 @@ func TestConvertCurrency(t *testing.T) {
}
_, err := o.ConvertCurrency(1337, "USD", "AUD")
if err == nil {
t.Error("test failed - ConvertCurrency() error", err)
t.Error("ConvertCurrency() Expected error")
}
}
@@ -91,7 +91,7 @@ func TestGetOHLC(t *testing.T) {
}
_, err := o.GetOHLC("2017-07-17T08:30:00Z", "1m", "USD", []string{"AUD"}, false)
if err == nil {
t.Error("test failed - GetOHLC() error", err)
t.Error("GetOHLC() Expected error")
}
}
@@ -101,6 +101,6 @@ func TestGetUsageStats(t *testing.T) {
}
_, err := o.GetUsageStats(false)
if err == nil {
t.Error("test failed - GetUsageStats() error", err)
t.Error("GetUsageStats() Expected error")
}
}

View File

@@ -1,5 +1,49 @@
package openexchangerates
import (
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider/base"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
// These consts contain endpoint information
const (
APIDeveloperAccess = iota
APIEnterpriseAccess
APIUnlimitedAccess
APIURL = "https://openexchangerates.org/api/"
APIEndpointLatest = "latest.json"
APIEndpointHistorical = "historical/%s.json"
APIEndpointCurrencies = "currencies.json"
APIEndpointTimeSeries = "time-series.json"
APIEndpointConvert = "convert/%s/%s/%s"
APIEndpointOHLC = "ohlc.json"
APIEndpointUsage = "usage.json"
oxrSupportedCurrencies = "AED,AFN,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD," +
"BDT,BGN,BHD,BIF,BMD,BND,BOB,BRL,BSD,BTC,BTN,BWP,BYN,BYR,BZD,CAD,CDF," +
"CHF,CLF,CLP,CNH,CNY,COP,CRC,CUC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EEK,EGP," +
"ERN,ETB,EUR,FJD,FKP,GBP,GEL,GGP,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HRK," +
"HTG,HUF,IDR,ILS,IMP,INR,IQD,IRR,ISK,JEP,JMD,JOD,JPY,KES,KGS,KHR,KMF," +
"KPW,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LRD,LSL,LYD,MAD,MDL,MGA,MKD,MMK,MNT," +
"MOP,MRO,MRU,MTL,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR," +
"PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SDG,SEK," +
"SGD,SHP,SLL,SOS,SRD,SSP,STD,STN,SVC,SYP,SZL,THB,TJS,TMT,TND,TOP,TRY," +
"TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XAG,XAU,XCD,XDR," +
"XOF,XPD,XPF,XPT,YER,ZAR,ZMK,ZMW"
authRate = 0
unAuthRate = 0
)
// OXR is a foreign exchange rate provider at https://openexchangerates.org/
// this is the overarching type across this package
// DOCs : https://docs.openexchangerates.org/docs
type OXR struct {
base.Base
Requester *request.Requester
}
// Latest holds latest rate data
type Latest struct {
Disclaimer string `json:"disclaimer"`

View File

@@ -29,11 +29,11 @@ func TestGetAssetTypes(t *testing.T) {
a := p.GetAssetTypes()
if len(a) == 0 {
t.Errorf("Test failed. GetAssetTypes shouldn't be nil")
t.Errorf("GetAssetTypes shouldn't be nil")
}
if !a.Contains(asset.Spot) {
t.Errorf("Test failed. AssetTypeSpot should be in the assets list")
t.Errorf("AssetTypeSpot should be in the assets list")
}
}
@@ -41,11 +41,11 @@ func TestGet(t *testing.T) {
initTest()
if p.Get(asset.Spot) == nil {
t.Error("Test failed. Spot assets shouldn't be nil")
t.Error("Spot assets shouldn't be nil")
}
if p.Get(asset.Futures) != nil {
t.Error("Test Failed. Futures should be nil")
t.Error("Futures should be nil")
}
}
@@ -65,7 +65,7 @@ func TestStore(t *testing.T) {
)
if p.Get(asset.Futures) == nil {
t.Error("Test failed. Futures assets shouldn't be nil")
t.Error("Futures assets shouldn't be nil")
}
}
@@ -80,12 +80,12 @@ func TestDelete(t *testing.T) {
)
p.Delete(asset.UpsideProfitContract)
if p.Get(asset.Spot) == nil {
t.Error("Test failed. AssetTypeSpot should exist")
t.Error("AssetTypeSpot should exist")
}
p.Delete(asset.Spot)
if p.Get(asset.Spot) != nil {
t.Error("Test failed. Delete should have deleted AssetTypeSpot")
t.Error("Delete should have deleted AssetTypeSpot")
}
}

View File

@@ -87,13 +87,6 @@ func NewPairFromFormattedPairs(currencyPair string, pairs Pairs, pairFmt PairFor
return NewPairFromString(currencyPair)
}
// Pair holds currency pair information
type Pair struct {
Delimiter string `json:"delimiter"`
Base Code `json:"base"`
Quote Code `json:"quote"`
}
// String returns a currency pair string
func (p Pair) String() string {
return p.Base.String() + p.Delimiter + p.Quote.String()
@@ -203,3 +196,10 @@ func (p Pair) IsEmpty() bool {
func (p Pair) ContainsCurrency(c Code) bool {
return p.Base.Item == c.Item || p.Quote.Item == c.Item
}
// Pair holds currency pair information
type Pair struct {
Delimiter string `json:"delimiter"`
Base Code `json:"base"`
Quote Code `json:"quote"`
}

View File

@@ -17,7 +17,7 @@ func TestLower(t *testing.T) {
actual := pair.Lower()
expected := NewPairFromString(defaultPair).Lower()
if actual != expected {
t.Errorf("Test failed. Lower(): %s was not equal to expected value: %s",
t.Errorf("Lower(): %s was not equal to expected value: %s",
actual, expected)
}
}
@@ -28,7 +28,7 @@ func TestUpper(t *testing.T) {
actual := pair.Upper()
expected := NewPairFromString(defaultPair)
if actual != expected {
t.Errorf("Test failed. Upper(): %s was not equal to expected value: %s",
t.Errorf("Upper(): %s was not equal to expected value: %s",
actual, expected)
}
}
@@ -39,21 +39,21 @@ func TestPairUnmarshalJSON(t *testing.T) {
encoded, err := common.JSONEncode(configPair)
if err != nil {
t.Fatal("Test Failed - Pair UnmarshalJSON() error", err)
t.Fatal("Pair UnmarshalJSON() error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Pair UnmarshalJSON() error", err)
t.Fatal("Pair UnmarshalJSON() error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Pair UnmarshalJSON() error", err)
t.Fatal("Pair UnmarshalJSON() error", err)
}
if !unmarshalHere.Equal(configPair) {
t.Errorf("Test Failed - Pairs UnmarshalJSON() error expected %s but received %s",
t.Errorf("Pairs UnmarshalJSON() error expected %s but received %s",
configPair, unmarshalHere)
}
}
@@ -67,43 +67,43 @@ func TestPairMarshalJSON(t *testing.T) {
encoded, err := common.JSONEncode(quickstruct)
if err != nil {
t.Fatal("Test Failed - Pair MarshalJSON() error", err)
t.Fatal("Pair MarshalJSON() error", err)
}
expected := `{"superPair":"BTC-USD"}`
if string(encoded) != expected {
t.Errorf("Test Failed - Pair MarshalJSON() error expected %s but received %s",
t.Errorf("Pair MarshalJSON() error expected %s but received %s",
expected, string(encoded))
}
}
func TestIsCryptoPair(t *testing.T) {
if !NewPair(BTC, LTC).IsCryptoPair() {
t.Error("Test Failed. TestIsCryptoPair. Expected true result")
t.Error("TestIsCryptoPair. Expected true result")
}
if NewPair(BTC, USD).IsCryptoPair() {
t.Error("Test Failed. TestIsCryptoPair. Expected false result")
t.Error("TestIsCryptoPair. Expected false result")
}
}
func TestIsCryptoFiatPair(t *testing.T) {
if !NewPair(BTC, USD).IsCryptoFiatPair() {
t.Error("Test Failed. TestIsCryptoPair. Expected true result")
t.Error("TestIsCryptoPair. Expected true result")
}
if NewPair(BTC, LTC).IsCryptoFiatPair() {
t.Error("Test Failed. TestIsCryptoPair. Expected false result")
t.Error("TestIsCryptoPair. Expected false result")
}
}
func TestIsFiatPair(t *testing.T) {
if !NewPair(AUD, USD).IsFiatPair() {
t.Error("Test Failed. TestIsFiatPair. Expected true result")
t.Error("TestIsFiatPair. Expected true result")
}
if NewPair(BTC, AUD).IsFiatPair() {
t.Error("Test Failed. TestIsFiatPair. Expected false result")
t.Error("TestIsFiatPair. Expected false result")
}
}
@@ -113,7 +113,7 @@ func TestString(t *testing.T) {
actual := defaultPair
expected := pair.String()
if actual != expected {
t.Errorf("Test failed. String(): %s was not equal to expected value: %s",
t.Errorf("String(): %s was not equal to expected value: %s",
actual, expected)
}
}
@@ -125,7 +125,7 @@ func TestFirstCurrency(t *testing.T) {
expected := BTC
if actual != expected {
t.Errorf(
"Test failed. GetFirstCurrency(): %s was not equal to expected value: %s",
"GetFirstCurrency(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -138,7 +138,7 @@ func TestSecondCurrency(t *testing.T) {
expected := USD
if actual != expected {
t.Errorf(
"Test failed. GetSecondCurrency(): %s was not equal to expected value: %s",
"GetSecondCurrency(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -151,7 +151,7 @@ func TestPair(t *testing.T) {
expected := defaultPair
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -164,7 +164,7 @@ func TestDisplay(t *testing.T) {
expected := defaultPairWDelimiter
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -173,7 +173,7 @@ func TestDisplay(t *testing.T) {
expected = "btcusd"
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -182,7 +182,7 @@ func TestDisplay(t *testing.T) {
expected = "BTC~USD"
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -196,7 +196,7 @@ func TestEquall(t *testing.T) {
expected := true
if actual != expected {
t.Errorf(
"Test failed. Equal(): %v was not equal to expected value: %v",
"Equal(): %v was not equal to expected value: %v",
actual, expected,
)
}
@@ -206,7 +206,7 @@ func TestEquall(t *testing.T) {
expected = false
if actual != expected {
t.Errorf(
"Test failed. Equal(): %v was not equal to expected value: %v",
"Equal(): %v was not equal to expected value: %v",
actual, expected,
)
}
@@ -216,7 +216,7 @@ func TestEquall(t *testing.T) {
expected = false
if actual != expected {
t.Errorf(
"Test failed. Equal(): %v was not equal to expected value: %v",
"Equal(): %v was not equal to expected value: %v",
actual, expected,
)
}
@@ -230,7 +230,7 @@ func TestEqualIncludeReciprocal(t *testing.T) {
expected := true
if actual != expected {
t.Errorf(
"Test failed. Equal(): %v was not equal to expected value: %v",
"Equal(): %v was not equal to expected value: %v",
actual, expected,
)
}
@@ -240,7 +240,7 @@ func TestEqualIncludeReciprocal(t *testing.T) {
expected = false
if actual != expected {
t.Errorf(
"Test failed. Equal(): %v was not equal to expected value: %v",
"Equal(): %v was not equal to expected value: %v",
actual, expected,
)
}
@@ -250,7 +250,7 @@ func TestEqualIncludeReciprocal(t *testing.T) {
expected = true
if actual != expected {
t.Errorf(
"Test failed. Equal(): %v was not equal to expected value: %v",
"Equal(): %v was not equal to expected value: %v",
actual, expected,
)
}
@@ -263,7 +263,7 @@ func TestSwap(t *testing.T) {
expected := "USDBTC"
if actual != expected {
t.Errorf(
"Test failed. TestSwap: %s was not equal to expected value: %s",
"TestSwap: %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -273,12 +273,12 @@ func TestEmpty(t *testing.T) {
t.Parallel()
pair := NewPair(BTC, USD)
if pair.IsEmpty() {
t.Error("Test failed. Empty() returned true when the pair was initialised")
t.Error("Empty() returned true when the pair was initialised")
}
p := NewPair(NewCode(""), NewCode(""))
if !p.IsEmpty() {
t.Error("Test failed. Empty() returned true when the pair wasn't initialised")
t.Error("Empty() returned true when the pair wasn't initialised")
}
}
@@ -289,7 +289,7 @@ func TestNewPair(t *testing.T) {
expected := defaultPair
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -302,7 +302,7 @@ func TestNewPairWithDelimiter(t *testing.T) {
expected := "BTC-test-USD"
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -312,7 +312,7 @@ func TestNewPairWithDelimiter(t *testing.T) {
expected = defaultPair
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -325,7 +325,7 @@ func TestNewPairDelimiter(t *testing.T) {
expected := defaultPairWDelimiter
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -334,7 +334,7 @@ func TestNewPairDelimiter(t *testing.T) {
expected = "-"
if actual != expected {
t.Errorf(
"Test failed. Delmiter: %s was not equal to expected value: %s",
"Delmiter: %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -349,7 +349,7 @@ func TestNewPairFromIndex(t *testing.T) {
pair, err := NewPairFromIndex(currency, index)
if err != nil {
t.Error("test failed - NewPairFromIndex() error", err)
t.Error("NewPairFromIndex() error", err)
}
pair.Delimiter = "-"
@@ -358,7 +358,7 @@ func TestNewPairFromIndex(t *testing.T) {
expected := defaultPairWDelimiter
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -367,7 +367,7 @@ func TestNewPairFromIndex(t *testing.T) {
pair, err = NewPairFromIndex(currency, index)
if err != nil {
t.Error("test failed - NewPairFromIndex() error", err)
t.Error("NewPairFromIndex() error", err)
}
pair.Delimiter = "-"
@@ -376,7 +376,7 @@ func TestNewPairFromIndex(t *testing.T) {
expected = "DOGE-BTC"
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -390,7 +390,7 @@ func TestNewPairFromString(t *testing.T) {
expected := defaultPairWDelimiter
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -401,7 +401,7 @@ func TestNewPairFromString(t *testing.T) {
expected = defaultPair
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
"Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
@@ -416,18 +416,18 @@ func TestNewPairFromFormattedPairs(t *testing.T) {
p := NewPairFromFormattedPairs("BTCUSDT", pairs, PairFormat{Uppercase: true})
if p.String() != "BTC-USDT" {
t.Error("Test failed. TestNewPairFromFormattedPairs: Expected currency was not found")
t.Error("TestNewPairFromFormattedPairs: Expected currency was not found")
}
p = NewPairFromFormattedPairs("btcusdt", pairs, PairFormat{Uppercase: false})
if p.String() != "BTC-USDT" {
t.Error("Test failed. TestNewPairFromFormattedPairs: Expected currency was not found")
t.Error("TestNewPairFromFormattedPairs: Expected currency was not found")
}
// Now a wrong one, will default to NewPairFromString
p = NewPairFromFormattedPairs("ethusdt", pairs, PairFormat{})
if p.String() != "ethusdt" && p.Base.String() != "eth" {
t.Error("Test failed. TestNewPairFromFormattedPairs: Expected currency was not found")
t.Error("TestNewPairFromFormattedPairs: Expected currency was not found")
}
}
@@ -435,48 +435,48 @@ func TestContainsCurrency(t *testing.T) {
p := NewPair(BTC, USD)
if !p.ContainsCurrency(BTC) {
t.Error("Test failed. TestContainsCurrency: Expected currency was not found")
t.Error("TestContainsCurrency: Expected currency was not found")
}
if p.ContainsCurrency(ETH) {
t.Error("Test failed. TestContainsCurrency: Non-existent currency was found")
t.Error("TestContainsCurrency: Non-existent currency was found")
}
}
func TestFormatPairs(t *testing.T) {
newP, err := FormatPairs([]string{""}, "-", "")
if err != nil {
t.Error("Test Failed - FormatPairs() error", err)
t.Error("FormatPairs() error", err)
}
if len(newP) > 0 {
t.Error("Test failed. TestFormatPairs: Empty string returned a valid pair")
t.Error("TestFormatPairs: Empty string returned a valid pair")
}
newP, err = FormatPairs([]string{defaultPairWDelimiter}, "-", "")
if err != nil {
t.Error("Test Failed - FormatPairs() error", err)
t.Error("FormatPairs() error", err)
}
if newP[0].String() != defaultPairWDelimiter {
t.Error("Test failed. TestFormatPairs: Expected pair was not found")
t.Error("TestFormatPairs: Expected pair was not found")
}
newP, err = FormatPairs([]string{defaultPair}, "", "BTC")
if err != nil {
t.Error("Test Failed - FormatPairs() error", err)
t.Error("FormatPairs() error", err)
}
if newP[0].String() != defaultPair {
t.Error("Test failed. TestFormatPairs: Expected pair was not found")
t.Error("TestFormatPairs: Expected pair was not found")
}
newP, err = FormatPairs([]string{"ETHUSD"}, "", "")
if err != nil {
t.Error("Test Failed - FormatPairs() error", err)
t.Error("FormatPairs() error", err)
}
if newP[0].String() != "ETHUSD" {
t.Error("Test failed. TestFormatPairs: Expected pair was not found")
t.Error("TestFormatPairs: Expected pair was not found")
}
}
@@ -492,12 +492,12 @@ func TestCopyPairFormat(t *testing.T) {
result := CopyPairFormat(testPair, pairs, false)
if result.String() != defaultPairWDelimiter {
t.Error("Test failed. TestCopyPairFormat: Expected pair was not found")
t.Error("TestCopyPairFormat: Expected pair was not found")
}
result = CopyPairFormat(NewPair(ETH, USD), pairs, true)
if result.String() != "" {
t.Error("Test failed. TestCopyPairFormat: Unexpected non empty pair returned")
t.Error("TestCopyPairFormat: Unexpected non empty pair returned")
}
}
@@ -507,26 +507,26 @@ func TestFindPairDifferences(t *testing.T) {
// Test new pair update
newPairs, removedPairs := pairList.FindDifferences(NewPairsFromStrings([]string{"DASH-USD"}))
if len(newPairs) != 1 && len(removedPairs) != 3 {
t.Error("Test failed. TestFindPairDifferences: Unexpected values")
t.Error("TestFindPairDifferences: Unexpected values")
}
// Test that we don't allow empty strings for new pairs
newPairs, removedPairs = pairList.FindDifferences(NewPairsFromStrings([]string{""}))
if len(newPairs) != 0 && len(removedPairs) != 3 {
t.Error("Test failed. TestFindPairDifferences: Unexpected values")
t.Error("TestFindPairDifferences: Unexpected values")
}
// Test that we don't allow empty strings for new pairs
newPairs, removedPairs = NewPairsFromStrings([]string{""}).FindDifferences(pairList)
if len(newPairs) != 3 && len(removedPairs) != 0 {
t.Error("Test failed. TestFindPairDifferences: Unexpected values")
t.Error("TestFindPairDifferences: Unexpected values")
}
// Test that the supplied pair lists are the same, so
// no newPairs or removedPairs
newPairs, removedPairs = pairList.FindDifferences(pairList)
if len(newPairs) != 0 && len(removedPairs) != 0 {
t.Error("Test failed. TestFindPairDifferences: Unexpected values")
t.Error("TestFindPairDifferences: Unexpected values")
}
}
@@ -538,7 +538,7 @@ func TestPairsToStringArray(t *testing.T) {
actual := pairs.Strings()
if actual[0] != expected[0] {
t.Error("Test failed. TestPairsToStringArray: Unexpected values")
t.Error("TestPairsToStringArray: Unexpected values")
}
}
@@ -547,7 +547,7 @@ func TestRandomPairFromPairs(t *testing.T) {
var emptyPairs Pairs
result := emptyPairs.GetRandomPair()
if !result.IsEmpty() {
t.Error("Test failed. TestRandomPairFromPairs: Unexpected values")
t.Error("TestRandomPairFromPairs: Unexpected values")
}
// Test that a populated pairs array returns a non-empty currency pair
@@ -556,7 +556,7 @@ func TestRandomPairFromPairs(t *testing.T) {
result = pairs.GetRandomPair()
if result.IsEmpty() {
t.Error("Test failed. TestRandomPairFromPairs: Unexpected values")
t.Error("TestRandomPairFromPairs: Unexpected values")
}
// Test that a populated pairs array over a number of attempts returns ALL
@@ -574,7 +574,7 @@ func TestRandomPairFromPairs(t *testing.T) {
for x := range pairs {
_, ok := expectedResults[pairs[x].String()]
if !ok {
t.Error("Test failed. TestRandomPairFromPairs: Unexpected values")
t.Error("TestRandomPairFromPairs: Unexpected values")
}
}
}
@@ -582,6 +582,6 @@ func TestRandomPairFromPairs(t *testing.T) {
func TestIsInvalid(t *testing.T) {
p := NewPair(LTC, LTC)
if !p.IsInvalid() {
t.Error("Test Failed - IsInvalid() error expect true but received false")
t.Error("IsInvalid() error expect true but received false")
}
}

View File

@@ -22,9 +22,6 @@ func NewPairsFromStrings(pairs []string) Pairs {
return ps
}
// Pairs defines a list of pairs
type Pairs []Pair
// Strings returns a slice of strings referring to each currency pair
func (p Pairs) Strings() []string {
var list []string
@@ -186,3 +183,6 @@ func (p Pairs) GetRandomPair() Pair {
return p[rand.Intn(pairsLen)]
}
// Pairs defines a list of pairs
type Pairs []Pair

View File

@@ -11,7 +11,7 @@ func TestPairsUpper(t *testing.T) {
expected := "BTC_USD,BTC_AUD,BTC_LTC"
if pairs.Upper().Join() != expected {
t.Errorf("Test Failed - Pairs Join() error expected %s but received %s",
t.Errorf("Pairs Join() error expected %s but received %s",
expected, pairs.Join())
}
}
@@ -22,7 +22,7 @@ func TestPairsString(t *testing.T) {
for i, p := range pairs {
if p.String() != expected[i] {
t.Errorf("Test Failed - Pairs String() error expected %s but received %s",
t.Errorf("Pairs String() error expected %s but received %s",
expected, p.String())
}
}
@@ -33,7 +33,7 @@ func TestPairsJoin(t *testing.T) {
expected := "btc_usd,btc_aud,btc_ltc"
if pairs.Join() != expected {
t.Errorf("Test Failed - Pairs Join() error expected %s but received %s",
t.Errorf("Pairs Join() error expected %s but received %s",
expected, pairs.Join())
}
}
@@ -43,25 +43,25 @@ func TestPairsFormat(t *testing.T) {
expected := "BTC-USD,BTC-AUD,BTC-LTC"
if pairs.Format("-", "", true).Join() != expected {
t.Errorf("Test Failed - Pairs Join() error expected %s but received %s",
t.Errorf("Pairs Join() error expected %s but received %s",
expected, pairs.Format("-", "", true).Join())
}
expected = "btc:usd,btc:aud,btc:ltc"
if pairs.Format(":", "", false).Join() != expected {
t.Errorf("Test Failed - Pairs Join() error expected %s but received %s",
t.Errorf("Pairs Join() error expected %s but received %s",
expected, pairs.Format(":", "", false).Join())
}
if pairs.Format(":", "KRW", false).Join() != "" {
t.Errorf("Test Failed - Pairs Join() error expected %s but received %s",
t.Errorf("Pairs Join() error expected %s but received %s",
expected, pairs.Format(":", "KRW", true).Join())
}
pairs = NewPairsFromStrings([]string{"DASHKRW", "BTCKRW"})
expected = "dash-krw,btc-krw"
if pairs.Format("-", "KRW", false).Join() != expected {
t.Errorf("Test Failed - Pairs Join() error expected %s but received %s",
t.Errorf("Pairs Join() error expected %s but received %s",
expected, pairs.Format("-", "KRW", false).Join())
}
}
@@ -72,21 +72,21 @@ func TestPairsUnmarshalJSON(t *testing.T) {
encoded, err := common.JSONEncode(configPairs)
if err != nil {
t.Fatal("Test Failed - Pairs UnmarshalJSON() error", err)
t.Fatal("Pairs UnmarshalJSON() error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Pairs UnmarshalJSON() error", err)
t.Fatal("Pairs UnmarshalJSON() error", err)
}
err = common.JSONDecode(encoded, &unmarshalHere)
if err != nil {
t.Fatal("Test Failed - Pairs UnmarshalJSON() error", err)
t.Fatal("Pairs UnmarshalJSON() error", err)
}
if unmarshalHere.Join() != configPairs {
t.Errorf("Test Failed - Pairs UnmarshalJSON() error expected %s but received %s",
t.Errorf("Pairs UnmarshalJSON() error expected %s but received %s",
configPairs, unmarshalHere.Join())
}
}
@@ -100,12 +100,12 @@ func TestPairsMarshalJSON(t *testing.T) {
encoded, err := common.JSONEncode(quickstruct)
if err != nil {
t.Fatal("Test Failed - Pairs MarshalJSON() error", err)
t.Fatal("Pairs MarshalJSON() error", err)
}
expected := `{"soManyPairs":"btc_usd,btc_aud,btc_ltc"}`
if string(encoded) != expected {
t.Errorf("Test Failed - Pairs MarshalJSON() error expected %s but received %s",
t.Errorf("Pairs MarshalJSON() error expected %s but received %s",
expected, string(encoded))
}
}
@@ -119,7 +119,7 @@ func TestRemovePairsByFilter(t *testing.T) {
pairs = pairs.RemovePairsByFilter(USDT)
if pairs.Contains(NewPair(LTC, USDT), true) {
t.Error("Test failed. TestRemovePairsByFilter unexpected result")
t.Error("TestRemovePairsByFilter unexpected result")
}
}
@@ -133,7 +133,7 @@ func TestRemove(t *testing.T) {
p := NewPair(BTC, USD)
pairs = pairs.Remove(p)
if pairs.Contains(p, true) || len(pairs) != 2 {
t.Error("Test failed. TestRemove unexpected result")
t.Error("TestRemove unexpected result")
}
}
@@ -148,13 +148,13 @@ func TestAdd(t *testing.T) {
p := NewPair(BTC, USDT)
pairs = pairs.Add(p)
if !pairs.Contains(p, true) || len(pairs) != 4 {
t.Error("Test failed. TestAdd unexpected result")
t.Error("TestAdd unexpected result")
}
// Now test adding a pair which already exists
pairs = pairs.Add(p)
if len(pairs) != 4 {
t.Error("Test failed. TestAdd unexpected result")
t.Error("TestAdd unexpected result")
}
}
@@ -165,10 +165,10 @@ func TestContains(t *testing.T) {
}
if !pairs.Contains(NewPair(BTC, USD), true) {
t.Errorf("Test failed. TestContains: Expected pair was not found")
t.Errorf("TestContains: Expected pair was not found")
}
if pairs.Contains(NewPair(ETH, USD), false) {
t.Errorf("Test failed. TestContains: Non-existent pair was found")
t.Errorf("TestContains: Non-existent pair was found")
}
}

View File

@@ -6,7 +6,6 @@ import (
"fmt"
"io/ioutil"
"path/filepath"
"sync"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
@@ -16,75 +15,10 @@ import (
log "github.com/thrasher-corp/gocryptotrader/logger"
)
// CurrencyFileUpdateDelay defines the rate at which the currency.json file is
// updated
const (
DefaultCurrencyFileDelay = 168 * time.Hour
DefaultForeignExchangeDelay = 1 * time.Minute
DefaultStorageFile = "currency.json"
)
func init() {
storage.SetDefaults()
}
// storage is an overarching type that keeps track of and updates currency,
// currency exchange rates and pairs
var storage Storage
// Storage contains the loaded storage currencies supported on available crypto
// or fiat marketplaces
// NOTE: All internal currencies are upper case
type Storage struct {
// FiatCurrencies defines the running fiat currencies in the currency
// storage
fiatCurrencies Currencies
// Cryptocurrencies defines the running cryptocurrencies in the currency
// storage
cryptocurrencies Currencies
// CurrencyCodes is a full basket of currencies either crypto, fiat, ico or
// contract being tracked by the currency storage system
currencyCodes BaseCodes
// Main converting currency
baseCurrency Code
// FXRates defines a protected conversion rate map
fxRates ConversionRates
// DefaultBaseCurrency is the base currency used for conversion
defaultBaseCurrency Code
// DefaultFiatCurrencies has the default minimum of FIAT values
defaultFiatCurrencies Currencies
// DefaultCryptoCurrencies has the default minimum of crytpocurrency values
defaultCryptoCurrencies Currencies
// FiatExchangeMarkets defines an interface to access FX data for fiat
// currency rates
fiatExchangeMarkets *forexprovider.ForexProviders
// CurrencyAnalysis defines a full market analysis suite to receieve and
// define different fiat currencies, cryptocurrencies and markets
currencyAnalysis *coinmarketcap.Coinmarketcap
// Path defines the main folder to dump and find currency JSON
path string
// Update delay variables
currencyFileUpdateDelay time.Duration
foreignExchangeUpdateDelay time.Duration
mtx sync.Mutex
wg sync.WaitGroup
shutdownC chan struct{}
updaterRunning bool
Verbose bool
}
// SetDefaults sets storage defaults for basic package functionality
func (s *Storage) SetDefaults() {
s.defaultBaseCurrency = USD

View File

@@ -8,7 +8,7 @@ func TestRunUpdater(t *testing.T) {
emptyMainConfig := MainConfiguration{}
err := newStorage.RunUpdater(BotOverrides{}, &emptyMainConfig, "", false)
if err == nil {
t.Fatal("Test Failed storage RunUpdater() error cannot be nil")
t.Fatal("storage RunUpdater() error cannot be nil")
}
mainConfig := MainConfiguration{
@@ -18,11 +18,11 @@ func TestRunUpdater(t *testing.T) {
err = newStorage.RunUpdater(BotOverrides{}, &mainConfig, "", false)
if err == nil {
t.Fatal("Test Failed storage RunUpdater() error cannot be nil")
t.Fatal("storage RunUpdater() error cannot be nil")
}
err = newStorage.RunUpdater(BotOverrides{}, &mainConfig, "/bla", false)
if err != nil {
t.Fatal("Test Failed storage RunUpdater() error", err)
t.Fatal("storage RunUpdater() error", err)
}
}

62
currency/storage_types.go Normal file
View File

@@ -0,0 +1,62 @@
package currency
import (
"sync"
"time"
"github.com/thrasher-corp/gocryptotrader/currency/coinmarketcap"
"github.com/thrasher-corp/gocryptotrader/currency/forexprovider"
)
// CurrencyFileUpdateDelay defines the rate at which the currency.json file is
// updated
const (
DefaultCurrencyFileDelay = 168 * time.Hour
DefaultForeignExchangeDelay = 1 * time.Minute
DefaultStorageFile = "currency.json"
)
// storage is an overarching type that keeps track of and updates currency,
// currency exchange rates and pairs
var storage Storage
// Storage contains the loaded storage currencies supported on available crypto
// or fiat marketplaces
// NOTE: All internal currencies are upper case
type Storage struct {
// FiatCurrencies defines the running fiat currencies in the currency
// storage
fiatCurrencies Currencies
// Cryptocurrencies defines the running cryptocurrencies in the currency
// storage
cryptocurrencies Currencies
// CurrencyCodes is a full basket of currencies either crypto, fiat, ico or
// contract being tracked by the currency storage system
currencyCodes BaseCodes
// Main converting currency
baseCurrency Code
// FXRates defines a protected conversion rate map
fxRates ConversionRates
// DefaultBaseCurrency is the base currency used for conversion
defaultBaseCurrency Code
// DefaultFiatCurrencies has the default minimum of FIAT values
defaultFiatCurrencies Currencies
// DefaultCryptoCurrencies has the default minimum of crytpocurrency values
defaultCryptoCurrencies Currencies
// FiatExchangeMarkets defines an interface to access FX data for fiat
// currency rates
fiatExchangeMarkets *forexprovider.ForexProviders
// CurrencyAnalysis defines a full market analysis suite to receieve and
// define different fiat currencies, cryptocurrencies and markets
currencyAnalysis *coinmarketcap.Coinmarketcap
// Path defines the main folder to dump and find currency JSON
path string
// Update delay variables
currencyFileUpdateDelay time.Duration
foreignExchangeUpdateDelay time.Duration
mtx sync.Mutex
wg sync.WaitGroup
shutdownC chan struct{}
updaterRunning bool
Verbose bool
}

View File

@@ -2,6 +2,15 @@ package currency
import "errors"
// GetSymbolByCurrencyName returns a currency symbol
func GetSymbolByCurrencyName(currency Code) (string, error) {
result, ok := symbols[currency.Item]
if !ok {
return "", errors.New("currency symbol not found")
}
return result, nil
}
// symbols map holds the currency name and symbol mappings
var symbols = map[*Item]string{
ALL.Item: "Lek",
@@ -116,12 +125,3 @@ var symbols = map[*Item]string{
YER.Item: "﷼",
ZWD.Item: "Z$",
}
// GetSymbolByCurrencyName returns a currency symbol
func GetSymbolByCurrencyName(currency Code) (string, error) {
result, ok := symbols[currency.Item]
if !ok {
return "", errors.New("currency symbol not found")
}
return result, nil
}

View File

@@ -6,16 +6,16 @@ func TestGetSymbolByCurrencyName(t *testing.T) {
expected := "₩"
actual, err := GetSymbolByCurrencyName(KPW)
if err != nil {
t.Errorf("Test failed. TestGetSymbolByCurrencyName error: %s", err)
t.Errorf("TestGetSymbolByCurrencyName error: %s", err)
}
if actual != expected {
t.Errorf("Test failed. TestGetSymbolByCurrencyName differing values")
t.Errorf("TestGetSymbolByCurrencyName differing values")
}
_, err = GetSymbolByCurrencyName(Code{})
if err == nil {
t.Errorf("Test failed. TestGetSymbolByCurrencyNam returned nil on non-existent currency")
t.Errorf("TestGetSymbolByCurrencyNam returned nil on non-existent currency")
}
}

View File

@@ -1,5 +1,15 @@
package currency
// GetTranslation returns similar strings for a particular currency if not found
// returns the code back
func GetTranslation(currency Code) (Code, bool) {
val, ok := translations[currency]
if !ok {
return currency, ok
}
return val, ok
}
var translations = map[Code]Code{
BTC: XBT,
ETH: XETH,
@@ -10,13 +20,3 @@ var translations = map[Code]Code{
XDG: DOGE,
USDT: USD,
}
// GetTranslation returns similar strings for a particular currency if not found
// returns the code back
func GetTranslation(currency Code) (Code, bool) {
val, ok := translations[currency]
if !ok {
return currency, ok
}
return val, ok
}