Skip to content

Commit

Permalink
Fixed linter issues and added test files
Browse files Browse the repository at this point in the history
  • Loading branch information
shazbert authored and thrasher- committed Jul 31, 2017
1 parent f302efe commit 7042da1
Show file tree
Hide file tree
Showing 16 changed files with 230 additions and 39 deletions.
7 changes: 6 additions & 1 deletion config_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"github.com/thrasher-/gocryptotrader/config"
)

// GetAllSettings replies to a request with an encoded JSON response about the
// trading bots configuration.
func GetAllSettings(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
Expand All @@ -15,6 +17,8 @@ func GetAllSettings(w http.ResponseWriter, r *http.Request) {
}
}

// SaveAllSettings saves all current settings from request body as a JSON
// document then reloads state and returns the settings
func SaveAllSettings(w http.ResponseWriter, r *http.Request) {
//Get the data from the request
decoder := json.NewDecoder(r.Body)
Expand All @@ -24,7 +28,7 @@ func SaveAllSettings(w http.ResponseWriter, r *http.Request) {
panic(jsonerr)
}
//Save change the settings
for x, _ := range bot.config.Exchanges {
for x := range bot.config.Exchanges {
for i := 0; i < len(responseData.Data.Exchanges); i++ {
if responseData.Data.Exchanges[i].Name == bot.config.Exchanges[x].Name {
bot.config.Exchanges[x].Enabled = responseData.Data.Exchanges[i].Enabled
Expand Down Expand Up @@ -52,6 +56,7 @@ func SaveAllSettings(w http.ResponseWriter, r *http.Request) {
}
}

// ConfigRoutes declares the current routes for config_routes.go
var ConfigRoutes = Routes{
Route{
"GetAllSettings",
Expand Down
26 changes: 20 additions & 6 deletions exchanges/exchange.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,26 @@ import (
)

const (
WarningBase64DecryptSecretKeyFailed = "WARNING -- Exchange %s unable to base64 decode secret key.. Disabling Authenticated API support."
ErrExchangeNotFound = "Exchange not found in dataset."
warningBase64DecryptSecretKeyFailed = "WARNING -- Exchange %s unable to base64 decode secret key.. Disabling Authenticated API support."
// ErrExchangeNotFound is a constant for an error message
ErrExchangeNotFound = "Exchange not found in dataset."
)

//ExchangeAccountInfo : Generic type to hold each exchange's holdings in all enabled currencies
// ExchangeAccountInfo is a Generic type to hold each exchange's holdings in
// all enabled currencies
type ExchangeAccountInfo struct {
ExchangeName string
Currencies []ExchangeAccountCurrencyInfo
}

//ExchangeAccountCurrencyInfo : Sub type to store currency name and value
// ExchangeAccountCurrencyInfo is a sub type to store currency name and value
type ExchangeAccountCurrencyInfo struct {
CurrencyName string
TotalValue float64
Hold float64
}

// ExchangeBase stores the individual exchange information
type ExchangeBase struct {
Name string
Enabled bool
Expand All @@ -45,7 +48,8 @@ type ExchangeBase struct {
APIUrl string
}

//IBotExchange : Enforces standard functions for all exchanges supported in gocryptotrader
// IBotExchange enforces standard functions for all exchanges supported in
// GoCryptoTrader
type IBotExchange interface {
Setup(exch config.ExchangeConfig)
Start()
Expand All @@ -58,20 +62,28 @@ type IBotExchange interface {
GetExchangeAccountInfo() (ExchangeAccountInfo, error)
}

// GetName is a method that returns the name of the exchange base
func (e *ExchangeBase) GetName() string {
return e.Name
}

// GetEnabledCurrencies is a method that returns the enabled currency pairs of
// the exchange base
func (e *ExchangeBase) GetEnabledCurrencies() []string {
return e.EnabledPairs
}

// SetEnabled is a method that sets if the exchange is enabled
func (e *ExchangeBase) SetEnabled(enabled bool) {
e.Enabled = enabled
}

// IsEnabled is a method that returns if the current exchange is enabled
func (e *ExchangeBase) IsEnabled() bool {
return e.Enabled
}

// SetAPIKeys is a method that sets the current API keys for the exchange
func (e *ExchangeBase) SetAPIKeys(APIKey, APISecret, ClientID string, b64Decode bool) {
e.APIKey = APIKey
e.ClientID = ClientID
Expand All @@ -80,14 +92,16 @@ func (e *ExchangeBase) SetAPIKeys(APIKey, APISecret, ClientID string, b64Decode
result, err := common.Base64Decode(APISecret)
if err != nil {
e.AuthenticatedAPISupport = false
log.Printf(WarningBase64DecryptSecretKeyFailed, e.Name)
log.Printf(warningBase64DecryptSecretKeyFailed, e.Name)
}
e.APISecret = string(result)
} else {
e.APISecret = APISecret
}
}

// UpdateAvailableCurrencies is a method that sets new pairs to the current
// exchange
func (e *ExchangeBase) UpdateAvailableCurrencies(exchangeProducts []string) error {
exchangeProducts = common.SplitStrings(common.StringToUpper(common.JoinStrings(exchangeProducts, ",")), ",")
diff := common.StringSliceDifference(e.AvailablePairs, exchangeProducts)
Expand Down
16 changes: 7 additions & 9 deletions exchanges/exchange_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,25 +60,23 @@ func TestSetAPIKeys(t *testing.T) {
}

SetAPIKeys.SetAPIKeys("RocketMan", "Digereedoo", "007", false)

if SetAPIKeys.APIKey != "RocketMan" && SetAPIKeys.APISecret != "Digereedoo" && SetAPIKeys.ClientID != "007" {
t.Error("Test Failed - Exchange SetAPIKeys() did not set correct values")
}

SetAPIKeys.SetAPIKeys("RocketMan", "Digereedoo", "007", true)
}

func TestUpdateAvailableCurrencies(t *testing.T) {
cfg := config.GetConfig()
err := cfg.LoadConfig(config.ConfigTestFile)
if err != nil {
t.Log("SOMETHING DONE HAPPENED!")
}

UAC := ExchangeBase{
Name: "ANX",
}
UAC := ExchangeBase{Name: "ANX"}
exchangeProducts := []string{"ltc", "btc", "usd", "aud"}

if err != nil {
t.Error(
"Test Failed - Exchange UpdateAvailableCurrencies() did not set correct values",
)
}
err2 := UAC.UpdateAvailableCurrencies(exchangeProducts)
if err2 != nil {
t.Errorf("Test Failed - Exchange UpdateAvailableCurrencies() error: %s", err2)
Expand Down
51 changes: 42 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/thrasher-/gocryptotrader/smsglobal"
)

// ExchangeMain contains all the necessary exchange packages
type ExchangeMain struct {
anx anx.ANX
btcc btcc.BTCC
Expand All @@ -56,6 +57,8 @@ type ExchangeMain struct {
kraken kraken.Kraken
}

// Bot contains configuration, portfolio, exchange & ticker data and is the
// overarching type across this code base.
type Bot struct {
config *config.Config
portfolio *portfolio.Base
Expand All @@ -74,10 +77,18 @@ func setupBotExchanges() {
if bot.exchanges[i].GetName() == exch.Name {
bot.exchanges[i].Setup(exch)
if bot.exchanges[i].IsEnabled() {
log.Printf("%s: Exchange support: %s (Authenticated API support: %s - Verbose mode: %s).\n", exch.Name, common.IsEnabled(exch.Enabled), common.IsEnabled(exch.AuthenticatedAPISupport), common.IsEnabled(exch.Verbose))
log.Printf(
"%s: Exchange support: %s (Authenticated API support: %s - Verbose mode: %s).\n",
exch.Name, common.IsEnabled(exch.Enabled),
common.IsEnabled(exch.AuthenticatedAPISupport),
common.IsEnabled(exch.Verbose),
)
bot.exchanges[i].Start()
} else {
log.Printf("%s: Exchange support: %s\n", exch.Name, common.IsEnabled(exch.Enabled))
log.Printf(
"%s: Exchange support: %s\n", exch.Name,
common.IsEnabled(exch.Enabled),
)
}
}
}
Expand All @@ -104,13 +115,19 @@ func main() {
log.Println(err) // non fatal event
bot.config.SMS.Enabled = false
} else {
log.Printf("SMS support enabled. Number of SMS contacts %d.\n", smsglobal.GetEnabledSMSContacts(bot.config.SMS))
log.Printf(
"SMS support enabled. Number of SMS contacts %d.\n",
smsglobal.GetEnabledSMSContacts(bot.config.SMS),
)
}
} else {
log.Println("SMS support disabled.")
}

log.Printf("Available Exchanges: %d. Enabled Exchanges: %d.\n", len(bot.config.Exchanges), bot.config.GetConfigEnabledExchanges())
log.Printf(
"Available Exchanges: %d. Enabled Exchanges: %d.\n",
len(bot.config.Exchanges), bot.config.GetConfigEnabledExchanges(),
)
log.Println("Bot Exchange support:")

bot.exchanges = []exchange.IBotExchange{
Expand All @@ -137,7 +154,10 @@ func main() {
for i := 0; i < len(bot.exchanges); i++ {
if bot.exchanges[i] != nil {
bot.exchanges[i].SetDefaults()
log.Printf("Exchange %s successfully set default settings.\n", bot.exchanges[i].GetName())
log.Printf(
"Exchange %s successfully set default settings.\n",
bot.exchanges[i].GetName(),
)
}
}

Expand All @@ -164,7 +184,10 @@ func main() {
//bot.config.Webserver.Enabled = false
} else {
listenAddr := bot.config.Webserver.ListenAddress
log.Printf("HTTP Webserver support enabled. Listen URL: http://%s:%d/\n", common.ExtractHost(listenAddr), common.ExtractPort(listenAddr))
log.Printf(
"HTTP Webserver support enabled. Listen URL: http://%s:%d/\n",
common.ExtractHost(listenAddr), common.ExtractPort(listenAddr),
)
router := NewRouter(bot.exchanges)
log.Fatal(http.ListenAndServe(listenAddr, router))
}
Expand All @@ -177,6 +200,7 @@ func main() {
Shutdown()
}

// AdjustGoMaxProcs adjusts the maximum processes that the CPU can handle.
func AdjustGoMaxProcs() {
log.Println("Adjusting bot runtime performance..")
maxProcsEnv := os.Getenv("GOMAXPROCS")
Expand All @@ -186,17 +210,20 @@ func AdjustGoMaxProcs() {
if maxProcsEnv != "" {
log.Println("GOMAXPROCS env =", maxProcsEnv)
env, err := strconv.Atoi(maxProcsEnv)

if err != nil {
log.Println("Unable to convert GOMAXPROCS to int, using", maxProcs)
} else {
maxProcs = env
}
}
if i := runtime.GOMAXPROCS(maxProcs); i != maxProcs {
log.Fatal("Go Max Procs were not set correctly.")
}
log.Println("Set GOMAXPROCS to:", maxProcs)
runtime.GOMAXPROCS(maxProcs)
}

// HandleInterrupt monitors and captures the SIGTERM in a new goroutine then
// shuts down bot
func HandleInterrupt() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
Expand All @@ -207,6 +234,7 @@ func HandleInterrupt() {
}()
}

// Shutdown correctly shuts down bot saving configuration files
func Shutdown() {
log.Println("Bot shutting down..")
bot.config.Portfolio = portfolio.Portfolio
Expand All @@ -222,6 +250,7 @@ func Shutdown() {
os.Exit(1)
}

// SeedExchangeAccountInfo seeds account info
func SeedExchangeAccountInfo(data []exchange.ExchangeAccountInfo) {
if len(data) == 0 {
return
Expand All @@ -242,7 +271,11 @@ func SeedExchangeAccountInfo(data []exchange.ExchangeAccountInfo) {
}

if !port.ExchangeAddressExists(exchangeName, currencyName) {
port.Addresses = append(port.Addresses, portfolio.Address{Address: exchangeName, CoinType: currencyName, Balance: total, Decscription: portfolio.PortfolioAddressExchange})
port.Addresses = append(
port.Addresses,
portfolio.Address{Address: exchangeName, CoinType: currencyName,
Balance: total, Decscription: portfolio.PortfolioAddressExchange},
)
} else {
port.UpdateExchangeAddressBalance(exchangeName, currencyName, total)
}
Expand Down
27 changes: 27 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import "testing"

func TestSetupBotExchanges(t *testing.T) {
// setupBotExchanges()
}

func TestMain(t *testing.T) {
// Nothing
}

func TestAdjustGoMaxProcs(t *testing.T) {
AdjustGoMaxProcs()
}

func TestHandleInterrupt(t *testing.T) {
HandleInterrupt()
}

func TestShutdown(t *testing.T) {
// Nothing
}

func TestSeedExchangeAccountInfo(t *testing.T) {
SeedExchangeAccountInfo(GetAllEnabledExchangeAccountInfo().Data)
}
22 changes: 14 additions & 8 deletions orders.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package main

const (
LIMIT_ORDER = iota
MARKET_ORDER
limitOrder = iota
marketOrder
)

// Orders variable holds an array of pointers to order structs
var Orders []*Order

// Order struct holds order values
type Order struct {
OrderID int
Exchange string
Expand All @@ -15,6 +17,7 @@ type Order struct {
Price float64
}

// NewOrder creates a new order and returns a an orderID
func NewOrder(Exchange string, amount, price float64) int {
order := &Order{}
if len(Orders) == 0 {
Expand All @@ -30,6 +33,7 @@ func NewOrder(Exchange string, amount, price float64) int {
return order.OrderID
}

// DeleteOrder deletes orders by ID and returns state
func DeleteOrder(orderID int) bool {
for i := range Orders {
if Orders[i].OrderID == orderID {
Expand All @@ -40,24 +44,26 @@ func DeleteOrder(orderID int) bool {
return false
}

func GetOrdersByExchange(exchange string) ([]*Order, bool) {
// GetOrdersByExchange returns order pointer grouped by exchange
func GetOrdersByExchange(exchange string) []*Order {
orders := []*Order{}
for i := range Orders {
if Orders[i].Exchange == exchange {
orders = append(orders, Orders[i])
}
}
if len(orders) > 0 {
return orders, true
return orders
}
return nil, false
return nil
}

func GetOrderByOrderID(orderID int) (*Order, bool) {
// GetOrderByOrderID returns order pointer by ID
func GetOrderByOrderID(orderID int) *Order {
for i := range Orders {
if Orders[i].OrderID == orderID {
return Orders[i], true
return Orders[i]
}
}
return nil, false
return nil
}
Loading

0 comments on commit 7042da1

Please sign in to comment.