Multi-Module Range Market Trading System: Integrating Bollinger Bands Momentum Detection and Mean Reversion Techniques

BB RSI MACD ADX ATR 均值回归 震荡市场 布林带 多模块交易系统 仓位互斥 动态止损
Created on: 2025-08-04 10:48:54 Modified on: 2025-08-21 17:20:29
Copy: 0 Number of hits: 228
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Multi-Module Range Market Trading System: Integrating Bollinger Bands Momentum Detection and Mean Reversion Techniques  Multi-Module Range Market Trading System: Integrating Bollinger Bands Momentum Detection and Mean Reversion Techniques

Strategy Overview

The Multi-Module Range Market Trading System is a quantitative trading strategy specifically designed for range-bound markets. It ingeniously combines technical indicators including Bollinger Bands, Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), and Average Directional Index (ADX) to form a highly adaptive trading system. The strategy employs a modular design approach with two independent and mutually exclusive trading logics: a momentum-confirmed mean reversion module and a Bollinger Band extreme reversal module, both capable of capturing price reversal opportunities in range-bound market environments with bi-directional trading support. The system’s most distinctive feature is its intelligent position management mechanism, allowing pyramiding within the same logic while ensuring position mutual exclusion between different logics, effectively avoiding signal conflicts and improving capital utilization efficiency.

Strategy Principles

Based on code analysis, the core principle of this strategy lies in the precise identification and capture of range-bound market characteristics. First, the strategy uses the ADX indicator to determine whether the market is in a range-bound state, only considering trading signals when the ADX value is below a set threshold, effectively filtering out false signals in trending markets that could lead to losses.

After confirming the range-bound state, the strategy generates trading signals through two independent logic modules:

  1. Momentum-Confirmed Mean Reversion Module (Logic 1): When price deviates from the Bollinger Bands middle line, it combines MACD golden/death crosses with RSI indicators to confirm momentum direction, forming long or short signals. This module focuses on momentum changes during price fluctuations, entering when momentum indicators suggest a potential reversion to the mean.

  2. Bollinger Band Extreme Reversal Module (Logic 2): When price touches the upper or lower Bollinger Bands and shows signs of rebound, it forms counter-trend trading signals combined with RSI overbought/oversold levels. This module captures reversal opportunities in extreme price areas.

For trade management, the strategy employs dynamic ATR stop-loss for risk control and designs multiple take-profit mechanisms, including Bollinger Bands middle/opposite band exits and RSI moving average reversal exits. The most critical design is the position mutual exclusion and same-logic pyramiding mechanism, which precisely tracks the source logic of each trade, ensuring position mutual exclusion between different logics while allowing intelligent pyramiding within the same logic framework, effectively balancing risk and reward.

Strategy Advantages

  1. Modular Design: The strategy adopts a modular structure, separating different trading logics, making the system more flexible and allowing specific modules to be enabled or disabled according to market conditions, enhancing the strategy’s adaptability.

  2. Precise Market State Identification: Effectively identifies range-bound markets through the ADX indicator, avoiding unnecessary trades in trending markets and reducing false signals.

  3. Multiple Signal Confirmation Mechanism: Each trading signal requires confirmation from multiple indicators, such as price position, momentum indicators, and oscillator indicators, greatly reducing the probability of misjudgment.

  4. Intelligent Position Management: The core advantage lies in its innovative position management system, achieving intelligent pyramiding within the same logic and position mutual exclusion between different logics, both fully utilizing favorable market conditions and avoiding signal conflicts.

  5. Multi-layered Risk Control: Includes dynamic ATR stop-loss, multiple take-profit strategies (Bollinger Bands take-profit, RSI reversal take-profit), and RSI reversal exit mechanism only in profitable situations, forming a comprehensive risk management system.

  6. Close Bar Confirmation Mechanism: Controls through barstate.isconfirmed, avoiding false signals before bar close, improving trading quality.

  7. Visualization Support: The strategy provides visualization elements such as Bollinger Bands channels and ATR dynamic stop-loss lines, allowing traders to intuitively grasp market conditions and strategy operation.

