diff --git a/backtesting.go b/backtesting.go index 053390d..8dd70fb 100644 --- a/backtesting.go +++ b/backtesting.go @@ -67,8 +67,15 @@ func (b *TestBroker) Advance() { } func (b *TestBroker) Candles(symbol string, frequency string, count int) (*DataFrame, error) { + start := Max(Max(b.candleCount, 1)-count, 0) + end := b.candleCount - 1 + if b.Data != nil && b.candleCount >= b.Data.Len() { // We have data and we are at the end of it. - return b.Data.Copy(0, -1).(*DataFrame), ErrEOF + if count >= b.Data.Len() { // We are asking for more data than we have. + return b.Data.Copy(0, -1).(*DataFrame), ErrEOF + } else { + return b.Data.Copy(start, -1).(*DataFrame), ErrEOF + } } else if b.DataBroker != nil && b.Data == nil { // We have a data broker but no data. // Fetch a lot of candles from the broker so we don't keep asking. candles, err := b.DataBroker.Candles(symbol, frequency, Max(count, 1000)) @@ -82,9 +89,6 @@ func (b *TestBroker) Candles(symbol string, frequency string, count int) (*DataF // TODO: check if count > our rows if we are using a data broker and then fetch more data if so. - end := b.candleCount - 1 - start := Max(Max(b.candleCount, 1)-count, 0) - return b.Data.Copy(start, end).(*DataFrame), nil } diff --git a/backtesting_test.go b/backtesting_test.go index 22466f8..f03cb46 100644 --- a/backtesting_test.go +++ b/backtesting_test.go @@ -65,8 +65,8 @@ func TestBacktestingBrokerCandles(t *testing.T) { for i := 0; i < 7; i++ { // 6 because we want to call broker.Candles 9 times total broker.Advance() candles, err = broker.Candles("EUR_USD", "D", 5) - if err != nil { - t.Fatalf("Got an error on iteration %d: %v (called Candles %d times)", i, err, 2+i+1) + if err != nil && err != ErrEOF && i != 6 { // Allow ErrEOF on last iteration. + t.Fatalf("Got an error on iteration %d: %v (called Advance() %d times)", i, err, broker.CandleIndex()+1) } if candles == nil { t.Errorf("Candles is nil on iteration %d", i+1)