Move the logic from your strategy's on_bar into an on_bar that returns its order, and replace the engine, venue, instrument and fee model setup with one rr.backtest call. NautilusTrader and Reamer Research both hand a strategy one bar at a time, so the decisions carry over. What changes is how much has to be set up around them.
What maps to what
Strategysubclass with aStrategyConfigbecomes a class withon_bar(self, data), an object with that method, or a plainon_barfunction. Settings are class or object attributes.- Registered indicators become arrays:
data.close[-10:].mean()is a 10-bar SMA.lookbacksets how many past barsdataholds. self.portfolio.is_flat(instrument_id)isdata.position() == 0.order_factory.bracket(...)andsubmit_order_listarerr.buy_market(qty, stop_loss=..., take_profit=...), returned fromon_bar.cancel_all_ordersandclose_all_positionsarerr.close_position(). Closing the position also ends its stop and target.BacktestEngine,add_venue, the instrument and the fee model arerr.backtest(strategy, bars, initial_capital=..., commission_per_unit=..., spread=...).BarDataWranglerandBarTypeare a CSV path, a pandas DataFrame or a NumPy bar array passed straight torr.backtest.- Reports 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 NautilusTrader 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 pandas as pd
from nautilus_trader.backtest.engine import BacktestEngine, BacktestEngineConfig
from nautilus_trader.backtest.models import FixedFeeModel
from nautilus_trader.config import StrategyConfig
from nautilus_trader.indicators import SimpleMovingAverage
from nautilus_trader.model import Bar, BarType, InstrumentId, Money, TraderId, Venue
from nautilus_trader.model.currencies import USD
from nautilus_trader.model.enums import AccountType, OmsType, OrderSide
from nautilus_trader.persistence.wranglers import BarDataWrangler
from nautilus_trader.test_kit.providers import TestInstrumentProvider
from nautilus_trader.trading.strategy import Strategy
class SmaCrossConfig(StrategyConfig, frozen=True):
instrument_id: InstrumentId
bar_type: BarType
class SmaCross(Strategy):
def __init__(self, config):
super().__init__(config)
self.fast = SimpleMovingAverage(10)
self.slow = SimpleMovingAverage(30)
self.prev = None
def on_start(self):
self.instrument = self.cache.instrument(self.config.instrument_id)
self.register_indicator_for_bars(self.config.bar_type, self.fast)
self.register_indicator_for_bars(self.config.bar_type, self.slow)
self.subscribe_bars(self.config.bar_type)
def on_bar(self, bar: Bar):
if not self.slow.initialized:
return
diff, prev, self.prev = self.fast.value - self.slow.value, self.prev, self.fast.value - self.slow.value
if prev is None:
return
iid = self.config.instrument_id
flat = self.portfolio.is_flat(iid)
if flat and prev <= 0 < diff and not self.cache.orders_open(instrument_id=iid):
price = bar.close.as_double()
orders = self.order_factory.bracket(
instrument_id=iid, order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(100),
sl_trigger_price=self.instrument.make_price(price * 0.99),
tp_price=self.instrument.make_price(price * 1.02))
self.submit_order_list(orders)
elif not flat and prev >= 0 > diff:
self.cancel_all_orders(iid)
self.close_all_positions(iid)
engine = BacktestEngine(BacktestEngineConfig(trader_id=TraderId('BACKTESTER-001')))
engine.add_venue(venue=Venue('XNAS'), oms_type=OmsType.NETTING,
account_type=AccountType.CASH, base_currency=USD,
starting_balances=[Money(100_000, USD)],
fee_model=FixedFeeModel(Money(0.50, USD)))
instrument = TestInstrumentProvider.equity(symbol='SAMPLE', venue='XNAS')
engine.add_instrument(instrument)
df = pd.read_csv('SAMPLE_5min.csv')
# the CSV stamps a bar at its open; NautilusTrader stamps it at its close
df.index = pd.to_datetime(df.Date + ' ' + df.Time, utc=True) + pd.Timedelta(minutes=5)
df = df.rename(columns=str.lower)[['open', 'high', 'low', 'close', 'volume']]
bar_type = BarType.from_str('SAMPLE.XNAS-5-MINUTE-LAST-EXTERNAL')
engine.add_data(BarDataWrangler(bar_type, instrument).process(df))
engine.add_strategy(SmaCross(SmaCrossConfig(instrument_id=instrument.id, bar_type=bar_type)))
engine.run()
pos = engine.trader.generate_positions_report()
net = sum(float(pnl.split()[0]) for pnl in pos.realized_pnl)
print('net', round(net, 2), 'positions', len(pos))
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 NautilusTrader 1.231.0 and Reamer Research 4.11.3, both charging 0.005 per share:
- NautilusTrader: 38 positions, net −587.50.
- Reamer Research: 39 closed trades, net −643.17, the same on every run.
The totals differ because the Reamer Research run pays a 0.01 spread on every fill, which this NautilusTrader setup does not charge, and because each engine has its own rules for when an order placed on a bar fills and which level a bar that touches both the stop and the target hits first. Reamer Research fills a market order on the first tick of the next bar and walks a seeded tick path inside each 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, where you write the calls to your broker's API. - Python or C++. The same strategy shape runs from either language.
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, NautilusTrader took 76.85 s as installed, and 13.61 s with record_trade patched out. 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. The free download runs the Reamer Research example 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.