bbgo: fix kline backward query for backtest

This commit is contained in:
c9s 2021-10-16 13:49:00 +08:00
parent 4bcea5a388
commit 30c7c34826
2 changed files with 7 additions and 6 deletions

View File

@ -408,7 +408,7 @@ func (session *ExchangeSession) initSymbol(ctx context.Context, environ *Environ
for interval := range klineSubscriptions { for interval := range klineSubscriptions {
// avoid querying the last unclosed kline // avoid querying the last unclosed kline
endTime := environ.startTime.Add(-interval.Duration()) endTime := environ.startTime
kLines, err := session.Exchange.QueryKLines(ctx, symbol, interval, types.KLineQueryOptions{ kLines, err := session.Exchange.QueryKLines(ctx, symbol, interval, types.KLineQueryOptions{
EndTime: &endTime, EndTime: &endTime,
Limit: 1000, // indicators need at least 100 Limit: 1000, // indicators need at least 100

View File

@ -98,9 +98,9 @@ func (s *BacktestService) QueryKLinesForward(exchange types.ExchangeName, symbol
rows, err := s.DB.NamedQuery(sql, map[string]interface{}{ rows, err := s.DB.NamedQuery(sql, map[string]interface{}{
"start_time": startTime, "start_time": startTime,
"limit": limit, "limit": limit,
"symbol": symbol, "symbol": symbol,
"interval": interval, "interval": interval,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
@ -110,12 +110,13 @@ func (s *BacktestService) QueryKLinesForward(exchange types.ExchangeName, symbol
} }
func (s *BacktestService) QueryKLinesBackward(exchange types.ExchangeName, symbol string, interval types.Interval, endTime time.Time, limit int) ([]types.KLine, error) { func (s *BacktestService) QueryKLinesBackward(exchange types.ExchangeName, symbol string, interval types.Interval, endTime time.Time, limit int) ([]types.KLine, error) {
sql := "SELECT * FROM `binance_klines` WHERE `end_time` <= :end_time AND `symbol` = :symbol AND `interval` = :interval ORDER BY end_time ASC LIMIT :limit" sql := "SELECT * FROM `binance_klines` WHERE `end_time` <= :end_time AND `symbol` = :symbol AND `interval` = :interval ORDER BY end_time DESC LIMIT :limit"
sql = strings.ReplaceAll(sql, "binance_klines", exchange.String()+"_klines") sql = strings.ReplaceAll(sql, "binance_klines", exchange.String()+"_klines")
sql = "SELECT t.* FROM (" + sql + ") AS t ORDER BY t.end_time ASC"
rows, err := s.DB.NamedQuery(sql, map[string]interface{}{ rows, err := s.DB.NamedQuery(sql, map[string]interface{}{
"limit": limit, "limit": limit,
"end_time": endTime, "end_time": endTime,
"symbol": symbol, "symbol": symbol,
"interval": interval, "interval": interval,
}) })