bbgo_origin/pkg/cmd/run.go

283 lines
6.8 KiB
Go
Raw Normal View History

package cmd
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"syscall"
"text/template"
"github.com/pkg/errors"
2020-10-24 07:43:55 +00:00
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/c9s/bbgo/pkg/bbgo"
2020-10-21 07:58:58 +00:00
"github.com/c9s/bbgo/pkg/cmd/cmdutil"
"github.com/c9s/bbgo/pkg/notifier/slacknotifier"
"github.com/c9s/bbgo/pkg/slack/slacklog"
2020-10-26 09:00:17 +00:00
"github.com/c9s/bbgo/pkg/types"
// import built-in strategies
_ "github.com/c9s/bbgo/pkg/strategy/buyandhold"
2020-10-24 10:22:23 +00:00
_ "github.com/c9s/bbgo/pkg/strategy/xpuremaker"
)
var errSlackTokenUndefined = errors.New("slack token is not defined.")
func init() {
RunCmd.Flags().Bool("no-compile", false, "do not compile wrapper binary")
RunCmd.Flags().String("os", runtime.GOOS, "GOOS")
RunCmd.Flags().String("arch", runtime.GOARCH, "GOARCH")
2020-10-23 06:28:07 +00:00
RunCmd.Flags().String("config", "config/bbgo.yaml", "strategy config file")
RunCmd.Flags().String("since", "", "pnl since time")
RootCmd.AddCommand(RunCmd)
}
2020-10-26 05:27:07 +00:00
var wrapperTemplate = template.Must(template.New("main").Parse(`package main
// DO NOT MODIFY THIS FILE. THIS FILE IS GENERATED FOR IMPORTING STRATEGIES
import (
"github.com/c9s/bbgo/pkg/cmd"
{{- range .Imports }}
_ "{{ . }}"
{{- end }}
)
func main() {
cmd.Execute()
}
`))
2020-10-26 13:45:02 +00:00
func compileRunFile(filepath string, config *bbgo.Config) error {
var buf = bytes.NewBuffer(nil)
2020-10-26 05:27:07 +00:00
if err := wrapperTemplate.Execute(buf, config); err != nil {
2020-10-23 06:49:54 +00:00
return err
}
return ioutil.WriteFile(filepath, buf.Bytes(), 0644)
}
2020-10-26 13:45:02 +00:00
func runConfig(ctx context.Context, userConfig *bbgo.Config) error {
// configure notifiers
2020-10-23 06:49:54 +00:00
slackToken := viper.GetString("slack-token")
if len(slackToken) > 0 {
2020-10-26 05:48:59 +00:00
log.Infof("found slack configured, setting up log hook...")
log.AddHook(slacklog.NewLogHook(slackToken, viper.GetString("slack-error-channel")))
2020-10-23 06:49:54 +00:00
}
notifierSet := &bbgo.Notifiability{}
if len(slackToken) > 0 {
2020-10-26 05:48:59 +00:00
log.Infof("adding slack notifier...")
var notifier = slacknotifier.New(slackToken, viper.GetString("slack-channel"))
notifierSet.AddNotifier(notifier)
}
2020-10-23 06:49:54 +00:00
db, err := cmdutil.ConnectMySQL()
if err != nil {
return err
}
2020-10-26 09:00:17 +00:00
environ := bbgo.NewEnvironment()
environ.SyncTrades(db)
2020-10-23 06:49:54 +00:00
trader := bbgo.NewTrader(environ)
trader.AddNotifier(notifierSet)
2020-10-23 06:49:54 +00:00
trader.ReportTrade()
2020-10-26 09:00:17 +00:00
if len(userConfig.Sessions) == 0 {
for _, n := range bbgo.SupportedExchanges {
if viper.IsSet(string(n) + "-api-key") {
exchange, err := cmdutil.NewExchangeWithEnvVarPrefix(n, "")
if err != nil {
panic(err)
}
environ.AddExchange(n.String(), exchange)
}
}
} else {
for sessionName, sessionConfig := range userConfig.Sessions {
exchangeName, err := types.ValidExchangeName(sessionConfig.ExchangeName)
if err != nil {
return err
}
exchange, err := cmdutil.NewExchangeWithEnvVarPrefix(exchangeName, sessionConfig.EnvVarPrefix)
if err != nil {
return err
}
environ.AddExchange(sessionName, exchange)
}
}
for _, entry := range userConfig.ExchangeStrategies {
2020-10-23 06:49:54 +00:00
for _, mount := range entry.Mounts {
2020-10-24 07:43:55 +00:00
log.Infof("attaching strategy %T on %s...", entry.Strategy, mount)
2020-10-23 06:49:54 +00:00
trader.AttachStrategyOn(mount, entry.Strategy)
}
}
for _, strategy := range userConfig.CrossExchangeStrategies {
2020-10-24 07:43:55 +00:00
log.Infof("attaching strategy %T", strategy)
2020-10-23 06:49:54 +00:00
trader.AttachCrossExchangeStrategy(strategy)
}
for _, report := range userConfig.PnLReporters {
2020-10-23 06:49:54 +00:00
if len(report.AverageCostBySymbols) > 0 {
2020-10-26 05:48:59 +00:00
log.Infof("setting up average cost pnl reporter on symbols: %v", report.AverageCostBySymbols)
2020-10-26 05:48:59 +00:00
trader.ReportPnL(notifierSet).
2020-10-23 06:49:54 +00:00
AverageCostBySymbols(report.AverageCostBySymbols...).
Of(report.Of...).
When(report.When...)
2020-10-26 05:48:59 +00:00
2020-10-23 06:49:54 +00:00
} else {
return errors.Errorf("unsupported PnL reporter: %+v", report)
}
}
return trader.Run(ctx)
}
2020-10-23 06:28:07 +00:00
var RunCmd = &cobra.Command{
Use: "run",
2020-10-23 06:49:54 +00:00
Short: "run strategies from config file",
// SilenceUsage is an option to silence usage when an error occurs.
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return err
}
if len(configFile) == 0 {
2020-10-23 06:49:54 +00:00
return errors.New("--config option is required")
}
noCompile, err := cmd.Flags().GetBool("no-compile")
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
2020-10-26 13:45:02 +00:00
userConfig, err := bbgo.Load(configFile)
if err != nil {
return err
}
// if there is no custom imports, we don't have to compile
if noCompile || len(userConfig.Imports) == 0 {
if err := runConfig(ctx, userConfig); err != nil {
return err
}
cmdutil.WaitForSignal(ctx, syscall.SIGINT, syscall.SIGTERM)
return nil
}
2020-10-26 05:27:07 +00:00
var runArgs = []string{"run", "--no-compile"}
cmd.Flags().Visit(func(flag *flag.Flag) {
2020-10-26 05:27:07 +00:00
runArgs = append(runArgs, flag.Name, flag.Value.String())
})
2020-10-26 05:27:07 +00:00
runArgs = append(runArgs, args...)
goOS, err := cmd.Flags().GetString("os")
if err != nil {
return err
}
goArch, err := cmd.Flags().GetString("arch")
if err != nil {
return err
}
2020-10-26 05:27:07 +00:00
return buildAndRun(ctx, userConfig, goOS, goArch, runArgs...)
},
}
2020-10-26 13:45:02 +00:00
func compile(buildDir string, userConfig *bbgo.Config) error {
if _, err := os.Stat(buildDir); os.IsNotExist(err) {
if err := os.MkdirAll(buildDir, 0777); err != nil {
return errors.Wrapf(err, "can not create build directory: %s", buildDir)
}
}
mainFile := filepath.Join(buildDir, "main.go")
if err := compileRunFile(mainFile, userConfig); err != nil {
return errors.Wrap(err, "compile error")
}
return nil
}
2020-10-26 13:45:02 +00:00
func build(ctx context.Context, buildDir string, userConfig *bbgo.Config, goOS, goArch string, output *string) (string, error) {
if err := compile(buildDir, userConfig); err != nil {
2020-10-26 05:27:07 +00:00
return "", err
}
cwd, err := os.Getwd()
if err != nil {
2020-10-26 05:27:07 +00:00
return "", err
}
2020-10-26 05:56:48 +00:00
buildEnvs := []string{
"GOOS=" + goOS,
"GOARCH=" + goArch,
}
buildTarget := filepath.Join(cwd, buildDir)
2020-10-26 05:56:48 +00:00
binary := fmt.Sprintf("bbgow-%s-%s", goOS, goArch)
2020-10-26 05:56:48 +00:00
if output != nil && len(*output) > 0 {
2020-10-26 05:27:07 +00:00
binary = *output
}
2020-10-26 05:56:48 +00:00
log.Infof("building binary %s from %s...", binary, buildTarget)
buildCmd := exec.CommandContext(ctx, "go", "build", "-tags", "wrapper", "-o", binary, buildTarget)
buildCmd.Env = append(os.Environ(), buildEnvs...)
buildCmd.Stdout = os.Stdout
buildCmd.Stderr = os.Stderr
if err := buildCmd.Run(); err != nil {
2020-10-26 05:56:48 +00:00
return binary, err
2020-10-26 05:27:07 +00:00
}
return binary, nil
}
2020-10-26 13:45:02 +00:00
func buildAndRun(ctx context.Context, userConfig *bbgo.Config, goOS, goArch string, args ...string) error {
2020-10-26 05:27:07 +00:00
buildDir := filepath.Join("build", "bbgow")
binary, err := build(ctx, buildDir, userConfig, goOS, goArch, nil)
if err != nil {
return err
}
cwd, err := os.Getwd()
if err != nil {
return err
}
executePath := filepath.Join(cwd, binary)
log.Infof("running wrapper binary, args: %v", args)
2020-10-26 05:27:07 +00:00
runCmd := exec.CommandContext(ctx, executePath, args...)
runCmd.Stdout = os.Stdout
runCmd.Stderr = os.Stderr
2020-10-26 05:27:07 +00:00
return runCmd.Run()
}