How ChartingLens backtests a strategy
The exact rules the backtesting engine uses to fill trades and calculate results, what it does not model, and three example strategies with their source code so you can reproduce the numbers yourself.
- Orders fill at the open of the bar after the signal. Stops and targets fill inside the bar at their level, or at the open when price gaps through.
- One position at a time, long or short, using the full account with no leverage. Returns compound from trade to trade.
- Signals cannot see the future: levels come from the prior bar, and higher-timeframe data is withheld until that bar has closed.
- Headline results include no commissions, slippage or dividends. The Monte Carlo panel shows the same trades with slippage applied.
- Every example below lists its symbol, timeframe, data window and full source code.
Where a strategy comes from
Every backtest in ChartingLens runs a strategy written in Pine Script. You can paste your own script into AI Chat, pick one of the built-in preset strategies, or describe the rules in plain English and let the AI write the script. Whichever way it starts, the engine trades the script's orders (strategy.entry, strategy.close and strategy.exit), and the same script draws the buy and sell markers on the chart, so the markers and the trade log always agree.
How orders are filled
- Entries and signal exits fill at the next bar's open. A signal on the last bar on the chart does not fill, because that bar's next open has not happened yet.
- Stop and target exits (
strategy.exitwithstoporlimit) fill during the bar at the level. If the bar opens beyond the level, the fill is the open, which is why a stop can lose more than its distance. - Resting entries (stop and limit entry orders) fill at their level the same way.
- One position at a time. Strategies can go long, short, or both, but never hold two positions at once.
- An open position at the end is shown separately, marked to the last price, and left out of every statistic.
How the engine avoids looking ahead
A backtest that peeks at future bars looks brilliant and trades badly. Three rules keep future data out:
- Stop, target and entry levels are read from the bar before the one being tested, never from the bar itself.
- Data from a higher timeframe or another symbol is only visible to the strategy once that bar has closed.
- Strategies that are converted rather than transpiled line by line are spot-checked: the engine re-runs them on growing slices of history at a sample of signals and checkpoints, and confirms those signals would have printed with only the bars that existed at the time.
How results are calculated
- Trade return: (exit price − entry price) ÷ entry price, reversed for shorts.
- Total return: the trade returns compounded in order, so each trade starts from the account value the previous trade left.
- Win rate: closed trades with a positive return, divided by all closed trades. A breakeven trade counts as a loss.
- Profit factor: the sum of winning trade returns divided by the sum of losing trade returns.
- Max drawdown: the largest fall from a peak in the compounded account value, measured from one closed trade to the next.
- Average win, average loss, best and worst trade: per closed trade, in percent.
Monte Carlo and stress tests
Any backtest with five or more closed trades can be stress tested. The engine resamples the closed trades 2,000 times to show the range of returns and drawdowns the same edge could have produced, and the odds of a 10%, 20%, 30% or 50% drawdown. It shuffles the trade order another 2,000 times to test drawdowns and losing streaks, and replays the trades under fixed scenarios: without the best 10% of trades, with 0.1% and 0.3% slippage per side, with winners halved, with losses 50% larger, and with every loser first. The resampling is seeded, so the same backtest always reports the same figures. Fewer than 30 trades is flagged as a small sample.
Find Best Timeframe
This test re-runs a strategy on the 15-minute, 1-hour, 4-hour and daily charts. Each timeframe covers a different amount of history (see below), so the ranking uses annualized return and a per-trade Sharpe ratio rather than raw total return.
Data used
- Daily bars cover the full history available for the symbol, back to 1993 for SPY and 1991 for Apple and Microsoft.
- Intraday bars for stocks and ETFs cover about the last month on the 15-minute chart and about the last two years on the 1-hour and 4-hour charts.
- Stock prices are adjusted for splits. Dividends are not added back, so long holding periods in dividend-paying stocks are understated.
- Pre-market and after-hours bars are included only when extended hours is switched on for the chart.
What the engine does not model
- Commissions and exchange fees.
- Slippage and the bid-ask spread, outside the Monte Carlo scenarios above.
- Dividends, and borrowing costs for short positions.
- Partial fills, liquidity and the market impact of large orders.
- Survivorship: a backtest runs on a symbol that still trades today, which flatters any strategy tested on a list of today's winners.
- Position sizing other than the full account, and more than one position at a time.
Backtests describe how a set of rules would have traded the past. They do not predict future results.
Three examples you can reproduce
Each example below ran on the daily chart in ChartingLens, through the same engine and with the same settings every user gets. To reproduce one, load the symbol on the 1D timeframe, paste the script into AI Chat, and click Backtest Signals. Pine Script conversion is part of Premium; a free account can run the built-in preset strategies. Each new daily bar can move the results slightly, so compare against the data window listed. Buy and hold is the price change over the same window, from the same bars, without dividends.
1. EMA 20/50 trend on SPY
//@version=5
strategy("EMA 20/50 Trend", overlay=true)
fast = ta.ema(close, 20)
slow = ta.ema(close, 50)
plot(fast, "EMA 20", color.aqua, 2)
plot(slow, "EMA 50", color.orange, 2)
if ta.crossover(fast, slow)
strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
strategy.close("Long")
| Closed trades | 69 |
|---|---|
| Win rate | 44.9% (31 won, 38 lost) |
| Total return | +637.31% |
| Max drawdown | −32.74% |
| Profit factor | 3.06 |
| Average win / average loss | +11.27% / −3.00% |
| Best / worst trade | +47.38% / −7.72% |
| Buy and hold, same window | +1,613.1% |
A classic trend filter: it loses more often than it wins, but its average win is almost four times its average loss. It also trailed simply holding SPY over the same 33 years, because it sits out every pullback that crosses the averages and buys back higher.
2. RSI(14) 30/70 mean reversion on Apple
//@version=5
strategy("RSI 30/70 Mean Reversion", overlay=false)
r = ta.rsi(close, 14)
plot(r, "RSI 14", color.purple)
hline(30)
hline(70)
if ta.crossover(r, 30)
strategy.entry("Long", strategy.long)
if ta.crossover(r, 70)
strategy.close("Long")
| Closed trades | 28 |
|---|---|
| Win rate | 78.6% (22 won, 6 lost) |
| Total return | +47.30% |
| Max drawdown | −57.62% |
| Profit factor | 1.55 |
| Average win / average loss | +10.37% / −24.60% |
| Best / worst trade | +30.87% / −40.27% |
| Buy and hold, same window | +71,240% |
Why a high win rate alone means little: nearly four in five trades won, yet the strategy made 47% in 35 years with a 57.6% drawdown. With no stop, a few trades that bought an oversold stock which kept falling erased most of the small wins. RSI here uses Wilder's smoothing, the standard formula.
3. 20-day breakout with an 8% stop on Microsoft
//@version=5
strategy("20-Day Breakout, 8% Stop", overlay=true)
upper = ta.highest(high, 20)[1]
lower = ta.lowest(low, 10)[1]
plot(upper, "20-day high", color.green)
plot(lower, "10-day low", color.red)
if close > upper and strategy.position_size == 0
strategy.entry("Long", strategy.long)
if strategy.position_size > 0
strategy.exit("Stop", "Long", stop=strategy.position_avg_price * 0.92)
if close < lower
strategy.close("Long")
| Closed trades | 136 (129 by the 10-day low, 7 by the stop) |
|---|---|
| Win rate | 50.0% (68 won, 68 lost) |
| Total return | +3,344.59% |
| Max drawdown | −31.83% |
| Profit factor | 2.54 |
| Average win / average loss | +10.13% / −3.98% |
| Best / worst trade | +42.77% / −8.94% |
| Open position at the end | −4.38%, not in the statistics |
| Buy and hold, same window | +26,022% |
This one shows the stop rules at work. Seven trades ended at the 8% stop, and the worst trade lost 8.94%, not 8%, because the stock opened below the stop and the fill came at the open. It also shows an open position reported on its own line instead of inside the totals.
Independent replication
We re-ran all three examples above in Backtesting.py 0.6.6, an open-source Python backtester that shares no code with ChartingLens. It used the same daily bars, the indicators written from their standard definitions, and the same settings: fills at the next bar's open, no commission or slippage, the full account in each trade.
| Strategy | Trades matched |
|---|---|
| EMA 20/50 trend on SPY | 69 of 69 (+637.31%, −32.74% max drawdown, profit factor 3.06 in both) |
| RSI 30/70 mean reversion on Apple | 28 of 28 (+47.30%, −57.62% max drawdown, profit factor 1.55 in both) |
| 20-day breakout, 8% stop, on Microsoft | 136 of 136 (+3,344.59%, −31.83% max drawdown, profit factor 2.54 in both) |
Every trade matched exactly: the same entry day, exit day, entry price and exit price, for all 233 of them. Every figure in the examples matched too, including the open Microsoft position at −4.38%.
Look-ahead test
We also ran each example on its history cut off at 20 different points. If the engine or a strategy used later bars, removing those bars would change the trades before the cutoff. Across 60 shortened runs and 2,247 trade comparisons, not one trade changed.
Files
- independent_backtest.py: the Backtesting.py replication, with the indicators and statistics written out
- EMA 20/50 on SPY, RSI 30/70 on Apple and breakout on Microsoft: every trade from both engines, side by side
- comparison.json and lookahead.json: the summary results
The price data isn't included, because we can't redistribute it. Split-adjusted daily bars from any provider for the same windows will reproduce these trades closely; providers adjust prices slightly differently, which can move an individual trade.
Comparing results with other platforms
Strategy testers on other platforms often default to a fixed order size, add a commission, or fill on the signal bar's close. To compare like for like with these examples, set the order size to 100% of equity, set commission and slippage to zero, and fill on the next bar's open.
Questions
- Does ChartingLens include commissions and slippage in backtests?
- No. Headline results assume no commissions and fills at the next bar's open with no slippage. The Monte Carlo and stress test panel shows the same backtest with 0.1% and 0.3% slippage per side so you can see how sensitive it is to trading costs.
- Can a backtest use future data?
- Orders fill on the bar after the signal, levels come from the prior bar, and data from higher timeframes or other symbols stays hidden until that bar has closed. Converted strategies are also spot-checked on growing slices of history to confirm their signals would have printed at the time.
- How is position size handled?
- Each trade uses the full account, with no leverage, and returns compound from trade to trade. One position is open at a time, long or short.
- Is backtesting free?
- The built-in preset strategies run on every plan for one AI credit each. Backtesting a strategy you describe or paste in, and Pine Script conversion, are part of Premium and Pro.