bbgo_origin/pkg/cmd/sync.go

114 lines
2.2 KiB
Go
Raw Normal View History

2020-11-05 06:12:19 +00:00
package cmd
import (
"context"
"os"
2020-11-05 06:12:19 +00:00
"time"
"github.com/pkg/errors"
2020-11-06 16:49:17 +00:00
log "github.com/sirupsen/logrus"
2020-11-05 06:12:19 +00:00
"github.com/spf13/cobra"
"github.com/c9s/bbgo/pkg/bbgo"
2020-11-05 06:12:19 +00:00
)
func init() {
SyncCmd.Flags().String("session", "", "the exchange session name for sync")
SyncCmd.Flags().String("symbol", "", "symbol of market for syncing")
2020-11-05 06:12:19 +00:00
SyncCmd.Flags().String("since", "", "sync from time")
RootCmd.AddCommand(SyncCmd)
}
var SyncCmd = &cobra.Command{
Use: "sync",
Short: "sync trades, orders",
2020-11-05 06:12:19 +00:00
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
configFile, err := cmd.Flags().GetString("config")
2020-11-05 06:12:19 +00:00
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)
2020-11-05 06:12:19 +00:00
if err != nil {
return err
}
since, err := cmd.Flags().GetString("since")
2020-11-05 06:12:19 +00:00
if err != nil {
return err
}
environ := bbgo.NewEnvironment()
2021-02-20 16:58:34 +00:00
if err := environ.ConfigureDatabase(ctx) ; err != nil {
return err
2020-11-05 06:12:19 +00:00
}
2021-02-21 08:52:47 +00:00
if err := environ.ConfigureExchangeSessions(userConfig); err != nil {
2020-11-05 06:12:19 +00:00
return err
}
var (
2021-02-20 03:29:33 +00:00
// default sync start time
startTime = time.Now().AddDate(-1, 0, 0)
2020-11-05 06:12:19 +00:00
)
if len(since) > 0 {
loc, err := time.LoadLocation("Asia/Taipei")
if err != nil {
return err
}
startTime, err = time.ParseInLocation("2006-01-02", since, loc)
if err != nil {
return err
}
}
sessionName, err := cmd.Flags().GetString("session")
if err != nil {
return err
}
symbol, err := cmd.Flags().GetString("symbol")
if err != nil {
return err
}
2021-02-20 03:29:33 +00:00
environ.SetSyncStartTime(startTime)
2021-02-18 14:40:46 +00:00
var defaultSymbols []string
if len(symbol) > 0 {
2021-02-18 14:40:46 +00:00
defaultSymbols = []string{symbol}
}
2021-02-18 14:40:46 +00:00
var selectedSessions []string
2021-02-18 14:40:46 +00:00
if len(sessionName) > 0 {
selectedSessions = []string{sessionName}
}
2020-11-06 16:49:17 +00:00
2021-02-18 14:40:46 +00:00
sessions := environ.SelectSessions(selectedSessions...)
for _, session := range sessions {
2021-02-20 03:29:33 +00:00
if err := environ.SyncSession(ctx, session, defaultSymbols...); err != nil {
return err
}
2021-02-18 14:40:46 +00:00
log.Infof("exchange session %s synchronization done", session.Name)
2020-11-06 16:49:17 +00:00
}
2020-11-05 06:12:19 +00:00
return nil
},
}