Strategy Risks

  1. Range Identification Misjudgment Risk: Despite using the ADX indicator to identify range-bound markets, market state judgment may still have errors, especially during the transition from range-bound to trending markets, potentially leading to inappropriate trading signals. The solution is to adjust the ADX threshold or add other trend confirmation indicators, such as trend strength index.

  2. Parameter Optimization Dependency: Strategy performance is highly dependent on parameter settings, including Bollinger Bands period, RSI threshold, MACD parameters, etc. Different market environments may require different parameter combinations. It is recommended to find the optimal parameter combination through historical data backtesting and periodically check parameter validity.

  3. Pyramiding Risk Accumulation: Although the strategy allows pyramiding within the same logic, it may lead to overly concentrated positions under extreme market conditions, amplifying losses. This risk can be controlled by setting maximum pyramiding times and single pyramiding capital ratio limits.

  4. Range Breakout Risk: When the market breaks out from range-bound to trending, the strategy may face significant losses. It is recommended to add trend breakout filtering conditions or automatically close all range-bound logic positions after trend confirmation.

  5. Indicator Lag Risk: Technical indicators themselves have certain lag, which may lead to less than ideal entry or exit timing. Try introducing more sensitive indicators or optimizing existing indicator parameters to balance sensitivity and reliability.

Strategy Optimization Directions

  1. Dynamic Parameter Adaptation: The current strategy uses fixed parameters. Consider introducing volatility-adaptive mechanisms to dynamically adjust Bollinger Bands standard deviation, ATR multiplier, and other parameters based on market volatility, allowing the strategy to better adapt to different market environments.

  2. Enhanced Market Environment Classification: Beyond the simple range/trend dichotomy, further classify market states, such as weak range, strong range, initial trend, etc., and configure optimal trading parameters and logic for each market state.

  3. Capital Management Optimization: The current strategy uses fixed percentage capital management. Consider introducing volatility-based position sizing methods, increasing positions in low volatility environments and decreasing positions in high volatility environments to optimize risk-adjusted returns.

  4. Signal Quality Grading: Establish a quality scoring system for trading signals based on multiple factors (such as indicator consistency, price position, etc.), only pyramiding on high-quality signals and reducing capital input for low-quality signals.

  5. Take-Profit Strategy Optimization: The current take-profit strategy is relatively simple. Consider introducing dynamic take-profit, such as ATR-based trailing take-profit or Bollinger Bands width-adaptive take-profit targets, making take-profit more flexible.

  6. Machine Learning Enhancement: Introduce machine learning algorithms, such as random forests or support vector machines, to train models through historical data, improving the accuracy of market state identification and signal generation.

  7. Add Trading Time Filters: Based on the active period characteristics of different markets, add trading time filters to avoid trading during low liquidity or high volatility periods, reducing slippage and execution risks.

Summary

The Multi-Module Range Market Trading System is an ingeniously designed quantitative trading strategy that effectively captures trading opportunities in range-bound markets by integrating multiple classic technical indicators and adopting a modular design approach. Its greatest innovation lies in implementing intelligent pyramiding within the same logic and position mutual exclusion between different logics, balancing profit potential and risk control. The strategy provides comprehensive parameter customization options and multi-layered risk management measures, suitable for range-bound market environments across different time periods.

Despite potential risks such as parameter dependency and market state misjudgment, these risks can be effectively controlled through reasonable parameter optimization, dynamic adaptive mechanisms, and more refined market environment classification. Future optimization directions mainly focus on dynamic parameter adjustment, more refined capital management, and the introduction of advanced technologies such as machine learning, which are expected to further improve the stability and adaptability of the strategy.

Overall, this is a theoretically sound and practical range-bound market strategy, suitable as a component of a medium to long-term quantitative trading system or for standalone application during clearly range-bound market phases. For quantitative traders, this strategy provides an excellent basic framework that can be further customized and optimized according to individual trading styles and market characteristics.

