Bollinger Bands Backtest Demo
Explore how to use Exchange Outpost to evaluate a trading strategy by backtesting it on multiple symbols simultaneously.
Variance is a statistical measurement of the spread between numbers in a data set. In finance, variance is used to measure the volatility of an asset's price over time. A high variance indicates that the price of the asset has been more volatile, while a low variance indicates that the price has been more stable.
Low Variance (σ² = 0.04)
Mean: $100.15 | Stable price movement
High Variance (σ² = 104.80)
Mean: $100.00 | Volatile price movement
Key Insight: The dashed line represents the mean price. Notice how the low variance data stays close to the mean, while the high variance data spreads much further from it. This spread (variance) is what Bollinger Bands use to create their upper and lower boundaries.
In financial markets, price movements often follow patterns similar to a normal distribution around a moving average. This statistical behavior is the foundation of many trading strategies, including Bollinger Bands.
The Normal Distribution (Bell Curve) tells us that:
- 68% of price movements stay within 1 standard deviation of the mean
- 95% of price movements stay within 2 standard deviations of the mean
- 99.7% of price movements stay within 3 standard deviations of the mean
68% of prices fall within ±1σ of the mean
68% of prices fall within ±1σ of the mean
95% of prices fall within ±2σ of the mean
Statistical Foundation: In a normal distribution, approximately 95% of all values fall within 2 standard deviations of the mean. This means that when a price moves beyond the ±2σ bands, it's statistically "unusual" and likely to revert back toward the mean. This is the mathematical basis for Bollinger Bands trading signals.
When a price moves beyond 2 standard deviations (the outer Bollinger Bands), it's statistically unusual - happening only about 5% of the time. This rarity suggests the price is likely to revert back toward the mean, making it an attractive entry point for mean reversion trades.
Trading Insight: The mathematical probability that prices will stay within the bands most of the time (95%) is what makes Bollinger Bands effective. When prices do break out beyond 2σ, the statistical tendency is for them to "snap back" toward the moving average.
Bollinger Bands are a type of statistical chart characterizing the prices and volatility over time of a financial instrument or commodity, using a formulaic method propounded by John Bollinger in the 1980s. Financial traders employ these charts as a methodical tool to inform trading decisions, control automated trading systems, or as a component of technical analysis.
Bollinger Bands consist of three lines:
- A simple moving average (SMA) in the middle.
- An upper band, which is the SMA plus a certain number of standard deviations (typically 2).
- A lower band, which is the SMA minus the same number of standard deviations.
Simple Moving Average - the baseline trend
SMA ± 2 standard deviations - volatility boundaries
Actual price movement relative to the bands
Trading Signals: When price touches the upper band (day 9, 11), it may indicate an overbought condition. When price touches the lower band (day 10), it may indicate an oversold condition. Notice how the bands expand during volatile periods and contract during stable periods.
The bands expand and contract based on market volatility. When the market is more volatile, the bands widen, and when the market is less volatile, the bands contract.
When the price of the asset moves closer to the upper band, it is considered overbought, and when it moves closer to the lower band, it is considered oversold. Traders often use Bollinger Bands to identify potential buy and sell signals.
The basic idea behind the strategy is to buy when the price of the asset moves below the lower band and sell when it moves above the upper band.
The strategy can be implemented in the following steps:
- Calculate the Bollinger Bands for the asset using a specified period and standard deviation.
- Monitor the price of the asset and look for buy and sell signals.
- When the price moves below the lower band, it is considered a buy signal.
- When the price moves above the upper band, it is considered a sell signal.
- Exit the position when the price moves back to the middle band (SMA).
Risk Management: Most traders prefer to use a target profit and stop loss to manage risk. A common approach is to set a target profit at a certain percentage above the entry price and a stop loss at a certain percentage below the entry price.
Mean Reversion Strategy: This strategy assumes that price movements that reach the outer bands are temporary extremes and that prices will tend to revert back toward the mean (middle band). Entry occurs at the bands, and exit occurs when price returns to the SMA.
This comprehensive example shows how the Bollinger Bands strategy would perform over 30 trading days with realistic price movements, volume data, and clear buy/sell signals marked.
Buy Signals (5)
Sell Signals (3)
Strategy Performance Analysis
Note: This demonstrates signal identification only. A complete backtest would include position sizing, transaction costs, and risk management rules.
Key Observations:
- Buy signals occur when price touches or breaks below the lower band
- Sell signals occur when price touches or breaks above the upper band
- Higher volume often coincides with band touches, confirming signals
- The bands expand during volatile periods and contract during consolidation
Strategy Rules Applied:
- Entry: Price touches outer band (buy at lower, sell at upper)
- Exit: Price returns to middle band (SMA)
- Mean reversion: Assumes price will return toward average
- Volume confirmation: Higher volume strengthens signals
Let's see how we can backtest the Bollinger Bands strategy using Exchange Outpost. We're going to write the backtesting code in Rust, which will grant us the best performance and flexibility. We're going to use the ta library to calculate the Bollinger Bands.
1. Define Basic Types
Loading...2. Implement the Run Function
Loading...3. Load Data and Parameters with Validation
Loading...4. Initialize Backtest Data
The data for the running backtest will be stored in these 2 variables:
Loading...- 1.
trades: a vector that will store all the closed trades. - 2.
open_trade: an optional variable that will store the currently open trade, if any.
5. Initialize Bollinger Bands
Loading...6. Execute the Backtest
Process remaining candles for the backtest with stop-loss and take-profit logic:
Loading...7. Cleanup Remaining Positions
We still need to cleanup any remaining open position at the end of the backtest:
Loading...8. Calculate Final Results
Finally we can calculate the total profit and return the result with symbol and exchange information:
Loading...Enhanced Strategy with Risk Management: This implementation includes stop-loss (SL) and take-profit (TP) functionality for better risk management. The strategy opens short positions when price exceeds the upper band and long positions when price drops below the lower band, with automatic position closure based on the configured risk parameters. Most traders prefer to use a target profit and stop loss to manage risk.
Exchange Outpost Advantage: With Exchange Outpost, you can run this backtesting code across multiple symbols simultaneously with serverless scaling and instant access to historical market data.
Now it's time to use the function we created to run a backtest. Let's start by backtesting the strategy on BTCUSDT perpetual futures on a timeframe of 1m from 1st of August 2025 to 1st of September 2025.
Getting Started: Push your code to GitHub using theRust function templatewhich provides automated CI to build your code.
Backtest Results Across Different Assets
BTCUSDT Perpetual Futures
+87.04 USDTLoading...Trades have been omitted for brevity - This means the strategy made a profit of 87.04 USDT in one month when trading BTC perpetual futures with 1000 USD, not bad for such a simple strategy!
ETHUSDT Perpetual Futures
-54.79 USDTLoading...Poor performance on Ethereum perpetual futures
BNBUSDT Perpetual Futures
+66.30 USDTLoading...Good performance on BNB perpetual futures
From these initial backtest results, we can see that our simple Bollinger Band strategy performs differently across various cryptocurrency perpetual futures:
BTCUSDT
Excellent performance
ETHUSDT
Poor performance
BNBUSDT
Good performance
Key Insights
- • Strategy performance varies significantly between different cryptocurrencies
- • The strategy works well on the major cryptocurrencies like BTC and BNB
- • ETH struggles with this strategy in this particular timeframe
- • This demonstrates the importance of testing strategies across multiple assets
To get a more comprehensive view of our strategy's performance, we will use a Python script to run this backtest on all available symbols in the exchange. This will give us statistical insights into which assets our strategy performs best on and help us identify potential market conditions where the strategy excels or struggles.
Benefits of Multi-Asset Testing
- • Identify which asset classes work best with your strategy
- • Understand correlation between market conditions and strategy performance
- • Build robust portfolios by diversifying across multiple profitable assets
- • Discover unexpected opportunities in lesser-known trading pairs
Ready to Build Your Own Strategy?
Start backtesting your trading strategies with Exchange Outpost's serverless financial functions.