Move the logic from next() into an on_bar that returns its order, and move the costs from Cerebro's broker into rr.backtest. A Backtrader strategy already decides one bar at a time, so the decisions carry over as they are. What changes is where the indicators, orders and costs are written.
What maps to what
bt.Strategysubclass becomes a class withon_bar(self, data), an object with that method, or a plainon_barfunction.__init__indicators become arrays:data.close[-10:].mean()is a 10-bar SMA.lookbacksets how many past barsdataholds.self.data.close[0]isdata.close[-1], the bar that just closed.self.positionisdata.position(), the signed quantity.buy_bracket(stopprice=..., limitprice=...)isrr.buy_market(qty, stop_loss=..., take_profit=...). The stop and target are part of the order, so there are no child orders to track or cancel.self.close()isrr.close_position().cerebro.broker.setcommissionand slippage settings arecommission_per_unit=andspread=onrr.backtest.GenericCSVDatacolumn mapping is a CSV path, a pandas DataFrame or a NumPy bar array passed straight torr.backtest.- Analyzers are fields on the result: net P&L, return, closed trades, win rate, profit factor, Sharpe, Sortino, maximum drawdown and fees print with
print(result), andresult.closed_tradeslists every trade.
The Backtrader version
A 10 and 30 bar SMA crossover that enters with a 1% stop and a 2% target, and exits early on the cross back down.
import backtrader as bt
class SmaCross(bt.Strategy):
def __init__(self):
fast = bt.ind.SMA(period=10)
slow = bt.ind.SMA(period=30)
self.cross = bt.ind.CrossOver(fast, slow)
self.bracket = []
def notify_order(self, order):
if not order.alive() and order in self.bracket:
self.bracket.remove(order)
def next(self):
if not self.position and not self.bracket and self.cross > 0:
price = self.data.close[0]
self.bracket = self.buy_bracket(size=100, exectype=bt.Order.Market,
stopprice=price * 0.99,
limitprice=price * 1.02)
elif self.position and self.cross < 0:
for order in self.bracket:
self.cancel(order)
self.close()
cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.GenericCSVData(
dataname='SAMPLE_5min.csv', dtformat='%Y-%m-%d', tmformat='%H:%M:%S',
datetime=0, time=1, open=2, high=3, low=4, close=5, volume=6,
openinterest=-1, timeframe=bt.TimeFrame.Minutes, compression=5))
cerebro.addstrategy(SmaCross)
cerebro.broker.setcash(100_000)
cerebro.broker.setcommission(commission=0.005, commtype=bt.CommInfoBase.COMM_FIXED)
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trades')
strat = cerebro.run()[0]
t = strat.analyzers.trades.get_analysis()
print('net', round(cerebro.broker.getvalue() - 100_000, 2), 'trades', t.total.closed)
The Reamer Research version
import reamer_research as rr
class SmaCross:
lookback = 31
def on_bar(self, data):
close = data.close
fast_now, slow_now = close[-10:].mean(), close[-30:].mean()
fast_prev, slow_prev = close[-11:-1].mean(), close[-31:-1].mean()
crossed_up = fast_prev <= slow_prev and fast_now > slow_now
crossed_down = fast_prev >= slow_prev and fast_now < slow_now
if data.position() == 0 and crossed_up:
price = close[-1]
return rr.buy_market(100, stop_loss=price * 0.99,
take_profit=price * 1.02)
if data.position() > 0 and crossed_down:
return rr.close_position()
result = rr.backtest(SmaCross, 'SAMPLE_5min.csv', initial_capital=100_000,
commission_per_unit=0.005, spread=0.01, rng_seed=1)
print(result)
More strategies in the same shape, with stop and target brackets, limit entries, risk-based sizing and several tickers, and loaders for CSV, .bin, Parquet, Alpaca and Databento bars, are in the Reamer Research examples repository on GitHub under the MIT licence, in Python, with C++ versions of the core examples.
To port with an AI assistant, the Reamer Research MCP server lets Claude Code, Claude Desktop or Cursor write the on_bar version, backtest it on your bars and compare its closed trades with the original's.
Running both on the same bars
On the Reamer Research kit's synthetic SAMPLE_5min.csv, with Backtrader 1.9.78.123 and Reamer Research 4.11.3:
- Backtrader: 37 closed trades, net −476.47.
- Reamer Research: 39 closed trades, net −643.17, the same on every run.
Both engines fill a market order on the next bar, so the entries line up. The totals differ because the Reamer Research run pays a 0.01 spread on every fill, which this Backtrader setup does not charge, and because the two engines settle a bar that touches both the stop and the target differently. Backtrader decides that bar from its open, high, low and close. Reamer Research walks a seeded tick path inside the bar. Set spread=0 to compare the fill rules alone.
What you get after the port
- Visual trade diagnostics. Every closed trade on its own bars beside every value your strategy printed, to check each entry and exit against the rules.
- Repeatable results. The same data, settings and seed give the same result to the byte.
- Monte Carlo.
result.monte_carlo(simulations=10000, seed=0)resamples the per-trade returns into loss, ruin and maximum-drawdown percentiles. - Live and paper trading. The relay sends the orders
on_barreturns to your broker through the open-source receiver.
The four-engine benchmark
What a Backtest Costs ran Backtrader, NautilusTrader, QuantConnect LEAN and Reamer Research on the same strategies and data, on one AMD EPYC 9575F with Reamer Research 4.6.0. On one backtest of 500,000 bars, a 20-bar breakout with no costs, Backtrader took 15.04 s. Reamer Research took 3.38 s from Python and 0.36 s from C++.
The benchmark repository on GitHub has a runner for each of the four engines, the dataset builders and the raw results. Its Reamer Research runners use the same Python package and C++ header as the code above, so you can rerun every engine on your own machine. The study's author builds and sells Reamer Research, which is why the runners are public.
Reamer Research runs on Linux, macOS, or Windows through WSL2, from Python or C++. The free download runs both examples above in Evaluation Mode, on one ticker over up to 30 days of bars. A licence costs $20 per seat per month, cancel any time.