avoid recording trades in backtest by default

introducing a RecordTrades option
This commit is contained in:
c9s 2021-12-06 01:42:53 +08:00
parent 85bb9f214e
commit 0472b7f21e
3 changed files with 32 additions and 23 deletions

View File

@ -98,6 +98,8 @@ type Backtest struct {
StartTime string `json:"startTime" yaml:"startTime"`
EndTime string `json:"endTime" yaml:"endTime"`
// RecordTrades is an option, if set to true, back-testing should record the trades into database
RecordTrades bool `json:"recordTrades,omitempty" yaml:"recordTrades,omitempty"`
Account BacktestAccount `json:"account" yaml:"account"`
Symbols []string `json:"symbols" yaml:"symbols"`
}

View File

@ -302,7 +302,11 @@ func (session *ExchangeSession) Init(ctx context.Context, environ *Environment)
session.UserDataStream.OnOrderUpdate(session.OrderExecutor.EmitOrderUpdate)
session.Account.BindStream(session.UserDataStream)
// insert trade into db right before everything
// TODO: move this logic to Environment struct
// if back-test service is not set, meaning we are not back-testing
// we should insert trade into db right before everything
if environ.BacktestService == nil {
// if trade service is configured, we have the db configured
if environ.TradeService != nil {
session.UserDataStream.OnTradeUpdate(func(trade types.Trade) {
if err := environ.TradeService.Insert(trade); err != nil {
@ -310,6 +314,7 @@ func (session *ExchangeSession) Init(ctx context.Context, environ *Environment)
}
})
}
}
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
log.WithField("marketData", "kline").Infof("kline closed: %+v", kline)

View File

@ -221,9 +221,10 @@ var BacktestCmd = &cobra.Command{
}
}
log.Warn("!!! To run backtest, you should use an isolated database for storing backtest trades !!!")
log.Warn("!!! The trade record in the current database WILL ALL BE DELETE !!!")
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
@ -233,6 +234,7 @@ var BacktestCmd = &cobra.Command{
if err := environ.TradeService.DeleteAll(); err != nil {
return err
}
}
backtestExchange := backtest.NewExchange(exchangeName, backtestService, userConfig.Backtest)
environ.SetStartTime(startTime)