Strategy source code
/*backtest
start: 2025-04-01 00:00:00
end: 2025-07-13 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BNB_USDT"}]
args: [["v_input_bool_1",false],["RunMode",1,358374]]
*/

strategy("Modular Oscillation Strategy", overlay=true, default_qty_value=10)

// =================================================================================
// Universal Indicator Parameters
// =================================================================================
bb_len = input.int(20, title="BB Period", group="Universal Indicators")//BB period
bb_stddev = input.float(2.0, title="BB Std Dev", group="Universal Indicators")//BB std dev multiplier
rsi_len = input.int(14, title="RSI Period", group="Universal Indicators")//RSI period
rsi_ma_len = input.int(14, title="RSI MA Period", group="Universal Indicators")//RSI MA period
macd_fast = input.int(12, title="MACD Fast", group="Universal Indicators")//MACD fast period
macd_slow = input.int(26, title="MACD Slow", group="Universal Indicators")//MACD slow period
macd_signal = input.int(9, title="MACD Signal", group="Universal Indicators")//MACD signal period
atr_len = input.int(14, title="ATR Period", group="Universal Indicators")//ATR period
adx_len = input.int(14, title="ADX Period", group="Universal Indicators")//ADX period

// =================================================================================
// Logic 1: Momentum Confirmed Mean Reversion
// =================================================================================
use_logic1 = input.bool(true, title="Enable Logic 1", group="Logic 1")//Enable Logic 1
adx_threshold_logic1 = input.float(40.0, "ADX Oscillation Threshold", group="Logic 1")//ADX threshold
atr_multiplier_logic1 = input.float(1.8, "ATR Stop Multiplier", group="Logic 1", step=0.1)//ATR stop multiplier
use_bb_exit_logic1 = input.bool(true, "BB Upper/Lower Exit", group="Logic 1")//Use BB exit
use_rsi_exit_logic1 = input.bool(true, "RSI MA Reversal Exit", group="Logic 1")//Use RSI exit

// =================================================================================
// Logic 2: Bollinger Band Extreme Reversal
// =================================================================================
use_logic2 = input.bool(true, title="Enable Logic 2", group="Logic 2")//Enable Logic 2
rsi_ob_logic2 = input.int(70, "RSI Overbought", group="Logic 2")//RSI overbought
rsi_os_logic2 = input.int(30, "RSI Oversold", group="Logic 2")//RSI oversold
adx_threshold_logic2 = input.float(30, "ADX Oscillation Threshold", group="Logic 2")//ADX threshold
atr_multiplier_logic2 = input.float(1.8, "ATR Stop Multiplier", group="Logic 2", step=0.1)//ATR stop multiplier
use_bb_exit_logic2 = input.bool(true, "BB Middle Exit", group="Logic 2")//Use BB middle exit
use_rsi_exit_logic2 = input.bool(true, "RSI MA Reversal Exit", group="Logic 2")//Use RSI exit

// =================================================================================
// Indicator Calculations
// =================================================================================
[bb_middle, bb_upper, bb_lower] = ta.bb(close, bb_len, bb_stddev)//Calculate BB lines
rsi = ta.rsi(close, rsi_len)//Calculate RSI
rsi_ma = ta.sma(rsi, rsi_ma_len)//Calculate RSI MA
[macd_line, signal_line, _] = ta.macd(close, macd_fast, macd_slow, macd_signal)//Calculate MACD
atr = ta.atr(atr_len)//Calculate ATR
[_, _, adx_value] = ta.dmi(adx_len, adx_len)//Calculate ADX

// Market State Judgment
is_ranging_market_logic1 = adx_value < adx_threshold_logic1//Check L1 oscillation
is_ranging_market_logic2 = adx_value < adx_threshold_logic2//Check L2 oscillation

// Price and Indicator Events
price_below_bb_middle = close < bb_middle//Price below BB middle
price_above_bb_middle = close > bb_middle//Price above BB middle
price_crosses_back_above_lower = ta.crossover(close, bb_lower)//Price cross up BB lower
price_crosses_back_below_upper = ta.crossunder(close, bb_upper)//Price cross down BB upper
macd_golden_cross = ta.crossover(macd_line, signal_line)//MACD golden cross
macd_death_cross = ta.crossunder(macd_line, signal_line)//MACD death cross
rsi_above_ma = rsi > rsi_ma//RSI above MA
rsi_below_ma = rsi < rsi_ma//RSI below MA

