Move the logic from OnData into an on_bar that returns its order, and move the cash, data and fee settings from Initialize into one rr.backtest call. A LEAN algorithm already decides one bar at a time, so the decisions carry over. The biggest change is the bracket: LEAN has no single bracket order, so a stop and a target are two separate orders that your code has to cancel against each other. In Reamer Research they are part of the entry order.
What maps to what
QCAlgorithmsubclass becomes a class withon_bar(self, data), an object with that method, or a plainon_barfunction.OnData(self, data)ison_bar(self, data), and it returns the order instead of placing it.self.SMA(symbol, 10)and other indicators become arrays:data.close[-10:].mean()is a 10-bar SMA.lookbacksets how many past barsdataholds.self.Portfolio[symbol].Investedisdata.position() != 0, and.Quantityisdata.position().MarketOrderplus aStopMarketOrderand aLimitOrder, cancelled against each other inOnOrderEvent, isrr.buy_market(qty, stop_loss=..., take_profit=...). When one exit fills, the other ends with it.Transactions.CancelOpenOrdersandLiquidatearerr.close_position().SetCash,SetFeeModel,SetStartDateandSetEndDateareinitial_capital=,commission_per_unit=andspread=, andstart=andend=onrr.backtest.AddEquity, or aPythonDataclass for your own files, is a CSV path, a pandas DataFrame or a NumPy bar array passed straight torr.backtest. The kit also includes fetchers for Alpaca and Databento bars, on your own vendor accounts.- The statistics LEAN prints at the end 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 LEAN 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. The SampleBar class loads the same CSV file as the Reamer Research version; on QuantConnect's own data you would call AddEquity instead.
from AlgorithmImports import *
class SampleBar(PythonData):
def GetSource(self, config, date, is_live):
return SubscriptionDataSource('SAMPLE_5min.csv', SubscriptionTransportMedium.LocalFile)
def Reader(self, config, line, date, is_live):
if not line or line[0].isalpha():
return None
d, t, o, h, l, c, v = line.split(',')
bar = SampleBar()
bar.Symbol = config.Symbol
bar.Time = datetime.strptime(d + ' ' + t, '%Y-%m-%d %H:%M:%S')
bar.EndTime = bar.Time + timedelta(minutes=5)
bar.Value = float(c)
bar['Open'], bar['High'], bar['Low'], bar['Close'] = float(o), float(h), float(l), float(c)
return bar
class SmaCross(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2025, 1, 1)
self.SetEndDate(2025, 2, 1)
self.SetCash(100_000)
self.SetTimeZone(TimeZones.Utc)
self.SetBenchmark(lambda dt: 0)
self.symbol = self.AddData(SampleBar, 'SAMPLE', Resolution.Minute, TimeZones.Utc).Symbol
self.Securities[self.symbol].SetFeeModel(ConstantFeeModel(0.50))
self.fast = self.SMA(self.symbol, 10)
self.slow = self.SMA(self.symbol, 30)
self.prev = None
self.stop = self.target = None
def OnData(self, data):
if self.symbol not in data or not self.slow.IsReady:
return
diff, prev = self.fast.Current.Value - self.slow.Current.Value, self.prev
self.prev = diff
if prev is None:
return
invested = self.Portfolio[self.symbol].Invested
if not invested and self.stop is None and prev <= 0 < diff:
price = data[self.symbol].Value
self.MarketOrder(self.symbol, 100)
self.stop = self.StopMarketOrder(self.symbol, -100, price * 0.99)
self.target = self.LimitOrder(self.symbol, -100, price * 1.02)
elif invested and prev >= 0 > diff:
self.Transactions.CancelOpenOrders(self.symbol)
self.Liquidate(self.symbol)
self.stop = self.target = None
def OnOrderEvent(self, event):
if event.Status != OrderStatus.Filled or self.stop is None:
return
# one side of the bracket filled: cancel the other
if event.OrderId == self.stop.OrderId:
self.target.Cancel()
self.stop = self.target = None
elif event.OrderId == self.target.OrderId:
self.stop.Cancel()
self.stop = self.target = None
def OnEndOfAlgorithm(self):
trades = len(self.TradeBuilder.ClosedTrades)
net = self.Portfolio.TotalPortfolioValue - 100_000
self.Debug(f'RESULT net {net:.2f} trades {trades}')
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 the open-source LEAN engine built from source (commit f3d841e, October 2026) and Reamer Research 4.11.3, both charging 0.005 per share:
- LEAN: 37 closed trades, net −465.50.
- Reamer Research: 39 closed trades, net −643.17, the same on every run.
The totals differ for three reasons. LEAN fills a market order placed in OnData at the price of the bar that triggered it, and Reamer Research fills it on the first tick of the next bar. The Reamer Research run pays a 0.01 spread on every fill, which this LEAN setup does not charge. And each engine has its own rule for a bar that touches both the stop and the target; 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
- Your own machine and your own data. Backtests run locally on Linux, macOS, or Windows through WSL2, on bars from any vendor you choose.
- 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. - 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, LEAN took 22.10 s, including a fixed start of 3.3 to 3.9 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 costs $20 per seat per month, cancel any time. The free download runs the Reamer Research example above in Evaluation Mode, on one ticker over up to 30 days of bars.