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"
|
2021-12-05 17:05:33 +00:00
|
|
|
"encoding/json"
|
2020-11-09 08:34:35 +00:00
|
|
|
"fmt"
|
2021-12-05 17:05:33 +00:00
|
|
|
"io/ioutil"
|
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-01-31 17:00:26 +00:00
|
|
|
"github.com/fatih/color"
|
2022-05-09 10:58:09 +00:00
|
|
|
"github.com/google/uuid"
|
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"
|
|
|
|
"github.com/c9s/bbgo/pkg/cmd/cmdutil"
|
|
|
|
"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
|
|
|
|
}
|
|
|
|
|
2021-12-23 15:02:07 +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)
|
|
|
|
}
|
|
|
|
|
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-01-24 16:24:12 +00:00
|
|
|
var now = time.Now()
|
|
|
|
var startTime, endTime time.Time
|
|
|
|
|
|
|
|
startTime = userConfig.Backtest.StartTime.Time()
|
|
|
|
|
2020-11-06 19:18:05 +00:00
|
|
|
// set default start time to the past 6 months
|
2022-01-24 16:24:12 +00:00
|
|
|
// userConfig.Backtest.StartTime = now.AddDate(0, -6, 0).Format("2006-01-02")
|
|
|
|
if userConfig.Backtest.EndTime != nil {
|
|
|
|
endTime = userConfig.Backtest.EndTime.Time()
|
|
|
|
} else {
|
|
|
|
endTime = now
|
2020-11-10 11:06:20 +00:00
|
|
|
}
|
|
|
|
|
2021-05-05 08:45:17 +00:00
|
|
|
log.Infof("starting backtest with startTime %s", startTime.Format(time.ANSIC))
|
|
|
|
|
2021-01-15 02:47:49 +00:00
|
|
|
environ := bbgo.NewEnvironment()
|
2021-05-30 07:25:00 +00:00
|
|
|
if err := BootstrapBacktestEnvironment(ctx, environ, userConfig); 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
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
publicExchange, err := cmdutil.NewExchangePublic(exName)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sourceExchanges[exName] = publicExchange
|
2022-04-09 16:56:25 +00:00
|
|
|
}
|
|
|
|
|
2020-11-07 12:14:53 +00:00
|
|
|
if wantSync {
|
2021-12-07 07:21:37 +00:00
|
|
|
var syncFromTime time.Time
|
2021-05-05 08:45:17 +00:00
|
|
|
|
|
|
|
// 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
|
|
|
|
|
|
|
if syncFromTime.After(startTime) {
|
|
|
|
return fmt.Errorf("sync-from time %s can not be latter than the backtest start time %s", syncFromTime, startTime)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// we need at least 1 month backward data for EMA and last prices
|
2021-12-07 07:21:37 +00:00
|
|
|
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-04-09 16:35:06 +00:00
|
|
|
log.Infof("starting synchronization: %v", userConfig.Backtest.Symbols)
|
2020-11-07 12:14:53 +00:00
|
|
|
for _, symbol := range userConfig.Backtest.Symbols {
|
2021-12-07 07:21:37 +00:00
|
|
|
|
2022-03-01 13:48:48 +00:00
|
|
|
for _, sourceExchange := range sourceExchanges {
|
|
|
|
exCustom, ok := sourceExchange.(types.CustomIntervalProvider)
|
2021-12-07 07:21:37 +00:00
|
|
|
|
2022-03-01 13:48:48 +00:00
|
|
|
var supportIntervals map[types.Interval]int
|
|
|
|
if ok {
|
|
|
|
supportIntervals = exCustom.SupportedInterval()
|
|
|
|
} else {
|
|
|
|
supportIntervals = types.SupportedIntervals
|
2021-12-14 16:59:28 +00:00
|
|
|
}
|
2020-11-11 08:08:24 +00:00
|
|
|
|
2022-03-01 13:48:48 +00:00
|
|
|
for interval := range supportIntervals {
|
|
|
|
// if err := s.SyncKLineByInterval(ctx, exchange, symbol, interval, startTime, endTime); err != nil {
|
|
|
|
// return err
|
|
|
|
// }
|
|
|
|
firstKLine, err := backtestService.QueryFirstKLine(sourceExchange.Name(), symbol, interval)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to query backtest kline")
|
2021-12-07 07:21:37 +00:00
|
|
|
}
|
2022-03-01 13:48:48 +00:00
|
|
|
|
|
|
|
// if we don't have klines before the start time endpoint, the back-test will fail.
|
|
|
|
// because the last price will be missing.
|
|
|
|
if firstKLine != nil {
|
|
|
|
if err := backtestService.SyncExist(ctx, sourceExchange, symbol, syncFromTime, time.Now(), interval); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if err := backtestService.Sync(ctx, sourceExchange, symbol, syncFromTime, time.Now(), interval); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-07 07:21:37 +00:00
|
|
|
}
|
2020-11-11 08:08:24 +00:00
|
|
|
}
|
|
|
|
}
|
2021-12-14 16:59:28 +00:00
|
|
|
}
|
|
|
|
log.Info("synchronization done")
|
2020-11-11 08:08:24 +00:00
|
|
|
|
2022-03-01 13:48:48 +00:00
|
|
|
for _, sourceExchange := range sourceExchanges {
|
|
|
|
if shouldVerify {
|
|
|
|
err2, done := backtestService.Verify(userConfig.Backtest.Symbols, startTime, time.Now(), sourceExchange, verboseCnt)
|
|
|
|
if done {
|
|
|
|
return err2
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
|
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-04-09 16:56:25 +00:00
|
|
|
environ.AddExchange(name.String(), backtestExchange)
|
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
|
|
|
}
|
|
|
|
|
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-03-01 13:48:48 +00:00
|
|
|
for _, session := range environ.Sessions() {
|
|
|
|
backtestExchange := session.Exchange.(*backtest.Exchange)
|
|
|
|
backtestExchange.InitMarketData()
|
|
|
|
}
|
|
|
|
|
2022-05-06 11:16:15 +00:00
|
|
|
var exchangeSources []backtest.ExchangeDataSource
|
2022-03-01 13:48:48 +00:00
|
|
|
for _, session := range environ.Sessions() {
|
|
|
|
exchange := session.Exchange.(*backtest.Exchange)
|
|
|
|
c, err := exchange.GetMarketData()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-06 11:16:15 +00:00
|
|
|
exchangeSources = append(exchangeSources, backtest.ExchangeDataSource{C: c, Exchange: exchange})
|
2022-03-01 13:48:48 +00:00
|
|
|
}
|
|
|
|
|
2022-05-09 11:27:02 +00:00
|
|
|
// back-test session report name
|
|
|
|
var backtestSessionName = backtest.FormatSessionName(
|
|
|
|
userConfig.Backtest.Sessions,
|
|
|
|
userConfig.Backtest.Symbols,
|
|
|
|
userConfig.Backtest.StartTime.Time(),
|
|
|
|
userConfig.Backtest.EndTime.Time(),
|
|
|
|
)
|
2022-05-09 11:40:49 +00:00
|
|
|
|
2022-05-09 10:58:09 +00:00
|
|
|
var kLineHandlers []func(k types.KLine)
|
2022-05-10 06:05:44 +00:00
|
|
|
var manifests backtest.Manifests
|
2022-05-09 10:58:09 +00:00
|
|
|
if generatingReport {
|
2022-05-10 05:25:03 +00:00
|
|
|
reportDir := outputDirectory
|
2022-05-09 10:58:09 +00:00
|
|
|
if reportFileInSubDir {
|
2022-05-10 05:25:03 +00:00
|
|
|
reportDir = filepath.Join(reportDir, backtestSessionName)
|
|
|
|
reportDir = filepath.Join(reportDir, uuid.NewString())
|
2022-05-09 10:58:09 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 05:25:03 +00:00
|
|
|
kLineDataDir := filepath.Join(reportDir, "klines")
|
|
|
|
if err := safeMkdirAll(kLineDataDir); err != nil {
|
|
|
|
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-10 06:05:44 +00:00
|
|
|
manifests = stateRecorder.Manifests()
|
2022-05-10 05:25:03 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
kLineHandlers = append(kLineHandlers, func(k types.KLine) {
|
|
|
|
// 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")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
kLineHandlers = append(kLineHandlers, func(k types.KLine) {
|
|
|
|
if err := dumper.Record(k); err != nil {
|
|
|
|
log.WithError(err).Errorf("can not write kline to file")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-05-09 11:14:09 +00:00
|
|
|
runCtx, cancelRun := context.WithCancel(ctx)
|
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
|
|
|
|
var count = len(exchangeSources)
|
|
|
|
if count == 1 {
|
|
|
|
exSource := exchangeSources[0]
|
|
|
|
for k := range exSource.C {
|
|
|
|
exSource.Exchange.ConsumeKLine(k)
|
2022-05-09 10:58:09 +00:00
|
|
|
|
|
|
|
for _, h := range kLineHandlers {
|
|
|
|
h(k)
|
|
|
|
}
|
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-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-03-16 10:25:27 +00:00
|
|
|
if more {
|
2022-05-09 10:58:09 +00:00
|
|
|
exK.Exchange.ConsumeKLine(k)
|
|
|
|
|
|
|
|
for _, h := range kLineHandlers {
|
|
|
|
h(k)
|
|
|
|
}
|
2022-03-16 10:25:27 +00:00
|
|
|
} else {
|
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
|
|
|
|
}
|
|
|
|
count--
|
2022-03-01 13:48:48 +00:00
|
|
|
}
|
2022-03-16 10:25:27 +00:00
|
|
|
}
|
|
|
|
if count == 0 {
|
|
|
|
break
|
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-03-16 10:25:27 +00:00
|
|
|
shutdownCtx, cancelShutdown := context.WithDeadline(runCtx, time.Now().Add(10*time.Second))
|
2020-11-12 06:50:08 +00:00
|
|
|
trader.Graceful.Shutdown(shutdownCtx)
|
2022-03-16 10:25:27 +00:00
|
|
|
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
|
|
|
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))
|
|
|
|
|
|
|
|
// aggregate total balances
|
|
|
|
initTotalBalances := types.BalanceMap{}
|
|
|
|
finalTotalBalances := types.BalanceMap{}
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
color.Green("INITIAL TOTAL BALANCE: %v\n", initTotalBalances)
|
|
|
|
color.Green("FINAL TOTAL BALANCE: %v\n", finalTotalBalances)
|
|
|
|
|
|
|
|
summaryReport := &backtest.SummaryReport{
|
|
|
|
StartTime: startTime,
|
|
|
|
EndTime: endTime,
|
|
|
|
Sessions: sessionNames,
|
|
|
|
InitialTotalBalances: initTotalBalances,
|
|
|
|
FinalTotalBalances: finalTotalBalances,
|
|
|
|
}
|
|
|
|
_ = summaryReport
|
|
|
|
|
|
|
|
for _, session := range environ.Sessions() {
|
|
|
|
backtestExchange, ok := session.Exchange.(*backtest.Exchange)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("unexpected error, exchange instance is not a backtest exchange")
|
|
|
|
}
|
|
|
|
|
|
|
|
// per symbol report
|
2022-03-01 13:48:48 +00:00
|
|
|
exchangeName := session.Exchange.Name().String()
|
2020-11-07 12:34:34 +00:00
|
|
|
for symbol, trades := range session.Trades {
|
2020-11-10 06:19:11 +00:00
|
|
|
market, ok := session.Market(symbol)
|
|
|
|
if !ok {
|
2022-03-01 13:48:48 +00:00
|
|
|
return fmt.Errorf("market not found: %s, %s", symbol, exchangeName)
|
2020-11-10 06:19:11 +00:00
|
|
|
}
|
|
|
|
|
2021-12-04 18:16:48 +00:00
|
|
|
calculator := &pnl.AverageCostCalculator{
|
|
|
|
TradingFeeCurrency: backtestExchange.PlatformFeeCurrency(),
|
2021-12-05 17:05:33 +00:00
|
|
|
Market: market,
|
2021-12-04 18:16:48 +00:00
|
|
|
}
|
|
|
|
|
2020-11-10 11:06:20 +00:00
|
|
|
startPrice, ok := session.StartPrice(symbol)
|
2020-11-10 06:19:11 +00:00
|
|
|
if !ok {
|
2022-04-07 02:15:25 +00:00
|
|
|
return fmt.Errorf("start price not found: %s, %s. run --sync first", symbol, exchangeName)
|
2020-11-10 06:19:11 +00:00
|
|
|
}
|
|
|
|
|
2020-11-07 12:34:34 +00:00
|
|
|
lastPrice, ok := session.LastPrice(symbol)
|
|
|
|
if !ok {
|
2022-03-01 13:48:48 +00:00
|
|
|
return fmt.Errorf("last price not found: %s, %s", symbol, exchangeName)
|
2020-11-07 12:34:34 +00:00
|
|
|
}
|
|
|
|
|
2022-03-01 13:48:48 +00:00
|
|
|
color.Green("%s %s PROFIT AND LOSS REPORT", strings.ToUpper(exchangeName), symbol)
|
|
|
|
color.Green("===============================================")
|
2021-12-05 17:05:33 +00:00
|
|
|
|
2021-01-21 07:10:40 +00:00
|
|
|
report := calculator.Calculate(symbol, trades.Trades, lastPrice)
|
2020-11-07 12:34:34 +00:00
|
|
|
report.Print()
|
2022-05-06 11:16:15 +00:00
|
|
|
|
2022-05-10 10:27:23 +00:00
|
|
|
accountConfig := userConfig.Backtest.GetAccount(exchangeName)
|
2022-05-03 09:32:10 +00:00
|
|
|
initBalances := accountConfig.Balances.BalanceMap()
|
2022-04-23 07:43:11 +00:00
|
|
|
finalBalances := session.GetAccount().Balances()
|
2020-11-10 06:19:11 +00:00
|
|
|
|
2022-05-10 06:05:44 +00:00
|
|
|
if generatingReport {
|
2022-05-10 10:27:23 +00:00
|
|
|
result := backtest.SessionSymbolReport{
|
2022-05-09 17:06:16 +00:00
|
|
|
StartTime: startTime,
|
|
|
|
EndTime: endTime,
|
2021-12-05 17:42:53 +00:00
|
|
|
Symbol: symbol,
|
2021-12-09 03:57:46 +00:00
|
|
|
LastPrice: lastPrice,
|
|
|
|
StartPrice: startPrice,
|
2021-12-05 17:42:53 +00:00
|
|
|
PnLReport: report,
|
2021-12-05 17:05:33 +00:00
|
|
|
InitialBalances: initBalances,
|
2021-12-05 17:42:53 +00:00
|
|
|
FinalBalances: finalBalances,
|
2022-05-10 06:05:44 +00:00
|
|
|
Manifests: manifests,
|
2021-12-05 17:05:33 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 10:27:23 +00:00
|
|
|
if err := writeJsonFile(filepath.Join(outputDirectory, symbol+".json"), &result) ; err != nil {
|
2021-12-05 17:05:33 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-31 16:54:55 +00:00
|
|
|
initQuoteAsset := inQuoteAsset(initBalances, market, startPrice)
|
2022-02-09 10:23:35 +00:00
|
|
|
finalQuoteAsset := inQuoteAsset(finalBalances, market, lastPrice)
|
2022-05-10 10:27:23 +00:00
|
|
|
color.Green("INITIAL ASSET IN %s ~= %s %s (1 %s = %v)", market.QuoteCurrency, market.FormatQuantity(initQuoteAsset), market.QuoteCurrency, market.BaseCurrency, startPrice)
|
|
|
|
color.Green("FINAL ASSET IN %s ~= %s %s (1 %s = %v)", market.QuoteCurrency, market.FormatQuantity(finalQuoteAsset), market.QuoteCurrency, market.BaseCurrency, lastPrice)
|
2022-01-31 16:54:55 +00:00
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if report.Profit.Sign() > 0 {
|
|
|
|
color.Green("REALIZED PROFIT: +%v %s", report.Profit, market.QuoteCurrency)
|
2022-01-31 17:05:11 +00:00
|
|
|
} else {
|
2022-02-09 10:23:35 +00:00
|
|
|
color.Red("REALIZED PROFIT: %v %s", report.Profit, market.QuoteCurrency)
|
2022-01-31 17:40:51 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if report.UnrealizedProfit.Sign() > 0 {
|
|
|
|
color.Green("UNREALIZED PROFIT: +%v %s", report.UnrealizedProfit, market.QuoteCurrency)
|
2022-01-31 17:40:51 +00:00
|
|
|
} else {
|
2022-02-07 03:40:30 +00:00
|
|
|
color.Red("UNREALIZED PROFIT: %v %s", report.UnrealizedProfit, market.QuoteCurrency)
|
2022-01-31 17:05:11 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if finalQuoteAsset.Compare(initQuoteAsset) > 0 {
|
|
|
|
color.Green("ASSET INCREASED: +%v %s (+%s)", finalQuoteAsset.Sub(initQuoteAsset), market.QuoteCurrency, finalQuoteAsset.Sub(initQuoteAsset).Div(initQuoteAsset).FormatPercentage(2))
|
2022-01-31 16:54:55 +00:00
|
|
|
} else {
|
2022-02-07 03:40:30 +00:00
|
|
|
color.Red("ASSET DECREASED: %v %s (%s)", finalQuoteAsset.Sub(initQuoteAsset), market.QuoteCurrency, finalQuoteAsset.Sub(initQuoteAsset).Div(initQuoteAsset).FormatPercentage(2))
|
2022-01-31 16:54:55 +00:00
|
|
|
}
|
|
|
|
|
2020-11-11 06:39:33 +00:00
|
|
|
if wantBaseAssetBaseline {
|
2022-01-31 16:54:55 +00:00
|
|
|
// initBaseAsset := inBaseAsset(initBalances, market, startPrice)
|
|
|
|
// finalBaseAsset := inBaseAsset(finalBalances, market, lastPrice)
|
|
|
|
// log.Infof("INITIAL ASSET IN %s ~= %s %s (1 %s = %f)", market.BaseCurrency, market.FormatQuantity(initBaseAsset), market.BaseCurrency, market.BaseCurrency, startPrice)
|
|
|
|
// log.Infof("FINAL ASSET IN %s ~= %s %s (1 %s = %f)", market.BaseCurrency, market.FormatQuantity(finalBaseAsset), market.BaseCurrency, market.BaseCurrency, lastPrice)
|
2020-11-10 06:19:11 +00:00
|
|
|
|
2022-02-07 03:40:30 +00:00
|
|
|
if lastPrice.Compare(startPrice) > 0 {
|
|
|
|
color.Green("%s BASE ASSET PERFORMANCE: +%s (= (%s - %s) / %s)",
|
|
|
|
market.BaseCurrency,
|
|
|
|
lastPrice.Sub(startPrice).Div(startPrice).FormatPercentage(2),
|
|
|
|
lastPrice.FormatString(2),
|
|
|
|
startPrice.FormatString(2),
|
|
|
|
startPrice.FormatString(2))
|
2022-01-31 17:00:26 +00:00
|
|
|
} else {
|
2022-02-07 03:40:30 +00:00
|
|
|
color.Red("%s BASE ASSET PERFORMANCE: %s (= (%s - %s) / %s)",
|
|
|
|
market.BaseCurrency,
|
|
|
|
lastPrice.Sub(startPrice).Div(startPrice).FormatPercentage(2),
|
|
|
|
lastPrice.FormatString(2),
|
|
|
|
startPrice.FormatString(2),
|
|
|
|
startPrice.FormatString(2))
|
2022-01-31 17:00:26 +00:00
|
|
|
}
|
2020-11-11 06:39:33 +00:00
|
|
|
}
|
2020-11-07 12:34:34 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-07 12:11:07 +00:00
|
|
|
|
2020-11-06 18:57:50 +00:00
|
|
|
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
|
|
|
|
2022-05-10 10:27:23 +00:00
|
|
|
func writeJsonFile(p string, obj interface{}) error {
|
|
|
|
out, err := json.MarshalIndent(obj, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return ioutil.WriteFile(p, out, 0644)
|
|
|
|
}
|
|
|
|
|
2022-05-10 05:25:03 +00:00
|
|
|
func safeMkdirAll(p string) error {
|
|
|
|
st, err := os.Stat(p)
|
|
|
|
if err == nil {
|
|
|
|
if !st.IsDir() {
|
|
|
|
return fmt.Errorf("path %s is not a directory", p)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return os.MkdirAll(p, 0755)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|