// Exit Events
exit_long_bb_upper_target = ta.crossover(close, bb_upper)//Price cross up BB upper
exit_short_bb_lower_target = ta.crossunder(close, bb_lower)//Price cross down BB lower
exit_long_bb_middle_target = ta.crossover(close, bb_middle)//Price cross up BB middle
exit_short_bb_middle_target = ta.crossunder(close, bb_middle)//Price cross down BB middle
exit_long_rsi_reversal = ta.crossunder(rsi, rsi_ma)//RSI cross down MA
exit_short_rsi_reversal = ta.crossover(rsi, rsi_ma)//RSI cross up MA

// =================================================================================
// Position State Management
// =================================================================================
var bool is_logic1_active = false//Init L1 state
var bool is_logic2_active = false//Init L2 state

is_logic1_active := false//Reset L1 state
is_logic2_active := false//Reset L2 state

//Check open trades for active logic
if strategy.opentrades > 0
    for i = 0 to strategy.opentrades - 1
        trade_id = strategy.opentrades.entry_id(i)
        if str.contains(trade_id, "Logic1")
            is_logic1_active := true//Mark L1 active
        if str.contains(trade_id, "Logic2")
            is_logic2_active := true//Mark L2 active

// =================================================================================
// Entry Conditions
// =================================================================================
// Logic 1 Entry Conditions
logic1_long_condition = use_logic1 and not use_logic2 and is_ranging_market_logic1 and macd_golden_cross and rsi_above_ma and price_below_bb_middle
//L1 long: Enable L1, disable L2, oscillating, MACD gold cross, RSI>MA, price<BB middle

logic1_short_condition = use_logic1 and not use_logic2 and is_ranging_market_logic1 and macd_death_cross and rsi_below_ma and price_above_bb_middle
//L1 short: Enable L1, disable L2, oscillating, MACD death cross, RSI<MA, price>BB middle

// Logic 2 Entry Conditions
logic2_long_condition = use_logic2 and not use_logic1 and is_ranging_market_logic2 and price_crosses_back_above_lower and rsi <= rsi_os_logic2
//L2 long: Enable L2, disable L1, oscillating, price cross up BB lower, RSI oversold

logic2_short_condition = use_logic2 and not use_logic1 and is_ranging_market_logic2 and price_crosses_back_below_upper and rsi >= rsi_ob_logic2
//L2 short: Enable L2, disable L1, oscillating, price cross down BB upper, RSI overbought

// =================================================================================
// Strategy Execution - Long Trades
// =================================================================================
// Logic 1 Long Execution
if use_logic1
    if logic1_long_condition
        strategy.entry("Logic1Long", strategy.long, comment="Logic1-Long")//Enter L1 long
        strategy.exit("StopLoss1Long", from_entry="Logic1Long", stop=close - atr * atr_multiplier_logic1)
        //Set L1 long stop loss

    // Logic 1 Long BB Profit Taking
    if use_bb_exit_logic1
        if exit_long_bb_upper_target
            strategy.close("Logic1Long", comment="Logic1-Upper Exit")//L1 upper exit

    // Logic 1 Long RSI Reversal Profit Taking
    if use_rsi_exit_logic1
        if strategy.position_size > 0 and exit_long_rsi_reversal and price_above_bb_middle
            float total_profit_L1_long = 0.0
            for i = 0 to strategy.opentrades - 1
                if str.contains(strategy.opentrades.entry_id(i), "Logic1Long")
                    total_profit_L1_long += strategy.opentrades.profit(i)
            //Calculate L1 long profit
            if total_profit_L1_long > 0
                strategy.close("Logic1Long", comment="Logic1-Profit&RSI Reversal")
                //Close L1 long on profit & RSI reversal

