From 048374566c631c5f6c4b4cce4a294d2ff809f611 Mon Sep 17 00:00:00 2001 From: c9s Date: Fri, 23 Oct 2020 14:28:07 +0800 Subject: [PATCH] move commands into pkg/cmd --- cmd/bbgo/main.go | 3 +-- {cmd => pkg/cmd}/migrate.go | 14 +++++----- {cmd => pkg/cmd}/pnl.go | 23 ++++++++-------- {cmd => pkg/cmd}/root.go | 36 +++++++++++++------------ {cmd => pkg/cmd}/run.go | 18 ++++++------- cmd/transfers.go => pkg/cmd/transfer.go | 24 ++++++++--------- 6 files changed, 58 insertions(+), 60 deletions(-) rename {cmd => pkg/cmd}/migrate.go (82%) rename {cmd => pkg/cmd}/pnl.go (79%) rename {cmd => pkg/cmd}/root.go (75%) rename {cmd => pkg/cmd}/run.go (81%) rename cmd/transfers.go => pkg/cmd/transfer.go (82%) diff --git a/cmd/bbgo/main.go b/cmd/bbgo/main.go index 5b4a66841..d803b7ff2 100644 --- a/cmd/bbgo/main.go +++ b/cmd/bbgo/main.go @@ -1,9 +1,8 @@ package main import ( - "github.com/c9s/bbgo/cmd" + "github.com/c9s/bbgo/pkg/cmd" - _ "github.com/go-sql-driver/mysql" ) func main() { diff --git a/cmd/migrate.go b/pkg/cmd/migrate.go similarity index 82% rename from cmd/migrate.go rename to pkg/cmd/migrate.go index dbb4924c6..8814c5545 100644 --- a/cmd/migrate.go +++ b/pkg/cmd/migrate.go @@ -8,7 +8,7 @@ import ( "path" "github.com/c9s/goose" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -44,32 +44,32 @@ var MigrateCmd = &cobra.Command{ sourceDir := bbgo.SourceDir() migrationDir := path.Join(sourceDir, "migrations") - log.Infof("creating dir: %s", dotDir) + logrus.Infof("creating dir: %s", dotDir) if err := os.Mkdir(dotDir, 0777); err != nil { // return err } - log.Infof("checking %s", sourceDir) + logrus.Infof("checking %s", sourceDir) _, err = os.Stat(sourceDir) if err != nil { - log.Infof("cloning bbgo source into %s ...", sourceDir) + logrus.Infof("cloning bbgo source into %s ...", sourceDir) cmd := exec.CommandContext(ctx, "git", "clone", "https://github.com/c9s/bbgo", sourceDir) if err := cmd.Run(); err != nil { return err } } else if !noUpdate { - log.Infof("updating: %s ...", sourceDir) + logrus.Infof("updating: %s ...", sourceDir) cmd := exec.CommandContext(ctx, "git", "--work-tree", sourceDir, "pull") if err := cmd.Run(); err != nil { return err } } - log.Infof("using migration file dir: %s", migrationDir) + logrus.Infof("using migration file dir: %s", migrationDir) command := args[0] if err := goose.Run(command, db, migrationDir); err != nil { - log.Fatalf("goose run: %v", err) + logrus.Fatalf("goose run: %v", err) } defer db.Close() diff --git a/cmd/pnl.go b/pkg/cmd/pnl.go similarity index 79% rename from cmd/pnl.go rename to pkg/cmd/pnl.go index 95be2f385..17040ab2e 100644 --- a/cmd/pnl.go +++ b/pkg/cmd/pnl.go @@ -5,7 +5,7 @@ import ( "strings" "time" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/c9s/bbgo/pkg/accounting" @@ -16,13 +16,13 @@ import ( ) func init() { - pnlCmd.Flags().String("exchange", "", "target exchange") - pnlCmd.Flags().String("symbol", "BTCUSDT", "trading symbol") - pnlCmd.Flags().String("since", "", "pnl since time") - RootCmd.AddCommand(pnlCmd) + PnLCmd.Flags().String("exchange", "", "target exchange") + PnLCmd.Flags().String("symbol", "BTCUSDT", "trading symbol") + PnLCmd.Flags().String("since", "", "pnl since time") + RootCmd.AddCommand(PnLCmd) } -var pnlCmd = &cobra.Command{ +var PnLCmd = &cobra.Command{ Use: "pnl", Short: "pnl calculator", SilenceUsage: true, @@ -75,7 +75,7 @@ var pnlCmd = &cobra.Command{ tradeService := &service.TradeService{DB: db} tradeSync := &service.TradeSync{Service: tradeService} - log.Info("syncing trades from exchange...") + logrus.Info("syncing trades from exchange...") if err := tradeSync.Sync(ctx, exchange, symbol, startTime); err != nil { return err } @@ -83,7 +83,7 @@ var pnlCmd = &cobra.Command{ var trades []types.Trade tradingFeeCurrency := exchange.PlatformFeeCurrency() if strings.HasPrefix(symbol, tradingFeeCurrency) { - log.Infof("loading all trading fee currency related trades: %s", symbol) + logrus.Infof("loading all trading fee currency related trades: %s", symbol) trades, err = tradeService.QueryForTradingFeeCurrency(symbol, tradingFeeCurrency) } else { trades, err = tradeService.Query(symbol) @@ -93,7 +93,7 @@ var pnlCmd = &cobra.Command{ return err } - log.Infof("%d trades loaded", len(trades)) + logrus.Infof("%d trades loaded", len(trades)) stockManager := &accounting.StockDistribution{ Symbol: symbol, @@ -105,14 +105,13 @@ var pnlCmd = &cobra.Command{ return err } - log.Infof("found checkpoints: %+v", checkpoints) - log.Infof("stock: %f", stockManager.Stocks.Quantity()) + logrus.Infof("found checkpoints: %+v", checkpoints) + logrus.Infof("stock: %f", stockManager.Stocks.Quantity()) currentPrice, err := exchange.QueryAveragePrice(ctx, symbol) calculator := &pnl.AverageCostCalculator{ TradingFeeCurrency: tradingFeeCurrency, - StartTime: startTime, } report := calculator.Calculate(symbol, trades, currentPrice) diff --git a/cmd/root.go b/pkg/cmd/root.go similarity index 75% rename from cmd/root.go rename to pkg/cmd/root.go index 937a1fc4d..9a15a01f6 100644 --- a/cmd/root.go +++ b/pkg/cmd/root.go @@ -6,12 +6,14 @@ import ( "strings" "time" - rotatelogs "github.com/lestrrat-go/file-rotatelogs" + "github.com/lestrrat-go/file-rotatelogs" "github.com/rifflock/lfshook" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" - prefixed "github.com/x-cray/logrus-prefixed-formatter" + "github.com/x-cray/logrus-prefixed-formatter" + + _ "github.com/go-sql-driver/mysql" ) var RootCmd = &cobra.Command{ @@ -61,23 +63,23 @@ func Run() { err := viper.ReadInConfig() if err != nil { - log.WithError(err).Fatal("failed to load config file") + logrus.WithError(err).Fatal("failed to load config file") } // Once the flags are defined, we can bind config keys with flags. if err := viper.BindPFlags(RootCmd.PersistentFlags()); err != nil { - log.WithError(err).Errorf("failed to bind persistent flags. please check the flag settings.") + logrus.WithError(err).Errorf("failed to bind persistent flags. please check the flag settings.") } if err := viper.BindPFlags(RootCmd.Flags()); err != nil { - log.WithError(err).Errorf("failed to bind local flags. please check the flag settings.") + logrus.WithError(err).Errorf("failed to bind local flags. please check the flag settings.") } - log.SetFormatter(&prefixed.TextFormatter{}) + logrus.SetFormatter(&prefixed.TextFormatter{}) - logger := log.StandardLogger() + logger := logrus.StandardLogger() if viper.GetBool("debug") { - logger.SetLevel(log.DebugLevel) + logger.SetLevel(logrus.DebugLevel) } environment := os.Getenv("BBGO_ENV") @@ -91,23 +93,23 @@ func Run() { rotatelogs.WithRotationTime(time.Duration(24)*time.Hour), ) if err != nil { - log.Panic(err) + logrus.Panic(err) } logger.AddHook( lfshook.NewHook( lfshook.WriterMap{ - log.DebugLevel: writer, - log.InfoLevel: writer, - log.WarnLevel: writer, - log.ErrorLevel: writer, - log.FatalLevel: writer, + logrus.DebugLevel: writer, + logrus.InfoLevel: writer, + logrus.WarnLevel: writer, + logrus.ErrorLevel: writer, + logrus.FatalLevel: writer, }, - &log.JSONFormatter{}, + &logrus.JSONFormatter{}, ), ) } if err := RootCmd.Execute(); err != nil { - log.WithError(err).Fatalf("cannot execute command") + logrus.WithError(err).Fatalf("cannot execute command") } } diff --git a/cmd/run.go b/pkg/cmd/run.go similarity index 81% rename from cmd/run.go rename to pkg/cmd/run.go index d822d79ad..09e62a2bf 100644 --- a/cmd/run.go +++ b/pkg/cmd/run.go @@ -5,7 +5,7 @@ import ( "syscall" "github.com/pkg/errors" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -14,19 +14,17 @@ import ( "github.com/c9s/bbgo/pkg/config" "github.com/c9s/bbgo/pkg/notifier/slacknotifier" "github.com/c9s/bbgo/pkg/slack/slacklog" - - _ "github.com/c9s/bbgo/pkg/strategy/buyandhold" ) var errSlackTokenUndefined = errors.New("slack token is not defined.") func init() { - runCmd.Flags().String("config", "config/bbgo.yaml", "strategy config file") - runCmd.Flags().String("since", "", "pnl since time") - RootCmd.AddCommand(runCmd) + RunCmd.Flags().String("config", "config/bbgo.yaml", "strategy config file") + RunCmd.Flags().String("since", "", "pnl since time") + RootCmd.AddCommand(RunCmd) } -var runCmd = &cobra.Command{ +var RunCmd = &cobra.Command{ Use: "run", Short: "run strategies", @@ -56,7 +54,7 @@ var runCmd = &cobra.Command{ return errSlackTokenUndefined } - log.AddHook(slacklog.NewLogHook(slackToken, viper.GetString("slack-error-channel"))) + logrus.AddHook(slacklog.NewLogHook(slackToken, viper.GetString("slack-error-channel"))) var notifier = slacknotifier.New(slackToken, viper.GetString("slack-channel")) @@ -72,13 +70,13 @@ var runCmd = &cobra.Command{ for _, entry := range userConfig.ExchangeStrategies { for _, mount := range entry.Mounts { - log.Infof("attaching strategy %T on %s...", entry.Strategy, mount) + logrus.Infof("attaching strategy %T on %s...", entry.Strategy, mount) trader.AttachStrategyOn(mount, entry.Strategy) } } for _, strategy := range userConfig.CrossExchangeStrategies { - log.Infof("attaching strategy %T", strategy) + logrus.Infof("attaching strategy %T", strategy) trader.AttachCrossExchangeStrategy(strategy) } diff --git a/cmd/transfers.go b/pkg/cmd/transfer.go similarity index 82% rename from cmd/transfers.go rename to pkg/cmd/transfer.go index be533640e..4e4048aed 100644 --- a/cmd/transfers.go +++ b/pkg/cmd/transfer.go @@ -5,7 +5,7 @@ import ( "sort" "time" - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/c9s/bbgo/pkg/cmd/cmdutil" @@ -13,10 +13,10 @@ import ( ) func init() { - transferHistoryCmd.Flags().String("exchange", "", "target exchange") - transferHistoryCmd.Flags().String("asset", "", "trading symbol") - transferHistoryCmd.Flags().String("since", "", "since time") - RootCmd.AddCommand(transferHistoryCmd) + TransferHistoryCmd.Flags().String("exchange", "", "target exchange") + TransferHistoryCmd.Flags().String("asset", "", "trading symbol") + TransferHistoryCmd.Flags().String("since", "", "since time") + RootCmd.AddCommand(TransferHistoryCmd) } type timeRecord struct { @@ -38,7 +38,7 @@ func (p timeSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -var transferHistoryCmd = &cobra.Command{ +var TransferHistoryCmd = &cobra.Command{ Use: "transfer-history", Short: "show transfer history", @@ -116,28 +116,28 @@ var transferHistoryCmd = &cobra.Command{ switch record := record.Record.(type) { case types.Deposit: - log.Infof("%s: %s <== (deposit) %f [%s]", record.Time, record.Asset, record.Amount, record.Status) + logrus.Infof("%s: %s <== (deposit) %f [%s]", record.Time, record.Asset, record.Amount, record.Status) case types.Withdraw: - log.Infof("%s: %s ==> (withdraw) %f [%s]", record.ApplyTime, record.Asset, record.Amount, record.Status) + logrus.Infof("%s: %s ==> (withdraw) %f [%s]", record.ApplyTime, record.Asset, record.Amount, record.Status) default: - log.Infof("unknown record: %+v", record) + logrus.Infof("unknown record: %+v", record) } } stats := calBaselineStats(asset, deposits, withdraws) for asset, quantity := range stats.TotalDeposit { - log.Infof("total %s deposit: %f", asset, quantity) + logrus.Infof("total %s deposit: %f", asset, quantity) } for asset, quantity := range stats.TotalWithdraw { - log.Infof("total %s withdraw: %f", asset, quantity) + logrus.Infof("total %s withdraw: %f", asset, quantity) } for asset, quantity := range stats.BaselineBalance { - log.Infof("baseline %s balance: %f", asset, quantity) + logrus.Infof("baseline %s balance: %f", asset, quantity) } return nil