From 22a980932785b7a15091e4a6bafde9135541ad47 Mon Sep 17 00:00:00 2001 From: c9s Date: Sun, 14 Mar 2021 10:31:53 +0800 Subject: [PATCH] improve balances command --- pkg/cmd/balances.go | 73 +++++++++++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 19 deletions(-) diff --git a/pkg/cmd/balances.go b/pkg/cmd/balances.go index c9b8f2798..27c011490 100644 --- a/pkg/cmd/balances.go +++ b/pkg/cmd/balances.go @@ -3,37 +3,72 @@ package cmd import ( "context" "fmt" + "os" + "github.com/pkg/errors" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" + + "github.com/c9s/bbgo/pkg/bbgo" ) -//godotenv -f .env.local go run ./cmd/bbgo balances --session=ftx +func init() { + balancesCmd.Flags().String("session", "", "the exchange session name for querying balances") + RootCmd.AddCommand(balancesCmd) +} + +// go run ./cmd/bbgo balances --session=ftx var balancesCmd = &cobra.Command{ Use: "balances", SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { ctx := context.Background() - session, err := cmd.Flags().GetString("session") - if err != nil { - return fmt.Errorf("can't get session from flags: %w", err) - } - ex, err := newExchange(session) - if err != nil { - return err - } - b, err := ex.QueryAccountBalances(ctx) - if err != nil { - return err - } - log.Infof("balances: %+v", b) + configFile, err := cmd.Flags().GetString("config") + if err != nil { + return err + } + + if len(configFile) == 0 { + return errors.New("--config option is required") + } + + if _, err := os.Stat(configFile); os.IsNotExist(err) { + return err + } + + userConfig, err := bbgo.Load(configFile, false) + if err != nil { + return err + } + + + environ := bbgo.NewEnvironment() + if err := environ.ConfigureDatabase(ctx) ; err != nil { + return err + } + + if err := environ.ConfigureExchangeSessions(userConfig); err != nil { + return err + } + + sessionName, err := cmd.Flags().GetString("session") + if err != nil { + return err + } + + session, ok := environ.Session(sessionName) + if !ok { + return fmt.Errorf("session %s not found", sessionName) + } + + b, err := session.Exchange.QueryAccountBalances(ctx) + if err != nil { + return err + } + + log.Infof("balances: %+v", b) return nil }, } -func init() { - balancesCmd.Flags().String("session", "", "the exchange session name for sync") - - RootCmd.AddCommand(balancesCmd) -}