2020-11-06 18:57:50 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
2021-05-30 07:25:00 +00:00
|
|
|
"bufio"
|
2020-11-06 18:57:50 +00:00
|
|
|
"context"
|
2020-11-09 08:34:35 +00:00
|
|
|
"fmt"
|
2021-05-30 07:25:00 +00:00
|
|
|
"os"
|
2021-12-05 17:05:33 +00:00
|
|
|
"path/filepath"
|
2021-05-30 07:25:00 +00:00
|
|
|
"strings"
|
2022-03-16 10:25:27 +00:00
|
|
|
"syscall"
|
2020-11-06 18:57:50 +00:00
|
|
|
"time"
|
|
|
|
|
2022-12-06 05:16:12 +00:00
|
|
|
"github.com/fatih/color"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
2022-11-10 09:17:35 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/cmd/cmdutil"
|
2023-07-04 13:42:24 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/core"
|
2022-11-10 09:17:35 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/data/tsv"
|
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
|
|
|
|
2022-01-24 16:24:12 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
|
2020-11-07 12:34:34 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/accounting/pnl"
|
2020-11-06 18:57:50 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/backtest"
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2022-06-03 18:23:23 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/exchange"
|
2022-08-29 05:11:02 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2020-11-06 18:57:50 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/service"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2020-11-07 12:34:34 +00:00
|
|
|
BacktestCmd.Flags().Bool("sync", false, "sync backtest data")
|
2020-11-11 08:08:24 +00:00
|
|
|
BacktestCmd.Flags().Bool("sync-only", false, "sync backtest data only, do not run backtest")
|
2021-05-05 08:45:17 +00:00
|
|
|
BacktestCmd.Flags().String("sync-from", "", "sync backtest data from the given time, which will override the time range in the backtest config")
|
2022-05-03 04:12:39 +00:00
|
|
|
BacktestCmd.Flags().String("sync-exchange", "", "specify only one exchange to sync backtest data")
|
2022-05-09 11:14:09 +00:00
|
|
|
BacktestCmd.Flags().String("session", "", "specify only one exchange session to run backtest")
|
|
|
|
|
2021-12-07 07:21:37 +00:00
|
|
|
BacktestCmd.Flags().Bool("verify", false, "verify the kline back-test data")
|
|
|
|
|
2020-11-11 06:39:33 +00:00
|
|
|
BacktestCmd.Flags().Bool("base-asset-baseline", false, "use base asset performance as the competitive baseline performance")
|
2020-11-09 08:47:29 +00:00
|
|
|
BacktestCmd.Flags().CountP("verbose", "v", "verbose level")
|
2020-11-06 18:57:50 +00:00
|
|
|
BacktestCmd.Flags().String("config", "config/bbgo.yaml", "strategy config file")
|
2021-12-04 16:18:51 +00:00
|
|
|
BacktestCmd.Flags().Bool("force", false, "force execution without confirm")
|
2021-12-05 17:05:33 +00:00
|
|
|
BacktestCmd.Flags().String("output", "", "the report output directory")
|
2022-05-09 10:58:09 +00:00
|
|
|
BacktestCmd.Flags().Bool("subdir", false, "generate report in the sub-directory of the output directory")
|
2020-11-06 18:57:50 +00:00
|
|
|
RootCmd.AddCommand(BacktestCmd)
|
|
|
|
}
|
|
|
|
|
|
|
|
var BacktestCmd = &cobra.Command{
|
|
|
|
Use: "backtest",
|
2022-05-06 11:16:15 +00:00
|
|
|
Short: "run backtest with strategies",
|
2020-11-06 18:57:50 +00:00
|
|
|
SilenceUsage: true,
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2020-11-09 08:49:03 +00:00
|
|
|
verboseCnt, err := cmd.Flags().GetCount("verbose")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-23 15:02:07 +00:00
|
|
|
if viper.GetBool("debug") {
|
|
|
|
verboseCnt = 2
|
|
|
|
}
|
|
|
|
|
2020-11-06 18:57:50 +00:00
|
|
|
configFile, err := cmd.Flags().GetString("config")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(configFile) == 0 {
|
|
|
|
return errors.New("--config option is required")
|
|
|
|
}
|
|
|
|
|
2020-11-11 06:39:33 +00:00
|
|
|
wantBaseAssetBaseline, err := cmd.Flags().GetBool("base-asset-baseline")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-11-07 12:14:53 +00:00
|
|
|
wantSync, err := cmd.Flags().GetBool("sync")
|
2020-11-06 18:57:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-03 04:12:39 +00:00
|
|
|
syncExchangeName, err := cmd.Flags().GetString("sync-exchange")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-09 11:27:02 +00:00
|
|
|
sessionName, err := cmd.Flags().GetString("session")
|
2022-05-09 11:14:09 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-04 16:18:51 +00:00
|
|
|
force, err := cmd.Flags().GetBool("force")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-05 17:05:33 +00:00
|
|
|
outputDirectory, err := cmd.Flags().GetString("output")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-07 07:21:37 +00:00
|
|
|
|
2022-05-09 10:58:09 +00:00
|
|
|
generatingReport := len(outputDirectory) > 0
|
|
|
|
|
|
|
|
reportFileInSubDir, err := cmd.Flags().GetBool("subdir")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-06 11:16:15 +00:00
|
|
|
|
2020-11-11 08:08:24 +00:00
|
|
|
syncOnly, err := cmd.Flags().GetBool("sync-only")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
syncFromDateStr, err := cmd.Flags().GetString("sync-from")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-07 07:21:37 +00:00
|
|
|
shouldVerify, err := cmd.Flags().GetBool("verify")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-13 23:15:18 +00:00
|
|
|
userConfig, err := bbgo.Load(configFile, true)
|
2020-11-06 18:57:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-03-01 13:48:48 +00:00
|
|
|
if userConfig.Backtest == nil {
|
|
|
|
return errors.New("backtest config is not defined")
|
2020-11-08 04:47:14 +00:00
|
|
|
}
|
|
|
|
|
2021-12-13 23:15:18 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
|
2022-08-29 05:11:02 +00:00
|
|
|
var now = time.Now().Local()
|
2022-01-24 16:24:12 +00:00
|
|
|
var startTime, endTime time.Time
|
|
|
|
|
2022-08-29 05:11:02 +00:00
|
|
|
startTime = userConfig.Backtest.StartTime.Time().Local()
|
2022-01-24 16:24:12 +00:00
|
|
|
|
2020-11-06 19:18:05 +00:00
|
|
|
// set default start time to the past 6 months
|
2022-09-01 11:17:41 +00:00
|
|
|
// userConfig.Backtest.StartTime = now.AddDate(0, -6, 0).Format("2006-01-02")
|
2022-01-24 16:24:12 +00:00
|
|
|
if userConfig.Backtest.EndTime != nil {
|
2022-08-29 05:11:02 +00:00
|
|
|
endTime = userConfig.Backtest.EndTime.Time().Local()
|
2022-01-24 16:24:12 +00:00
|
|
|
} else {
|
|
|
|
endTime = now
|
2020-11-10 11:06:20 +00:00
|
|
|
}
|
|
|
|
|
2022-08-26 11:06:52 +00:00
|
|
|
// ensure that we're using local time
|
|
|
|
startTime = startTime.Local()
|
|
|
|
endTime = endTime.Local()
|
|
|
|
|
|
|
|
log.Infof("starting backtest with startTime %s", startTime.Format(time.RFC3339))
|
2021-05-05 08:45:17 +00:00
|
|
|
|
2021-01-15 02:47:49 +00:00
|
|
|
environ := bbgo.NewEnvironment()
|
2022-09-06 08:50:45 +00:00
|
|
|
if err := bbgo.BootstrapBacktestEnvironment(ctx, environ); err != nil {
|
2021-02-06 03:33:49 +00:00
|
|
|
return err
|
2021-01-15 02:47:49 +00:00
|
|
|
}
|
|
|
|
|
2021-03-22 14:48:43 +00:00
|
|
|
if environ.DatabaseService == nil {
|
|
|
|
return errors.New("database service is not enabled, please check your environment variables DB_DRIVER and DB_DSN")
|
|
|
|
}
|
|
|
|
|
2021-02-06 01:56:26 +00:00
|
|
|
backtestService := &service.BacktestService{DB: environ.DatabaseService.DB}
|
2021-05-06 17:50:38 +00:00
|
|
|
environ.BacktestService = backtestService
|
2022-06-20 17:12:16 +00:00
|
|
|
bbgo.SetBackTesting(backtestService)
|
2020-11-06 19:18:05 +00:00
|
|
|
|
2022-05-09 11:27:02 +00:00
|
|
|
if len(sessionName) > 0 {
|
|
|
|
userConfig.Backtest.Sessions = []string{sessionName}
|
|
|
|
} else if len(syncExchangeName) > 0 {
|
|
|
|
userConfig.Backtest.Sessions = []string{syncExchangeName}
|
|
|
|
} else if len(userConfig.Backtest.Sessions) == 0 {
|
|
|
|
log.Infof("backtest.sessions is not defined, using all supported exchanges: %v", types.SupportedExchanges)
|
|
|
|
for _, exName := range types.SupportedExchanges {
|
|
|
|
userConfig.Backtest.Sessions = append(userConfig.Backtest.Sessions, exName.String())
|
|
|
|
}
|
2022-05-09 11:14:09 +00:00
|
|
|
}
|
|
|
|
|
2022-04-09 16:56:25 +00:00
|
|
|
var sourceExchanges = make(map[types.ExchangeName]types.Exchange)
|
2022-05-09 11:27:02 +00:00
|
|
|
for _, name := range userConfig.Backtest.Sessions {
|
|
|
|
exName, err := types.ValidExchangeName(name)
|
2022-05-03 04:12:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-06-03 18:23:23 +00:00
|
|
|
publicExchange, err := exchange.NewPublic(exName)
|
2022-05-03 04:12:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sourceExchanges[exName] = publicExchange
|
2023-12-21 10:19:28 +00:00
|
|
|
|
|
|
|
// Set exchange to use futures
|
|
|
|
if userConfig.Sessions[exName.String()].Futures {
|
|
|
|
futuresExchange, ok := publicExchange.(types.FuturesExchange)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("exchange %s does not support futures", publicExchange.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
futuresExchange.UseFutures()
|
|
|
|
}
|
2022-04-09 16:56:25 +00:00
|
|
|
}
|
|
|
|
|
2022-06-04 17:01:59 +00:00
|
|
|
var syncFromTime time.Time
|
2021-05-05 08:45:17 +00:00
|
|
|
|
2022-06-04 17:01:59 +00:00
|
|
|
// user can override the sync from time if the option is given
|
|
|
|
if len(syncFromDateStr) > 0 {
|
|
|
|
syncFromTime, err = time.Parse(types.DateFormat, syncFromDateStr)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-05-07 16:44:43 +00:00
|
|
|
|
2022-06-04 17:01:59 +00:00
|
|
|
if syncFromTime.After(startTime) {
|
|
|
|
return fmt.Errorf("sync-from time %s can not be latter than the backtest start time %s", syncFromTime, startTime)
|
2021-05-05 08:45:17 +00:00
|
|
|
}
|
2022-08-26 11:06:52 +00:00
|
|
|
|
|
|
|
syncFromTime = syncFromTime.Local()
|
2022-06-04 17:01:59 +00:00
|
|
|
} else {
|
|
|
|
// we need at least 1 month backward data for EMA and last prices
|
|
|
|
syncFromTime = startTime.AddDate(0, -1, 0)
|
|
|
|
log.Infof("adjusted sync start time %s to %s for backward market data", startTime, syncFromTime)
|
|
|
|
}
|
2021-05-05 08:45:17 +00:00
|
|
|
|
2022-06-04 17:01:59 +00:00
|
|
|
if wantSync {
|
2022-04-09 16:35:06 +00:00
|
|
|
log.Infof("starting synchronization: %v", userConfig.Backtest.Symbols)
|
2022-08-26 11:06:52 +00:00
|
|
|
if err := sync(ctx, userConfig, backtestService, sourceExchanges, syncFromTime, endTime); err != nil {
|
2022-05-11 05:59:44 +00:00
|
|
|
return err
|
2021-12-14 16:59:28 +00:00
|
|
|
}
|
|
|
|
log.Info("synchronization done")
|
2020-11-11 08:08:24 +00:00
|
|
|
|
2022-05-11 05:59:44 +00:00
|
|
|
if shouldVerify {
|
2022-08-26 11:06:52 +00:00
|
|
|
err := verify(userConfig, backtestService, sourceExchanges, syncFromTime, endTime)
|
2022-05-11 05:59:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2021-12-07 07:21:37 +00:00
|
|
|
}
|
2020-11-11 08:08:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if syncOnly {
|
|
|
|
return nil
|
|
|
|
}
|
2020-11-07 12:14:53 +00:00
|
|
|
}
|
|
|
|
|
2021-12-05 17:42:53 +00:00
|
|
|
if userConfig.Backtest.RecordTrades {
|
|
|
|
log.Warn("!!! Trade recording is enabled for back-testing !!!")
|
|
|
|
log.Warn("!!! To run back-testing, you should use an isolated database for storing back-testing trades !!!")
|
|
|
|
log.Warn("!!! The trade record in the current database WILL ALL BE DELETED BEFORE THIS BACK-TESTING !!!")
|
|
|
|
if !force {
|
|
|
|
if !confirmation("Are you sure to continue?") {
|
|
|
|
return nil
|
|
|
|
}
|
2021-12-04 16:18:51 +00:00
|
|
|
}
|
2021-05-30 07:25:00 +00:00
|
|
|
|
2021-12-05 17:42:53 +00:00
|
|
|
if err := environ.TradeService.DeleteAll(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-05-30 07:25:00 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 07:15:57 +00:00
|
|
|
if verboseCnt == 2 {
|
|
|
|
log.SetLevel(log.DebugLevel)
|
|
|
|
} else if verboseCnt > 0 {
|
|
|
|
log.SetLevel(log.InfoLevel)
|
|
|
|
} else {
|
|
|
|
// default mode, disable strategy logging and order executor logging
|
|
|
|
log.SetLevel(log.ErrorLevel)
|
|
|
|
}
|
|
|
|
|
2020-11-10 06:19:11 +00:00
|
|
|
environ.SetStartTime(startTime)
|
2021-12-13 23:15:18 +00:00
|
|
|
|
2021-12-23 15:02:07 +00:00
|
|
|
// exchangeNameStr is the session name.
|
2022-03-01 13:48:48 +00:00
|
|
|
for name, sourceExchange := range sourceExchanges {
|
|
|
|
backtestExchange, err := backtest.NewExchange(sourceExchange.Name(), sourceExchange, backtestService, userConfig.Backtest)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to create backtest exchange")
|
|
|
|
}
|
2022-06-15 07:32:04 +00:00
|
|
|
session := environ.AddExchange(name.String(), backtestExchange)
|
|
|
|
exchangeFromConfig := userConfig.Sessions[name.String()]
|
|
|
|
if exchangeFromConfig != nil {
|
|
|
|
session.UseHeikinAshi = exchangeFromConfig.UseHeikinAshi
|
2023-12-22 03:55:11 +00:00
|
|
|
session.Futures = exchangeFromConfig.Futures
|
2022-06-15 07:32:04 +00:00
|
|
|
}
|
2022-03-01 13:48:48 +00:00
|
|
|
}
|
2021-05-07 16:44:43 +00:00
|
|
|
|
2021-05-30 07:25:00 +00:00
|
|
|
if err := environ.Init(ctx); err != nil {
|
2021-05-07 16:14:25 +00:00
|
|
|
return err
|
2020-11-06 19:18:05 +00:00
|
|
|
}
|
|
|
|
|
2022-07-03 18:21:14 +00:00
|
|
|
for _, session := range environ.Sessions() {
|
2022-07-03 18:27:29 +00:00
|
|
|
userDataStream := session.UserDataStream.(types.StandardStreamEmitter)
|
2022-07-03 18:21:14 +00:00
|
|
|
backtestEx := session.Exchange.(*backtest.Exchange)
|
|
|
|
backtestEx.MarketDataStream = session.MarketDataStream.(types.StandardStreamEmitter)
|
2022-07-03 18:27:29 +00:00
|
|
|
backtestEx.BindUserData(userDataStream)
|
2022-07-03 18:21:14 +00:00
|
|
|
}
|
|
|
|
|
2020-11-06 18:57:50 +00:00
|
|
|
trader := bbgo.NewTrader(environ)
|
2021-12-23 15:02:07 +00:00
|
|
|
if verboseCnt == 0 {
|
2020-11-10 06:19:11 +00:00
|
|
|
trader.DisableLogging()
|
|
|
|
}
|
2020-11-09 08:47:29 +00:00
|
|
|
|
2021-05-30 07:25:00 +00:00
|
|
|
if err := trader.Configure(userConfig); err != nil {
|
2021-05-07 16:14:25 +00:00
|
|
|
return err
|
2020-11-06 18:57:50 +00:00
|
|
|
}
|
|
|
|
|
2020-11-06 19:18:05 +00:00
|
|
|
if err := trader.Run(ctx); err != nil {
|
2020-11-06 18:57:50 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-12-06 05:16:12 +00:00
|
|
|
allKLineIntervals, requiredInterval, backTestIntervals := backtest.CollectSubscriptionIntervals(environ)
|
|
|
|
exchangeSources, err := backtest.InitializeExchangeSources(environ.Sessions(), startTime, endTime, requiredInterval, backTestIntervals...)
|
2022-05-11 05:59:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2022-03-01 13:48:48 +00:00
|
|
|
}
|
|
|
|
|
2022-05-11 06:36:18 +00:00
|
|
|
var kLineHandlers []func(k types.KLine, exSource *backtest.ExchangeDataSource)
|
2022-05-10 06:05:44 +00:00
|
|
|
var manifests backtest.Manifests
|
2022-05-17 10:10:37 +00:00
|
|
|
var runID = userConfig.GetSignature() + "_" + uuid.NewString()
|
|
|
|
var reportDir = outputDirectory
|
2022-08-24 06:13:28 +00:00
|
|
|
var sessionTradeStats = make(map[string]map[string]*types.TradeStats)
|
|
|
|
|
2023-08-15 09:54:24 +00:00
|
|
|
// for each exchange session, iterate the positions and
|
|
|
|
// allocate trade collector to calculate the tradeStats
|
2023-07-05 07:26:36 +00:00
|
|
|
var tradeCollectorList []*core.TradeCollector
|
2022-08-24 06:13:28 +00:00
|
|
|
for _, exSource := range exchangeSources {
|
|
|
|
sessionName := exSource.Session.Name
|
|
|
|
tradeStatsMap := make(map[string]*types.TradeStats)
|
|
|
|
for usedSymbol := range exSource.Session.Positions() {
|
|
|
|
market, _ := exSource.Session.Market(usedSymbol)
|
|
|
|
position := types.NewPositionFromMarket(market)
|
2023-07-04 13:42:24 +00:00
|
|
|
orderStore := core.NewOrderStore(usedSymbol)
|
2022-08-24 06:13:28 +00:00
|
|
|
orderStore.AddOrderUpdate = true
|
2023-07-05 07:26:36 +00:00
|
|
|
tradeCollector := core.NewTradeCollector(usedSymbol, position, orderStore)
|
2022-08-24 06:13:28 +00:00
|
|
|
|
|
|
|
tradeStats := types.NewTradeStats(usedSymbol)
|
|
|
|
tradeStats.SetIntervalProfitCollector(types.NewIntervalProfitCollector(types.Interval1d, startTime))
|
|
|
|
tradeCollector.OnProfit(func(trade types.Trade, profit *types.Profit) {
|
|
|
|
if profit == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
tradeStats.Add(profit)
|
|
|
|
})
|
|
|
|
tradeStatsMap[usedSymbol] = tradeStats
|
|
|
|
|
|
|
|
orderStore.BindStream(exSource.Session.UserDataStream)
|
|
|
|
tradeCollector.BindStream(exSource.Session.UserDataStream)
|
|
|
|
tradeCollectorList = append(tradeCollectorList, tradeCollector)
|
|
|
|
}
|
|
|
|
sessionTradeStats[sessionName] = tradeStatsMap
|
|
|
|
}
|
2023-08-15 09:54:24 +00:00
|
|
|
|
2022-08-24 06:13:28 +00:00
|
|
|
kLineHandlers = append(kLineHandlers, func(k types.KLine, _ *backtest.ExchangeDataSource) {
|
|
|
|
if k.Interval == types.Interval1d && k.Closed {
|
|
|
|
for _, collector := range tradeCollectorList {
|
|
|
|
collector.Process()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2022-05-17 10:10:37 +00:00
|
|
|
|
2022-05-09 10:58:09 +00:00
|
|
|
if generatingReport {
|
|
|
|
if reportFileInSubDir {
|
2022-05-17 10:10:37 +00:00
|
|
|
// reportDir = filepath.Join(reportDir, backtestSessionName)
|
|
|
|
reportDir = filepath.Join(reportDir, runID)
|
2022-05-09 10:58:09 +00:00
|
|
|
}
|
2022-06-13 04:26:47 +00:00
|
|
|
if err := util.SafeMkdirAll(reportDir); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-09 10:58:09 +00:00
|
|
|
|
2022-06-14 04:54:05 +00:00
|
|
|
startTimeStr := startTime.Format("20060102")
|
|
|
|
endTimeStr := endTime.Format("20060102")
|
|
|
|
kLineSubDir := strings.Join([]string{"klines", "_", startTimeStr, "-", endTimeStr}, "")
|
|
|
|
kLineDataDir := filepath.Join(outputDirectory, "shared", kLineSubDir)
|
2022-05-17 10:23:09 +00:00
|
|
|
if err := util.SafeMkdirAll(kLineDataDir); err != nil {
|
2022-05-10 05:25:03 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-05-09 10:58:09 +00:00
|
|
|
|
2022-05-10 05:25:03 +00:00
|
|
|
stateRecorder := backtest.NewStateRecorder(reportDir)
|
|
|
|
err = trader.IterateStrategies(func(st bbgo.StrategyID) error {
|
|
|
|
return stateRecorder.Scan(st.(backtest.Instance))
|
|
|
|
})
|
2022-05-17 14:59:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-10 05:25:03 +00:00
|
|
|
|
2022-05-17 14:59:34 +00:00
|
|
|
manifests = stateRecorder.Manifests()
|
|
|
|
manifests, err = rewriteManifestPaths(manifests, reportDir)
|
2022-05-10 05:25:03 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-10 11:10:16 +00:00
|
|
|
// state snapshot
|
2022-05-11 06:36:18 +00:00
|
|
|
kLineHandlers = append(kLineHandlers, func(k types.KLine, _ *backtest.ExchangeDataSource) {
|
2022-05-10 05:25:03 +00:00
|
|
|
// snapshot per 1m
|
|
|
|
if k.Interval == types.Interval1m && k.Closed {
|
|
|
|
if _, err := stateRecorder.Snapshot(); err != nil {
|
|
|
|
log.WithError(err).Errorf("state record failed to snapshot the strategy state")
|
2022-05-09 11:40:49 +00:00
|
|
|
}
|
2022-05-09 11:14:09 +00:00
|
|
|
}
|
2022-05-10 05:25:03 +00:00
|
|
|
})
|
2022-05-09 11:14:09 +00:00
|
|
|
|
2022-05-10 05:25:03 +00:00
|
|
|
dumper := backtest.NewKLineDumper(kLineDataDir)
|
2022-05-09 10:58:09 +00:00
|
|
|
defer func() {
|
2022-05-09 11:14:09 +00:00
|
|
|
if err := dumper.Close(); err != nil {
|
2022-05-09 10:58:09 +00:00
|
|
|
log.WithError(err).Errorf("kline dumper can not close files")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2022-05-11 06:36:18 +00:00
|
|
|
kLineHandlers = append(kLineHandlers, func(k types.KLine, _ *backtest.ExchangeDataSource) {
|
2022-05-09 10:58:09 +00:00
|
|
|
if err := dumper.Record(k); err != nil {
|
|
|
|
log.WithError(err).Errorf("can not write kline to file")
|
|
|
|
}
|
|
|
|
})
|
2022-05-11 06:36:18 +00:00
|
|
|
|
|
|
|
// equity curve recording -- record per 1h kline
|
2022-05-12 14:12:31 +00:00
|
|
|
equityCurveTsv, err := tsv.NewWriterFile(filepath.Join(reportDir, "equity_curve.tsv"))
|
2022-05-11 06:36:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-12 14:12:31 +00:00
|
|
|
defer func() { _ = equityCurveTsv.Close() }()
|
2022-05-11 06:36:18 +00:00
|
|
|
|
2022-05-12 14:12:31 +00:00
|
|
|
_ = equityCurveTsv.Write([]string{
|
2022-05-11 06:36:18 +00:00
|
|
|
"time",
|
|
|
|
"in_usd",
|
|
|
|
})
|
2022-05-12 14:12:31 +00:00
|
|
|
defer equityCurveTsv.Flush()
|
2022-05-11 06:36:18 +00:00
|
|
|
|
|
|
|
kLineHandlers = append(kLineHandlers, func(k types.KLine, exSource *backtest.ExchangeDataSource) {
|
|
|
|
if k.Interval != types.Interval1h {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
balances, err := exSource.Exchange.QueryAccountBalances(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("query back-test account balance error")
|
|
|
|
} else {
|
|
|
|
assets := balances.Assets(exSource.Session.AllLastPrices(), k.EndTime.Time())
|
2022-05-12 14:12:31 +00:00
|
|
|
_ = equityCurveTsv.Write([]string{
|
2022-05-11 06:36:18 +00:00
|
|
|
k.EndTime.Time().Format(time.RFC1123),
|
|
|
|
assets.InUSD().String(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
2022-05-11 06:58:52 +00:00
|
|
|
|
2022-05-12 14:12:31 +00:00
|
|
|
ordersTsv, err := tsv.NewWriterFile(filepath.Join(reportDir, "orders.tsv"))
|
2022-05-11 06:58:52 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-12 14:12:31 +00:00
|
|
|
defer func() { _ = ordersTsv.Close() }()
|
|
|
|
_ = ordersTsv.Write(types.Order{}.CsvHeader())
|
2022-05-11 06:58:52 +00:00
|
|
|
|
|
|
|
for _, exSource := range exchangeSources {
|
|
|
|
exSource.Session.UserDataStream.OnOrderUpdate(func(order types.Order) {
|
|
|
|
if order.Status == types.OrderStatusFilled {
|
|
|
|
for _, record := range order.CsvRecords() {
|
2022-05-12 14:12:31 +00:00
|
|
|
_ = ordersTsv.Write(record)
|
2022-05-11 06:58:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2022-05-09 10:58:09 +00:00
|
|
|
}
|
|
|
|
|
2022-05-09 11:14:09 +00:00
|
|
|
runCtx, cancelRun := context.WithCancel(ctx)
|
2022-08-30 12:02:21 +00:00
|
|
|
for _, exK := range exchangeSources {
|
|
|
|
exK.Callbacks = kLineHandlers
|
|
|
|
}
|
2022-03-16 10:25:27 +00:00
|
|
|
go func() {
|
|
|
|
defer cancelRun()
|
2022-05-06 11:16:15 +00:00
|
|
|
|
|
|
|
// Optimize back-test speed for single exchange source
|
2022-05-10 11:10:16 +00:00
|
|
|
var numOfExchangeSources = len(exchangeSources)
|
|
|
|
if numOfExchangeSources == 1 {
|
2022-05-06 11:16:15 +00:00
|
|
|
exSource := exchangeSources[0]
|
|
|
|
for k := range exSource.C {
|
2022-10-03 16:24:16 +00:00
|
|
|
exSource.Exchange.ConsumeKLine(k, requiredInterval)
|
2022-05-06 11:16:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := exSource.Exchange.CloseMarketData(); err != nil {
|
|
|
|
log.WithError(err).Errorf("close market data error")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-05-10 11:10:16 +00:00
|
|
|
RunMultiExchangeData:
|
2022-03-16 10:25:27 +00:00
|
|
|
for {
|
2022-05-06 11:16:15 +00:00
|
|
|
for _, exK := range exchangeSources {
|
2022-05-09 10:58:09 +00:00
|
|
|
k, more := <-exK.C
|
2022-05-10 11:10:16 +00:00
|
|
|
if !more {
|
2022-05-06 11:16:15 +00:00
|
|
|
if err := exK.Exchange.CloseMarketData(); err != nil {
|
|
|
|
log.WithError(err).Errorf("close market data error")
|
2022-03-16 10:25:27 +00:00
|
|
|
return
|
|
|
|
}
|
2022-05-10 11:10:16 +00:00
|
|
|
break RunMultiExchangeData
|
|
|
|
}
|
|
|
|
|
2022-10-03 16:24:16 +00:00
|
|
|
exK.Exchange.ConsumeKLine(k, requiredInterval)
|
2022-03-01 13:48:48 +00:00
|
|
|
}
|
|
|
|
}
|
2022-03-16 10:25:27 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
cmdutil.WaitForSignal(runCtx, syscall.SIGINT, syscall.SIGTERM)
|
2020-11-07 12:34:34 +00:00
|
|
|
|
2020-11-12 06:50:08 +00:00
|
|
|
log.Infof("shutting down trader...")
|
2022-10-11 06:22:46 +00:00
|
|
|
|
|
|
|
gracefulShutdownPeriod := 30 * time.Second
|
|
|
|
shtCtx, cancelShutdown := context.WithTimeout(bbgo.NewTodoContextWithExistingIsolation(ctx), gracefulShutdownPeriod)
|
|
|
|
bbgo.Shutdown(shtCtx)
|
|
|
|
cancelShutdown()
|
2020-11-12 06:50:08 +00:00
|
|
|
|
2020-11-10 06:19:11 +00:00
|
|
|
// put the logger back to print the pnl
|
|
|
|
log.SetLevel(log.InfoLevel)
|
2022-05-09 17:10:36 +00:00
|
|
|
|
2022-05-10 10:27:23 +00:00
|
|
|
// aggregate total balances
|
|
|
|
initTotalBalances := types.BalanceMap{}
|
|
|
|
finalTotalBalances := types.BalanceMap{}
|
2022-05-17 14:59:34 +00:00
|
|
|
var sessionNames []string
|
2020-11-07 12:34:34 +00:00
|
|
|
for _, session := range environ.Sessions() {
|
2022-05-10 10:27:23 +00:00
|
|
|
sessionNames = append(sessionNames, session.Name)
|
|
|
|
accountConfig := userConfig.Backtest.GetAccount(session.Name)
|
|
|
|
initBalances := accountConfig.Balances.BalanceMap()
|
|
|
|
initTotalBalances = initTotalBalances.Add(initBalances)
|
|
|
|
|
|
|
|
finalBalances := session.GetAccount().Balances()
|
|
|
|
finalTotalBalances = finalTotalBalances.Add(finalBalances)
|
|
|
|
}
|
2022-05-17 14:59:34 +00:00
|
|
|
|
2022-05-10 10:27:23 +00:00
|
|
|
summaryReport := &backtest.SummaryReport{
|
|
|
|
StartTime: startTime,
|
|
|
|
EndTime: endTime,
|
|
|
|
Sessions: sessionNames,
|
|
|
|
InitialTotalBalances: initTotalBalances,
|
|
|
|
FinalTotalBalances: finalTotalBalances,
|
2022-05-17 14:59:34 +00:00
|
|
|
Manifests: manifests,
|
2022-05-17 18:05:57 +00:00
|
|
|
Symbols: nil,
|
2022-05-10 10:27:23 +00:00
|
|
|
}
|
|
|
|
|
2022-05-19 01:48:36 +00:00
|
|
|
for interval := range allKLineIntervals {
|
|
|
|
summaryReport.Intervals = append(summaryReport.Intervals, interval)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, session := range environ.Sessions() {
|
2020-11-07 12:34:34 +00:00
|
|
|
for symbol, trades := range session.Trades {
|
2023-11-01 07:22:53 +00:00
|
|
|
if len(trades.Trades) == 0 {
|
|
|
|
log.Warnf("session has no %s trades", symbol)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-11-10 09:17:35 +00:00
|
|
|
tradeState := sessionTradeStats[session.Name][symbol]
|
|
|
|
profitFactor := tradeState.ProfitFactor
|
|
|
|
winningRatio := tradeState.WinningRatio
|
|
|
|
intervalProfits := tradeState.IntervalProfits[types.Interval1d]
|
2023-07-12 09:16:46 +00:00
|
|
|
|
|
|
|
symbolReport, err := createSymbolReport(userConfig, session, symbol, trades.Copy(), intervalProfits, profitFactor, winningRatio)
|
2022-05-17 14:59:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2022-05-17 10:45:06 +00:00
|
|
|
}
|
|
|
|
|
2022-05-17 18:05:57 +00:00
|
|
|
summaryReport.Symbols = append(summaryReport.Symbols, symbol)
|
2022-05-17 14:59:34 +00:00
|
|
|
summaryReport.SymbolReports = append(summaryReport.SymbolReports, *symbolReport)
|
2022-05-19 10:45:45 +00:00
|
|
|
summaryReport.TotalProfit = symbolReport.PnL.Profit
|
|
|
|
summaryReport.TotalUnrealizedProfit = symbolReport.PnL.UnrealizedProfit
|
2022-07-12 11:50:28 +00:00
|
|
|
summaryReport.InitialEquityValue = summaryReport.InitialEquityValue.Add(symbolReport.InitialEquityValue())
|
|
|
|
summaryReport.FinalEquityValue = summaryReport.FinalEquityValue.Add(symbolReport.FinalEquityValue())
|
|
|
|
summaryReport.TotalGrossProfit.Add(symbolReport.PnL.GrossProfit)
|
|
|
|
summaryReport.TotalGrossLoss.Add(symbolReport.PnL.GrossLoss)
|
2022-05-17 10:45:06 +00:00
|
|
|
|
|
|
|
// write report to a file
|
2022-05-10 06:05:44 +00:00
|
|
|
if generatingReport {
|
2022-09-06 05:18:35 +00:00
|
|
|
reportFileName := fmt.Sprintf("symbol_report_%s_%s.json", session.Name, symbol)
|
2022-05-17 10:45:06 +00:00
|
|
|
if err := util.WriteJsonFile(filepath.Join(reportDir, reportFileName), &symbolReport); err != nil {
|
2021-12-05 17:05:33 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-11-07 12:34:34 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-07 12:11:07 +00:00
|
|
|
|
2022-05-19 10:45:45 +00:00
|
|
|
if generatingReport {
|
2022-05-17 14:59:34 +00:00
|
|
|
summaryReportFile := filepath.Join(reportDir, "summary.json")
|
2022-05-19 10:45:45 +00:00
|
|
|
|
|
|
|
// output summary report filepath to stdout, so that our optimizer can read from it
|
|
|
|
fmt.Println(summaryReportFile)
|
|
|
|
|
2022-05-17 14:59:34 +00:00
|
|
|
if err := util.WriteJsonFile(summaryReportFile, summaryReport); err != nil {
|
2022-09-06 05:20:37 +00:00
|
|
|
return errors.Wrapf(err, "can not write summary report json file: %s", summaryReportFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
configJsonFile := filepath.Join(reportDir, "config.json")
|
|
|
|
if err := util.WriteJsonFile(configJsonFile, userConfig); err != nil {
|
|
|
|
return errors.Wrapf(err, "can not write config json file: %s", configJsonFile)
|
2022-05-17 14:59:34 +00:00
|
|
|
}
|
|
|
|
|
2022-05-17 10:10:37 +00:00
|
|
|
// append report index
|
2022-05-19 10:45:45 +00:00
|
|
|
if reportFileInSubDir {
|
|
|
|
if err := backtest.AddReportIndexRun(outputDirectory, backtest.Run{
|
|
|
|
ID: runID,
|
|
|
|
Config: userConfig,
|
|
|
|
Time: time.Now(),
|
|
|
|
}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2022-05-19 12:31:25 +00:00
|
|
|
color.Green("BACK-TEST REPORT")
|
|
|
|
color.Green("===============================================\n")
|
|
|
|
color.Green("START TIME: %s\n", startTime.Format(time.RFC1123))
|
|
|
|
color.Green("END TIME: %s\n", endTime.Format(time.RFC1123))
|
|
|
|
color.Green("INITIAL TOTAL BALANCE: %v\n", initTotalBalances)
|
|
|
|
color.Green("FINAL TOTAL BALANCE: %v\n", finalTotalBalances)
|
2022-05-19 10:45:45 +00:00
|
|
|
for _, symbolReport := range summaryReport.SymbolReports {
|
|
|
|
symbolReport.Print(wantBaseAssetBaseline)
|
2022-05-17 10:10:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-06 18:57:50 +00:00
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
2021-05-30 07:25:00 +00:00
|
|
|
|
2023-11-01 07:22:53 +00:00
|
|
|
func createSymbolReport(
|
|
|
|
userConfig *bbgo.Config, session *bbgo.ExchangeSession, symbol string, trades []types.Trade,
|
|
|
|
intervalProfit *types.IntervalProfitCollector,
|
|
|
|
profitFactor, winningRatio fixedpoint.Value,
|
|
|
|
) (
|
2022-08-24 06:13:28 +00:00
|
|
|
*backtest.SessionSymbolReport,
|
|
|
|
error,
|
|
|
|
) {
|
2022-05-17 14:59:34 +00:00
|
|
|
backtestExchange, ok := session.Exchange.(*backtest.Exchange)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("unexpected error, exchange instance is not a backtest exchange")
|
|
|
|
}
|
|
|
|
|
|
|
|
market, ok := session.Market(symbol)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("market not found: %s, %s", symbol, session.Exchange.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
startPrice, ok := session.StartPrice(symbol)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("start price not found: %s, %s. run --sync first", symbol, session.Exchange.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
lastPrice, ok := session.LastPrice(symbol)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("last price not found: %s, %s", symbol, session.Exchange.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
calculator := &pnl.AverageCostCalculator{
|
|
|
|
TradingFeeCurrency: backtestExchange.PlatformFeeCurrency(),
|
|
|
|
Market: market,
|
|
|
|
}
|
|
|
|
|
2022-08-29 05:11:02 +00:00
|
|
|
sharpeRatio := fixedpoint.NewFromFloat(intervalProfit.GetSharpe())
|
|
|
|
sortinoRatio := fixedpoint.NewFromFloat(intervalProfit.GetSortino())
|
2022-08-24 09:45:34 +00:00
|
|
|
|
2022-05-17 14:59:34 +00:00
|
|
|
report := calculator.Calculate(symbol, trades, lastPrice)
|
|
|
|
accountConfig := userConfig.Backtest.GetAccount(session.Exchange.Name().String())
|
|
|
|
initBalances := accountConfig.Balances.BalanceMap()
|
|
|
|
finalBalances := session.GetAccount().Balances()
|
|
|
|
symbolReport := backtest.SessionSymbolReport{
|
|
|
|
Exchange: session.Exchange.Name(),
|
|
|
|
Symbol: symbol,
|
|
|
|
Market: market,
|
|
|
|
LastPrice: lastPrice,
|
|
|
|
StartPrice: startPrice,
|
|
|
|
PnL: report,
|
|
|
|
InitialBalances: initBalances,
|
|
|
|
FinalBalances: finalBalances,
|
|
|
|
// Manifests: manifests,
|
2022-11-10 09:17:35 +00:00
|
|
|
Sharpe: sharpeRatio,
|
|
|
|
Sortino: sortinoRatio,
|
|
|
|
ProfitFactor: profitFactor,
|
|
|
|
WinningRatio: winningRatio,
|
2022-05-17 14:59:34 +00:00
|
|
|
}
|
2022-05-19 01:48:36 +00:00
|
|
|
|
|
|
|
for _, s := range session.Subscriptions {
|
|
|
|
symbolReport.Subscriptions = append(symbolReport.Subscriptions, s)
|
|
|
|
}
|
|
|
|
|
|
|
|
sessionKLineIntervals := map[types.Interval]struct{}{}
|
|
|
|
for _, sub := range session.Subscriptions {
|
|
|
|
if sub.Channel == types.KLineChannel {
|
2022-05-19 16:50:58 +00:00
|
|
|
sessionKLineIntervals[sub.Options.Interval] = struct{}{}
|
2022-05-19 01:48:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for interval := range sessionKLineIntervals {
|
|
|
|
symbolReport.Intervals = append(symbolReport.Intervals, interval)
|
|
|
|
}
|
|
|
|
|
2022-05-17 14:59:34 +00:00
|
|
|
return &symbolReport, nil
|
|
|
|
}
|
|
|
|
|
2023-11-01 07:22:53 +00:00
|
|
|
func verify(
|
|
|
|
userConfig *bbgo.Config, backtestService *service.BacktestService,
|
|
|
|
sourceExchanges map[types.ExchangeName]types.Exchange, startTime, endTime time.Time,
|
|
|
|
) error {
|
2022-05-11 05:59:44 +00:00
|
|
|
for _, sourceExchange := range sourceExchanges {
|
2022-06-06 06:58:26 +00:00
|
|
|
err := backtestService.Verify(sourceExchange, userConfig.Backtest.Symbols, startTime, endTime)
|
2022-05-11 05:59:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-05-30 07:25:00 +00:00
|
|
|
func confirmation(s string) bool {
|
|
|
|
reader := bufio.NewReader(os.Stdin)
|
|
|
|
for {
|
|
|
|
fmt.Printf("%s [y/N]: ", s)
|
|
|
|
|
|
|
|
response, err := reader.ReadString('\n')
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
response = strings.ToLower(strings.TrimSpace(response))
|
|
|
|
|
|
|
|
if response == "y" || response == "yes" {
|
|
|
|
return true
|
|
|
|
} else if response == "n" || response == "no" {
|
|
|
|
return false
|
|
|
|
} else {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-05-10 05:25:03 +00:00
|
|
|
|
2023-07-03 07:14:48 +00:00
|
|
|
func getExchangeIntervals(ex types.Exchange) types.IntervalMap {
|
2023-07-03 07:07:34 +00:00
|
|
|
exCustom, ok := ex.(types.CustomIntervalProvider)
|
|
|
|
if ok {
|
|
|
|
return exCustom.SupportedInterval()
|
|
|
|
}
|
|
|
|
return types.SupportedIntervals
|
|
|
|
}
|
|
|
|
|
2023-11-01 07:22:53 +00:00
|
|
|
func sync(
|
|
|
|
ctx context.Context, userConfig *bbgo.Config, backtestService *service.BacktestService,
|
|
|
|
sourceExchanges map[types.ExchangeName]types.Exchange, syncFrom, syncTo time.Time,
|
|
|
|
) error {
|
2022-05-11 05:59:44 +00:00
|
|
|
for _, symbol := range userConfig.Backtest.Symbols {
|
|
|
|
for _, sourceExchange := range sourceExchanges {
|
2023-07-03 07:07:34 +00:00
|
|
|
var supportIntervals = getExchangeIntervals(sourceExchange)
|
2022-05-11 05:59:44 +00:00
|
|
|
|
2022-10-04 14:04:09 +00:00
|
|
|
if !userConfig.Backtest.SyncSecKLines {
|
|
|
|
delete(supportIntervals, types.Interval1s)
|
|
|
|
}
|
2022-05-11 05:59:44 +00:00
|
|
|
|
2022-06-06 16:48:13 +00:00
|
|
|
// sort intervals
|
2023-07-03 07:14:48 +00:00
|
|
|
var intervals = supportIntervals.Slice()
|
2023-07-03 07:07:34 +00:00
|
|
|
intervals.Sort()
|
2022-06-06 16:48:13 +00:00
|
|
|
|
|
|
|
for _, interval := range intervals {
|
2022-06-08 06:38:47 +00:00
|
|
|
if err := backtestService.Sync(ctx, sourceExchange, symbol, interval, syncFrom, syncTo); err != nil {
|
|
|
|
return err
|
2022-05-11 05:59:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2022-05-17 10:45:06 +00:00
|
|
|
|
2022-05-17 14:59:34 +00:00
|
|
|
func rewriteManifestPaths(manifests backtest.Manifests, basePath string) (backtest.Manifests, error) {
|
|
|
|
var filterManifests = backtest.Manifests{}
|
|
|
|
for k, m := range manifests {
|
|
|
|
p, err := filepath.Rel(basePath, m)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
filterManifests[k] = p
|
|
|
|
}
|
|
|
|
return filterManifests, nil
|
|
|
|
}
|