move commands into pkg/cmd

This commit is contained in:
c9s 2020-10-23 14:28:07 +08:00
parent 0ec57cf404
commit 048374566c
6 changed files with 58 additions and 60 deletions

View File

@ -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() {

View File

@ -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()

View File

@ -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)

View File

@ -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")
}
}

View File

@ -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)
}

View File

@ -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