Currency package update (#247)

* Initial currency overhaul before service system implementation

* Remove redundant currency string in orderbook.Base
Unexport lastupdated field in orderbook.Base as it was being instantiated multiple times
Add error handling for process orderbook

*  Remove redundant currency string in ticker.Price
 Unexport lastupdated field in ticker.Price
 Add error handling for process ticker function and fix tests

* Phase Two Update

* Update translations to use map type - thankyou to kempeng for spotting this

* Change pair method name from Display -> Format for better readability

* Fixes misspelling and tests

* Implement requested changes from GloriousCode

* Remove reduntant function and streamlined return in currency_translation.go

* Revert pair method naming conventions

* Change currency naming conventions

* Changed code type to exported Item type with underlying string to reduce complexity

* Added interim orderbook process method to orderbook.Base type

* Changed feebuilder struct field to currency.Pair

* Adds fall over system for backup fx providers

* deprecate function and children and fix linter issue with btcmarkets

* Fixed requested changes

* Fix bug and move mtx for rates

* Fixed after rebase oopsies

* Fix linter issues

* Fixes race conditions in testing functions

* Final phase coinmarketcap update

* fix linter issues

* Implement requested changes

* Adds configuration variables to increase/decrease time durations between updating currency file and fetching new currency rates

* Add a collection of tests to improve codecov

* After rebase oopsy fixes for btse

* Fix requested changes

* fix after rebase oopsies and add more efficient comparison checks within currency pair

* Fix linter issues
This commit is contained in:
Ryan O'Hara-Reid
2019-03-19 11:49:05 +11:00
committed by Adrian Gallagher
parent ed760e184e
commit 0990f9d118
189 changed files with 11982 additions and 8055 deletions

View File

@@ -12,7 +12,7 @@ import (
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/config"
"github.com/thrasher-/gocryptotrader/currency/symbol"
"github.com/thrasher-/gocryptotrader/currency"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
"github.com/thrasher-/gocryptotrader/exchanges/request"
"github.com/thrasher-/gocryptotrader/exchanges/ticker"
@@ -80,9 +80,9 @@ func (i *ItBit) Setup(exch config.ExchangeConfig) {
i.SetHTTPClientUserAgent(exch.HTTPUserAgent)
i.RESTPollingDelay = exch.RESTPollingDelay
i.Verbose = exch.Verbose
i.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",")
i.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",")
i.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",")
i.BaseCurrencies = exch.BaseCurrencies
i.AvailablePairs = exch.AvailablePairs
i.EnabledPairs = exch.EnabledPairs
err := i.SetCurrencyPairFormat()
if err != nil {
log.Fatal(err)
@@ -427,7 +427,7 @@ func (i *ItBit) GetFee(feeBuilder exchange.FeeBuilder) (float64, error) {
case exchange.CryptocurrencyTradeFee:
fee = calculateTradingFee(feeBuilder.PurchasePrice, feeBuilder.Amount, feeBuilder.IsMaker)
case exchange.InternationalBankWithdrawalFee:
fee = getInternationalBankWithdrawalFee(feeBuilder.CurrencyItem, feeBuilder.BankTransactionType)
fee = getInternationalBankWithdrawalFee(feeBuilder.FiatCurrency, feeBuilder.BankTransactionType)
}
if fee < 0 {
@@ -447,11 +447,15 @@ func calculateTradingFee(purchasePrice, amount float64, isMaker bool) float64 {
return feePercent * purchasePrice * amount
}
func getInternationalBankWithdrawalFee(currency string, bankTransactionType exchange.InternationalBankTransactionType) float64 {
func getInternationalBankWithdrawalFee(c currency.Code, bankTransactionType exchange.InternationalBankTransactionType) float64 {
var fee float64
if (bankTransactionType == exchange.Swift || bankTransactionType == exchange.WireTransfer) && currency == symbol.USD {
if (bankTransactionType == exchange.Swift ||
bankTransactionType == exchange.WireTransfer) &&
c == currency.USD {
fee = 40
} else if (bankTransactionType == exchange.SEPA || bankTransactionType == exchange.WireTransfer) && currency == symbol.EUR {
} else if (bankTransactionType == exchange.SEPA ||
bankTransactionType == exchange.WireTransfer) &&
c == currency.EUR {
fee = 1
}
return fee

View File

@@ -6,8 +6,7 @@ import (
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/config"
"github.com/thrasher-/gocryptotrader/currency/pair"
"github.com/thrasher-/gocryptotrader/currency/symbol"
"github.com/thrasher-/gocryptotrader/currency"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
)
@@ -144,14 +143,13 @@ func TestWalletTransfer(t *testing.T) {
func setFeeBuilder() exchange.FeeBuilder {
return exchange.FeeBuilder{
Amount: 1,
Delimiter: "_",
FeeType: exchange.CryptocurrencyTradeFee,
FirstCurrency: symbol.BTC,
SecondCurrency: symbol.LTC,
IsMaker: false,
Amount: 1,
FeeType: exchange.CryptocurrencyTradeFee,
Pair: currency.NewPairWithDelimiter(currency.BTC.String(),
currency.LTC.String(),
"_"),
PurchasePrice: 1,
CurrencyItem: symbol.USD,
FiatCurrency: currency.USD,
BankTransactionType: exchange.WireTransfer,
}
}
@@ -199,7 +197,7 @@ func TestGetFee(t *testing.T) {
// CryptocurrencyWithdrawalFee Invalid currency
feeBuilder = setFeeBuilder()
feeBuilder.FirstCurrency = "hello"
feeBuilder.Pair.Base = currency.NewCode("hello")
feeBuilder.FeeType = exchange.CryptocurrencyWithdrawalFee
if resp, err := i.GetFee(feeBuilder); resp != float64(0) || err != nil {
t.Errorf("Test Failed - GetFee() error. Expected: %f, Received: %f", float64(0), resp)
@@ -225,7 +223,7 @@ func TestGetFee(t *testing.T) {
// InternationalBankWithdrawalFee Basic
feeBuilder = setFeeBuilder()
feeBuilder.FeeType = exchange.InternationalBankWithdrawalFee
feeBuilder.CurrencyItem = symbol.USD
feeBuilder.FiatCurrency = currency.USD
if resp, err := i.GetFee(feeBuilder); resp != float64(40) || err != nil {
t.Errorf("Test Failed - GetFee() error. Expected: %f, Received: %f", float64(40), resp)
t.Error(err)
@@ -292,10 +290,10 @@ func TestSubmitOrder(t *testing.T) {
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
}
var p = pair.CurrencyPair{
Delimiter: "",
FirstCurrency: symbol.BTC,
SecondCurrency: symbol.USDT,
var p = currency.Pair{
Delimiter: "",
Base: currency.BTC,
Quote: currency.USDT,
}
response, err := i.SubmitOrder(p, exchange.BuyOrderSide, exchange.LimitOrderType, 1, 10, "hi")
if areTestAPIKeysSet() && (err != nil || !response.IsOrderPlaced) {
@@ -313,7 +311,7 @@ func TestCancelExchangeOrder(t *testing.T) {
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
}
currencyPair := pair.NewCurrencyPair(symbol.LTC, symbol.BTC)
currencyPair := currency.NewPair(currency.LTC, currency.BTC)
var orderCancellation = exchange.OrderCancellation{
OrderID: "1",
@@ -340,7 +338,7 @@ func TestCancelAllExchangeOrders(t *testing.T) {
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
}
currencyPair := pair.NewCurrencyPair(symbol.LTC, symbol.BTC)
currencyPair := currency.NewPair(currency.LTC, currency.BTC)
var orderCancellation = exchange.OrderCancellation{
OrderID: "1",
@@ -384,7 +382,7 @@ func TestWithdraw(t *testing.T) {
TestSetup(t)
var withdrawCryptoRequest = exchange.WithdrawRequest{
Amount: 100,
Currency: symbol.LTC,
Currency: currency.LTC,
Address: "1F5zVDgNjorJ51oGebSvNCrSAHpwGkUdDB",
Description: "WITHDRAW IT ALL",
}
@@ -432,7 +430,7 @@ func TestWithdrawInternationalBank(t *testing.T) {
}
func TestGetDepositAddress(t *testing.T) {
_, err := i.GetDepositAddress(symbol.BTC, "")
_, err := i.GetDepositAddress(currency.BTC, "")
if err == nil {
t.Error("Test Failed - GetDepositAddress() error cannot be nil")
}

View File

@@ -9,7 +9,7 @@ import (
"time"
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/currency/pair"
"github.com/thrasher-/gocryptotrader/currency"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
"github.com/thrasher-/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-/gocryptotrader/exchanges/ticker"
@@ -34,7 +34,7 @@ func (i *ItBit) Run() {
}
// UpdateTicker updates and returns the ticker for a currency pair
func (i *ItBit) UpdateTicker(p pair.CurrencyPair, assetType string) (ticker.Price, error) {
func (i *ItBit) UpdateTicker(p currency.Pair, assetType string) (ticker.Price, error) {
var tickerPrice ticker.Price
tick, err := i.GetTicker(exchange.FormatExchangeCurrency(i.Name,
p).String())
@@ -49,12 +49,17 @@ func (i *ItBit) UpdateTicker(p pair.CurrencyPair, assetType string) (ticker.Pric
tickerPrice.High = tick.High24h
tickerPrice.Low = tick.Low24h
tickerPrice.Volume = tick.Volume24h
ticker.ProcessTicker(i.GetName(), p, tickerPrice, assetType)
err = ticker.ProcessTicker(i.GetName(), tickerPrice, assetType)
if err != nil {
return tickerPrice, err
}
return ticker.GetTicker(i.Name, p, assetType)
}
// GetTickerPrice returns the ticker for a currency pair
func (i *ItBit) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Price, error) {
func (i *ItBit) GetTickerPrice(p currency.Pair, assetType string) (ticker.Price, error) {
tickerNew, err := ticker.GetTicker(i.GetName(), p, assetType)
if err != nil {
return i.UpdateTicker(p, assetType)
@@ -63,8 +68,8 @@ func (i *ItBit) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Pr
}
// GetOrderbookEx returns orderbook base on the currency pair
func (i *ItBit) GetOrderbookEx(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
ob, err := orderbook.GetOrderbook(i.GetName(), p, assetType)
func (i *ItBit) GetOrderbookEx(p currency.Pair, assetType string) (orderbook.Base, error) {
ob, err := orderbook.Get(i.GetName(), p, assetType)
if err != nil {
return i.UpdateOrderbook(p, assetType)
}
@@ -72,7 +77,7 @@ func (i *ItBit) GetOrderbookEx(p pair.CurrencyPair, assetType string) (orderbook
}
// UpdateOrderbook updates and returns the orderbook for a currency pair
func (i *ItBit) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
func (i *ItBit) UpdateOrderbook(p currency.Pair, assetType string) (orderbook.Base, error) {
var orderBook orderbook.Base
orderbookNew, err := i.GetOrderbook(exchange.FormatExchangeCurrency(i.Name,
p).String())
@@ -82,32 +87,42 @@ func (i *ItBit) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderboo
for x := range orderbookNew.Bids {
data := orderbookNew.Bids[x]
price, err := strconv.ParseFloat(data[0], 64)
var price, amount float64
price, err = strconv.ParseFloat(data[0], 64)
if err != nil {
log.Error(err)
return orderBook, err
}
amount, err := strconv.ParseFloat(data[1], 64)
amount, err = strconv.ParseFloat(data[1], 64)
if err != nil {
log.Error(err)
return orderBook, err
}
orderBook.Bids = append(orderBook.Bids, orderbook.Item{Amount: amount, Price: price})
}
for x := range orderbookNew.Asks {
data := orderbookNew.Asks[x]
price, err := strconv.ParseFloat(data[0], 64)
var price, amount float64
price, err = strconv.ParseFloat(data[0], 64)
if err != nil {
log.Error(err)
return orderBook, err
}
amount, err := strconv.ParseFloat(data[1], 64)
amount, err = strconv.ParseFloat(data[1], 64)
if err != nil {
log.Error(err)
return orderBook, err
}
orderBook.Asks = append(orderBook.Asks, orderbook.Item{Amount: amount, Price: price})
}
orderbook.ProcessOrderbook(i.GetName(), p, orderBook, assetType)
return orderbook.GetOrderbook(i.Name, p, assetType)
orderBook.Pair = p
orderBook.ExchangeName = i.GetName()
orderBook.AssetType = assetType
err = orderBook.Process()
if err != nil {
return orderBook, err
}
return orderbook.Get(i.Name, p, assetType)
}
// GetAccountInfo retrieves balances for all enabled currencies
@@ -142,7 +157,7 @@ func (i *ItBit) GetAccountInfo() (exchange.AccountInfo, error) {
for key, data := range amounts {
fullBalance = append(fullBalance, exchange.AccountCurrencyInfo{
CurrencyName: key,
CurrencyName: currency.NewCode(key),
TotalValue: data.TotalValue,
Hold: data.Hold,
})
@@ -163,14 +178,14 @@ func (i *ItBit) GetFundingHistory() ([]exchange.FundHistory, error) {
}
// GetExchangeHistory returns historic trade data since exchange opening.
func (i *ItBit) GetExchangeHistory(p pair.CurrencyPair, assetType string) ([]exchange.TradeHistory, error) {
func (i *ItBit) GetExchangeHistory(p currency.Pair, assetType string) ([]exchange.TradeHistory, error) {
var resp []exchange.TradeHistory
return resp, common.ErrNotYetImplemented
}
// SubmitOrder submits a new order
func (i *ItBit) SubmitOrder(p pair.CurrencyPair, side exchange.OrderSide, orderType exchange.OrderType, amount, price float64, _ string) (exchange.SubmitOrderResponse, error) {
func (i *ItBit) SubmitOrder(p currency.Pair, side exchange.OrderSide, orderType exchange.OrderType, amount, price float64, _ string) (exchange.SubmitOrderResponse, error) {
var submitOrderResponse exchange.SubmitOrderResponse
var wallet string
@@ -182,17 +197,28 @@ func (i *ItBit) SubmitOrder(p pair.CurrencyPair, side exchange.OrderSide, orderT
// Determine what wallet ID to use if there is any actual available currency to make the trade!
for _, i := range wallets {
for j := range i.Balances {
if i.Balances[j].Currency == p.FirstCurrency.String() && i.Balances[j].AvailableBalance >= amount {
if i.Balances[j].Currency == p.Base.String() &&
i.Balances[j].AvailableBalance >= amount {
wallet = i.ID
}
}
}
if wallet == "" {
return submitOrderResponse, fmt.Errorf("no wallet found with currency: %s with amount >= %v", p.FirstCurrency.String(), amount)
return submitOrderResponse,
fmt.Errorf("no wallet found with currency: %s with amount >= %v",
p.Base,
amount)
}
response, err := i.PlaceOrder(wallet, side.ToString(), orderType.ToString(), p.FirstCurrency.String(), amount, price, p.Pair().String(), "")
response, err := i.PlaceOrder(wallet,
side.ToString(),
orderType.ToString(),
p.Base.String(),
amount,
price,
p.String(),
"")
if response.ID != "" {
submitOrderResponse.OrderID = response.ID
@@ -246,7 +272,7 @@ func (i *ItBit) GetOrderInfo(orderID string) (exchange.OrderDetail, error) {
// NOTE: This has not been implemented due to the fact you need to generate a
// a specific wallet ID and they restrict the amount of deposit address you can
// request limiting them to 2.
func (i *ItBit) GetDepositAddress(cryptocurrency pair.CurrencyItem, accountID string) (string, error) {
func (i *ItBit) GetDepositAddress(cryptocurrency currency.Code, accountID string) (string, error) {
return "", common.ErrNotYetImplemented
}
@@ -296,7 +322,8 @@ func (i *ItBit) GetActiveOrders(getOrdersRequest exchange.GetOrdersRequest) ([]e
var orders []exchange.OrderDetail
for _, order := range allOrders {
symbol := pair.NewCurrencyPairDelimiter(order.Instrument, i.ConfigCurrencyPairFormat.Delimiter)
symbol := currency.NewPairDelimiter(order.Instrument,
i.ConfigCurrencyPairFormat.Delimiter)
side := exchange.OrderSide(strings.ToUpper(order.Side))
orderDate, err := time.Parse(time.RFC3339, order.CreatedTime)
if err != nil {
@@ -316,7 +343,8 @@ func (i *ItBit) GetActiveOrders(getOrdersRequest exchange.GetOrdersRequest) ([]e
})
}
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks,
getOrdersRequest.EndTicks)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
exchange.FilterOrdersByCurrencies(&orders, getOrdersRequest.Currencies)
@@ -346,7 +374,8 @@ func (i *ItBit) GetOrderHistory(getOrdersRequest exchange.GetOrdersRequest) ([]e
continue
}
symbol := pair.NewCurrencyPairDelimiter(order.Instrument, i.ConfigCurrencyPairFormat.Delimiter)
symbol := currency.NewPairDelimiter(order.Instrument,
i.ConfigCurrencyPairFormat.Delimiter)
side := exchange.OrderSide(strings.ToUpper(order.Side))
orderDate, err := time.Parse(time.RFC3339, order.CreatedTime)
if err != nil {
@@ -366,7 +395,8 @@ func (i *ItBit) GetOrderHistory(getOrdersRequest exchange.GetOrdersRequest) ([]e
})
}
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks,
getOrdersRequest.EndTicks)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
exchange.FilterOrdersByCurrencies(&orders, getOrdersRequest.Currencies)