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

@@ -10,7 +10,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 (l *LakeBTC) Setup(exch config.ExchangeConfig) {
l.SetHTTPClientUserAgent(exch.HTTPUserAgent)
l.RESTPollingDelay = exch.RESTPollingDelay
l.Verbose = exch.Verbose
l.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",")
l.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",")
l.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",")
l.BaseCurrencies = exch.BaseCurrencies
l.AvailablePairs = exch.AvailablePairs
l.EnabledPairs = exch.EnabledPairs
err := l.SetCurrencyPairFormat()
if err != nil {
log.Fatal(err)
@@ -379,12 +379,15 @@ func (l *LakeBTC) GetFee(feeBuilder exchange.FeeBuilder) (float64, error) {
var fee float64
switch feeBuilder.FeeType {
case exchange.CryptocurrencyTradeFee:
fee = calculateTradingFee(feeBuilder.PurchasePrice, feeBuilder.Amount, feeBuilder.IsMaker)
fee = calculateTradingFee(feeBuilder.PurchasePrice,
feeBuilder.Amount,
feeBuilder.IsMaker)
case exchange.CyptocurrencyDepositFee:
fee = getCryptocurrencyWithdrawalFee(feeBuilder.FirstCurrency)
fee = getCryptocurrencyWithdrawalFee(feeBuilder.Pair.Base)
case exchange.InternationalBankWithdrawalFee:
// fees for withdrawals are dynamic. They cannot be calculated in advance
// As they are manually performed via the website, it can only be determined when submitting the request
// fees for withdrawals are dynamic. They cannot be calculated in
// advance as they are manually performed via the website, it can only
// be determined when submitting the request
}
if fee < 0 {
@@ -405,8 +408,8 @@ func calculateTradingFee(purchasePrice, amount float64, isMaker bool) (fee float
return fee * amount * purchasePrice
}
func getCryptocurrencyWithdrawalFee(currency string) (fee float64) {
if currency == symbol.BTC {
func getCryptocurrencyWithdrawalFee(c currency.Code) (fee float64) {
if c == currency.BTC {
fee = 0.001
}
return fee

View File

@@ -5,8 +5,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"
)
@@ -137,14 +136,14 @@ func TestGetExternalAccounts(t *testing.T) {
func setFeeBuilder() exchange.FeeBuilder {
return exchange.FeeBuilder{
Amount: 1,
Delimiter: "_",
FeeType: exchange.CryptocurrencyTradeFee,
FirstCurrency: symbol.BTC,
SecondCurrency: symbol.LTC,
Amount: 1,
FeeType: exchange.CryptocurrencyTradeFee,
Pair: currency.NewPairWithDelimiter(currency.BTC.String(),
currency.LTC.String(),
"_"),
IsMaker: false,
PurchasePrice: 1,
CurrencyItem: symbol.USD,
FiatCurrency: currency.USD,
BankTransactionType: exchange.WireTransfer,
}
}
@@ -192,7 +191,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 := l.GetFee(feeBuilder); resp != float64(0) || err != nil {
t.Errorf("Test Failed - GetFee() error. Expected: %f, Received: %f", float64(0), resp)
@@ -218,7 +217,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 := l.GetFee(feeBuilder); resp != float64(0) || err != nil {
t.Errorf("Test Failed - GetFee() error. Expected: %f, Received: %f", float64(0), resp)
t.Error(err)
@@ -286,10 +285,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.EUR,
var p = currency.Pair{
Delimiter: "",
Base: currency.BTC,
Quote: currency.EUR,
}
response, err := l.SubmitOrder(p, exchange.BuyOrderSide, exchange.MarketOrderType, 1, 10, "hi")
if areTestAPIKeysSet() && (err != nil || !response.IsOrderPlaced) {
@@ -307,7 +306,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",
@@ -333,7 +332,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",
@@ -368,7 +367,7 @@ func TestWithdraw(t *testing.T) {
TestSetup(t)
var withdrawCryptoRequest = exchange.WithdrawRequest{
Amount: 100,
Currency: symbol.BTC,
Currency: currency.BTC,
Address: "1F5zVDgNjorJ51oGebSvNCrSAHpwGkUdDB",
Description: "7860767916",
}
@@ -420,12 +419,12 @@ func TestWithdrawInternationalBank(t *testing.T) {
func TestGetDepositAddress(t *testing.T) {
if areTestAPIKeysSet() {
_, err := l.GetDepositAddress(symbol.BTC, "")
_, err := l.GetDepositAddress(currency.BTC, "")
if err != nil {
t.Error("Test Failed - GetDepositAddress() error", err)
}
} else {
_, err := l.GetDepositAddress(symbol.DASH, "")
_, err := l.GetDepositAddress(currency.DASH, "")
if err == nil {
t.Error("Test Failed - GetDepositAddress() error cannot be nil")
}

View File

@@ -9,8 +9,7 @@ import (
"time"
"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/currency/pair"
"github.com/thrasher-/gocryptotrader/currency/symbol"
"github.com/thrasher-/gocryptotrader/currency"
exchange "github.com/thrasher-/gocryptotrader/exchanges"
"github.com/thrasher-/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-/gocryptotrader/exchanges/ticker"
@@ -37,7 +36,13 @@ func (l *LakeBTC) Run() {
if err != nil {
log.Errorf("%s Failed to get available products.\n", l.GetName())
} else {
err = l.UpdateCurrencies(exchangeProducts, false, false)
var newExchangeProducts currency.Pairs
for _, p := range exchangeProducts {
newExchangeProducts = append(newExchangeProducts,
currency.NewPairFromString(p))
}
err = l.UpdateCurrencies(newExchangeProducts, false, false)
if err != nil {
log.Errorf("%s Failed to update available currencies.\n", l.GetName())
}
@@ -45,7 +50,7 @@ func (l *LakeBTC) Run() {
}
// UpdateTicker updates and returns the ticker for a currency pair
func (l *LakeBTC) UpdateTicker(p pair.CurrencyPair, assetType string) (ticker.Price, error) {
func (l *LakeBTC) UpdateTicker(p currency.Pair, assetType string) (ticker.Price, error) {
tick, err := l.GetTicker()
if err != nil {
return ticker.Price{}, err
@@ -61,13 +66,17 @@ func (l *LakeBTC) UpdateTicker(p pair.CurrencyPair, assetType string) (ticker.Pr
tickerPrice.High = tick[currency].High
tickerPrice.Low = tick[currency].Low
tickerPrice.Last = tick[currency].Last
ticker.ProcessTicker(l.GetName(), x, tickerPrice, assetType)
err = ticker.ProcessTicker(l.GetName(), tickerPrice, assetType)
if err != nil {
return tickerPrice, err
}
}
return ticker.GetTicker(l.Name, p, assetType)
}
// GetTickerPrice returns the ticker for a currency pair
func (l *LakeBTC) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Price, error) {
func (l *LakeBTC) GetTickerPrice(p currency.Pair, assetType string) (ticker.Price, error) {
tickerNew, err := ticker.GetTicker(l.GetName(), p, assetType)
if err != nil {
return l.UpdateTicker(p, assetType)
@@ -76,8 +85,8 @@ func (l *LakeBTC) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.
}
// GetOrderbookEx returns orderbook base on the currency pair
func (l *LakeBTC) GetOrderbookEx(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
ob, err := orderbook.GetOrderbook(l.GetName(), p, assetType)
func (l *LakeBTC) GetOrderbookEx(p currency.Pair, assetType string) (orderbook.Base, error) {
ob, err := orderbook.Get(l.GetName(), p, assetType)
if err != nil {
return l.UpdateOrderbook(p, assetType)
}
@@ -85,9 +94,9 @@ func (l *LakeBTC) GetOrderbookEx(p pair.CurrencyPair, assetType string) (orderbo
}
// UpdateOrderbook updates and returns the orderbook for a currency pair
func (l *LakeBTC) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
func (l *LakeBTC) UpdateOrderbook(p currency.Pair, assetType string) (orderbook.Base, error) {
var orderBook orderbook.Base
orderbookNew, err := l.GetOrderBook(p.Pair().String())
orderbookNew, err := l.GetOrderBook(p.String())
if err != nil {
return orderBook, err
}
@@ -100,8 +109,16 @@ func (l *LakeBTC) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderb
orderBook.Asks = append(orderBook.Asks, orderbook.Item{Amount: orderbookNew.Asks[x].Amount, Price: orderbookNew.Asks[x].Price})
}
orderbook.ProcessOrderbook(l.GetName(), p, orderBook, assetType)
return orderbook.GetOrderbook(l.Name, p, assetType)
orderBook.Pair = p
orderBook.ExchangeName = l.GetName()
orderBook.AssetType = assetType
err = orderBook.Process()
if err != nil {
return orderBook, err
}
return orderbook.Get(l.Name, p, assetType)
}
// GetAccountInfo retrieves balances for all enabled currencies for the
@@ -121,7 +138,7 @@ func (l *LakeBTC) GetAccountInfo() (exchange.AccountInfo, error) {
continue
}
var exchangeCurrency exchange.AccountCurrencyInfo
exchangeCurrency.CurrencyName = common.StringToUpper(x)
exchangeCurrency.CurrencyName = currency.NewCode(x)
exchangeCurrency.TotalValue, _ = strconv.ParseFloat(y, 64)
exchangeCurrency.Hold, _ = strconv.ParseFloat(w, 64)
currencies = append(currencies, exchangeCurrency)
@@ -143,17 +160,17 @@ func (l *LakeBTC) GetFundingHistory() ([]exchange.FundHistory, error) {
}
// GetExchangeHistory returns historic trade data since exchange opening.
func (l *LakeBTC) GetExchangeHistory(p pair.CurrencyPair, assetType string) ([]exchange.TradeHistory, error) {
func (l *LakeBTC) GetExchangeHistory(p currency.Pair, assetType string) ([]exchange.TradeHistory, error) {
var resp []exchange.TradeHistory
return resp, common.ErrNotYetImplemented
}
// SubmitOrder submits a new order
func (l *LakeBTC) SubmitOrder(p pair.CurrencyPair, side exchange.OrderSide, _ exchange.OrderType, amount, price float64, _ string) (exchange.SubmitOrderResponse, error) {
func (l *LakeBTC) SubmitOrder(p currency.Pair, side exchange.OrderSide, _ exchange.OrderType, amount, price float64, _ string) (exchange.SubmitOrderResponse, error) {
var submitOrderResponse exchange.SubmitOrderResponse
isBuyOrder := side == exchange.BuyOrderSide
response, err := l.Trade(isBuyOrder, amount, price, common.StringToLower(p.Pair().String()))
response, err := l.Trade(isBuyOrder, amount, price, p.Lower().String())
if response.ID > 0 {
submitOrderResponse.OrderID = fmt.Sprintf("%v", response.ID)
@@ -210,8 +227,8 @@ func (l *LakeBTC) GetOrderInfo(orderID string) (exchange.OrderDetail, error) {
}
// GetDepositAddress returns a deposit address for a specified currency
func (l *LakeBTC) GetDepositAddress(cryptocurrency pair.CurrencyItem, _ string) (string, error) {
if !strings.EqualFold(cryptocurrency.String(), symbol.BTC) {
func (l *LakeBTC) GetDepositAddress(cryptocurrency currency.Code, _ string) (string, error) {
if !strings.EqualFold(cryptocurrency.String(), currency.BTC.String()) {
return "", fmt.Errorf("unsupported currency %s deposit address can only be BTC, manual deposit is required for other currencies",
cryptocurrency.String())
}
@@ -227,8 +244,8 @@ func (l *LakeBTC) GetDepositAddress(cryptocurrency pair.CurrencyItem, _ string)
// WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is
// submitted
func (l *LakeBTC) WithdrawCryptocurrencyFunds(withdrawRequest exchange.WithdrawRequest) (string, error) {
if withdrawRequest.Currency.String() != symbol.BTC {
return "", errors.New("only BTC is supported for withdrawals")
if withdrawRequest.Currency != currency.BTC {
return "", errors.New("only BTC supported for withdrawals")
}
resp, err := l.CreateWithdraw(withdrawRequest.Amount, withdrawRequest.Description)
@@ -271,7 +288,7 @@ func (l *LakeBTC) GetActiveOrders(getOrdersRequest exchange.GetOrdersRequest) ([
var orders []exchange.OrderDetail
for _, order := range resp {
symbol := pair.NewCurrencyPairDelimiter(order.Symbol, l.ConfigCurrencyPairFormat.Delimiter)
symbol := currency.NewPairDelimiter(order.Symbol, l.ConfigCurrencyPairFormat.Delimiter)
orderDate := time.Unix(order.At, 0)
side := exchange.OrderSide(strings.ToUpper(order.Type))
@@ -307,7 +324,8 @@ func (l *LakeBTC) GetOrderHistory(getOrdersRequest exchange.GetOrdersRequest) ([
continue
}
symbol := pair.NewCurrencyPairDelimiter(order.Symbol, l.ConfigCurrencyPairFormat.Delimiter)
symbol := currency.NewPairDelimiter(order.Symbol,
l.ConfigCurrencyPairFormat.Delimiter)
orderDate := time.Unix(order.At, 0)
side := exchange.OrderSide(strings.ToUpper(order.Type))
@@ -322,7 +340,8 @@ func (l *LakeBTC) GetOrderHistory(getOrdersRequest exchange.GetOrdersRequest) ([
})
}
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks,
getOrdersRequest.EndTicks)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
exchange.FilterOrdersByCurrencies(&orders, getOrdersRequest.Currencies)