// Logic 2 Long Execution
if use_logic2
    if logic2_long_condition
        strategy.entry("Logic2Long", strategy.long, comment="Logic2-Long")//Enter L2 long
        strategy.exit("StopLoss2Long", from_entry="Logic2Long", stop=close - atr * atr_multiplier_logic2)
        //Set L2 long stop loss

    // Logic 2 Long BB Profit Taking
    if use_bb_exit_logic2
        if exit_long_bb_middle_target
            strategy.close("Logic2Long", comment="Logic2-Middle Exit")//L2 middle exit

    // Logic 2 Long RSI Reversal Profit Taking
    if use_rsi_exit_logic2
        if is_logic2_active and strategy.position_size > 0 and exit_long_rsi_reversal and price_above_bb_middle
            float total_profit_L2_long = 0.0
            for i = 0 to strategy.opentrades - 1
                if str.contains(strategy.opentrades.entry_id(i), "Logic2Long")
                    total_profit_L2_long += strategy.opentrades.profit(i)
            //Calculate L2 long profit
            if total_profit_L2_long > 0
                strategy.close("Logic2Long", comment="Logic2-Profit&RSI Reversal")
                //Close L2 long on profit & RSI reversal

// =================================================================================
// Strategy Execution - Short Trades
// =================================================================================
// Logic 1 Short Execution
if use_logic1
    if logic1_short_condition
        strategy.entry("Logic1Short", strategy.short, comment="Logic1-Short")//Enter L1 short
        strategy.exit("StopLoss1Short", from_entry="Logic1Short", stop=close + atr * atr_multiplier_logic1)
        //Set L1 short stop loss

    // Logic 1 Short BB Profit Taking
    if use_bb_exit_logic1
        if exit_short_bb_lower_target
            strategy.close("Logic1Short", comment="Logic1-Lower Exit")//L1 lower exit

    // Logic 1 Short RSI Reversal Profit Taking
    if use_rsi_exit_logic1
        if strategy.position_size < 0 and exit_short_rsi_reversal and price_below_bb_middle
            float total_profit_L1_short = 0.0
            for i = 0 to strategy.opentrades - 1
                if str.contains(strategy.opentrades.entry_id(i), "Logic1Short")
                    total_profit_L1_short += strategy.opentrades.profit(i)
            //Calculate L1 short profit
            if total_profit_L1_short > 0
                strategy.close("Logic1Short", comment="Logic1-Profit&RSI Reversal")
                //Close L1 short on profit & RSI reversal

// Logic 2 Short Execution
if use_logic2
    if logic2_short_condition
        strategy.entry("Logic2Short", strategy.short, comment="Logic2-Short")//Enter L2 short
        strategy.exit("StopLoss2Short", from_entry="Logic2Short", stop=close + atr * atr_multiplier_logic2)
        //Set L2 short stop loss

    // Logic 2 Short BB Profit Taking
    if use_bb_exit_logic2
        if exit_short_bb_middle_target
            strategy.close("Logic2Short", comment="Logic2-Middle Exit")//L2 middle exit

    // Logic 2 Short RSI Reversal Profit Taking
    if use_rsi_exit_logic2
        if is_logic2_active and strategy.position_size < 0 and exit_short_rsi_reversal and price_below_bb_middle
            float total_profit_L2_short = 0.0
            for i = 0 to strategy.opentrades - 1
                if str.contains(strategy.opentrades.entry_id(i), "Logic2Short")
                    total_profit_L2_short += strategy.opentrades.profit(i)
            //Calculate L2 short profit
            if total_profit_L2_short > 0
                strategy.close("Logic2Short", comment="Logic2-Profit&RSI Reversal")
                //Close L2 short on profit & RSI reversal

// =================================================================================
// Visualization
// =================================================================================
// Plotting
plot(bb_upper, title="Upper Track", color=color.new(color.teal, 50))//Plot BB upper
plot(bb_middle, title="Middle Track", color=color.new(color.gray, 70))//Plot BB middle
plot(bb_lower, title="Lower Track", color=color.new(color.teal, 50))//Plot BB lower