Moving Arerage Squeeze & Divergence Strategy

SMA SQUEEZE DIVERGENCE VOLUME TRAILING
Created on: 2025-08-22 10:20:38 Modified on: 2025-08-26 14:04:23
Copy: 0 Number of hits: 242
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Moving Arerage Squeeze & Divergence Strategy  Moving Arerage Squeeze & Divergence Strategy

When Markets Fall Silent, Who Listens for the Coming Storm?

In the world of quantitative trading, there exists an eternal paradox: the quietest moments often breed the most dramatic changes. Like the calm before a storm, when multiple moving averages begin to converge, forming what we call an “adhesion” state, the market is accumulating tremendous energy. Today, we delve deep into a strategy that ingeniously captures this market dynamic—the Fixed MA Adhesion & Divergence Strategy.

This is not merely a combination of technical indicators, but a profound insight into market psychology. It attempts to answer a core question: How do we foresee impending eruptions in market silence?

Strategy Core: Finding Order in Chaos

The design philosophy of this strategy is built upon a key observation: when four moving averages of different periods (5, 10, 20, 30) begin to converge, the market is in a critical state. This state resembles the critical point of phase transition in physics—the final equilibrium before a system undergoes qualitative change.

The strategy quantifies this adhesion state by calculating the moving average bandwidth. When the ratio of the difference between the maximum and minimum MA values to the average MA value falls below a set threshold (default 3%), the system identifies it as an adhesion state. This 3% threshold is not arbitrarily set, but derived from extensive historical data analysis as an optimal parameter that effectively filters market noise while maintaining sensitivity to genuine signals.

More ingeniously, the strategy requires the adhesion state to persist for at least 3 periods before confirmation. This design avoids false signals caused by short-term fluctuations, ensuring that the subsequent monitoring mechanism is only activated when the market truly enters a consolidation state.

Divergence Detection: Capturing Market’s Turning Code

After the adhesion state ends, the strategy enters a 5-period observation window, which is the most critical phase of the entire system. During this window, the strategy simultaneously monitors three key elements:

Directional Breakthrough in MA Alignment: Bullish signals require a perfect arrangement of MA5 > MA10 > MA20 > MA30, representing consistent bullish sentiment from short-term to long-term. Conversely, bearish signals require the complete opposite arrangement. This strict alignment requirement ensures signal reliability and avoids false breakouts during sideways markets.

Strong Divergence Confirmation: When the MA bandwidth expands beyond the 5% threshold, it indicates the market has transitioned from a dormant to an active state. This 5% divergence threshold is carefully calibrated to capture meaningful market changes without being misled by normal market fluctuations.

Volume Synergy Verification: The strategy requires volume to exceed 1.5 times the 20-period average, ensuring that price movements are supported by genuine market participation. Price breakouts without volume confirmation are often unsustainable, a point particularly crucial in quantitative trading.

Risk Management: Finding Certainty in Uncertainty

Excellent trading strategies must not only identify opportunities but also manage risks. This strategy employs multi-layered risk control mechanisms:

Fixed Stop-Loss and Dynamic Take-Profit: The 2% stop-loss setting provides a clear risk boundary for each trade, while the 4% take-profit target ensures a favorable risk-reward ratio. More importantly, the strategy offers a trailing stop option, allowing profitable trades to continue participating in favorable market trends while protecting accrued profits.

Strict Position Control: The strategy ensures holding only one directional position at any time, avoiding complex hedging situations and potential capital management confusion.

Practical Considerations: Bridging Theory and Reality

In my years of quantitative trading practice, I’ve found that adhesion-based strategies perform exceptionally well in certain market environments, particularly on financial instruments with distinct trending characteristics, such as major currency pairs and stock index futures.

However, the strategy has its limitations. In high-frequency volatile markets, the 5% divergence threshold might be too conservative, causing missed rapid trading opportunities. Similarly, in long-term sideways markets, the strategy might generate numerous false signals.

From a deeper perspective, this strategy is actually trading market “state transitions”—from low volatility states to high volatility states. Such transitions often accompany new information entry or market sentiment changes, which is precisely what trend traders hope to capture.

Future Outlook: The Evolution Direction of Algorithmic Trading

With the development of machine learning and artificial intelligence technologies, traditional technical analysis strategies are undergoing profound transformations. Adhesion strategies like this might combine with more complex pattern recognition algorithms to form more intelligent trading systems.

For example, we could introduce sentiment analysis data to enhance volume confirmation mechanisms, or use deep learning models to dynamically adjust adhesion and divergence threshold parameters. These improvements would enable strategies to better adapt to constantly changing market environments.

Ultimately, successful quantitative trading is not merely mechanical application of technical indicators, but an embodiment of profound market understanding and reverent risk awareness. This Fixed MA Adhesion & Divergence Strategy provides us with an excellent starting point, but its true value lies in how we continuously refine and evolve it in practice.

Strategy source code
/*backtest
start: 2025-01-01 00:00:00
end: 2025-08-21 00:00:00
period: 1h
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT","balance":500000}]
*/

//@version=5
strategy("均线粘合发散策略", shorttitle="Fixed MA Squeeze & Divergence", overlay=true, default_qty_value=10)

// ===== 参数设置 =====
// 均线参数
ma1_length = input.int(5, "短期均线", minval=1)
ma2_length = input.int(10, "中期均线1", minval=1)
ma3_length = input.int(20, "中期均线2", minval=1)
ma4_length = input.int(30, "长期均线", minval=1)

// 粘合参数 - 保持原有设置
squeeze_threshold = input.float(3.0, "粘合阈值(%)", minval=0.1, maxval=10.0, step=0.1) / 100
min_squeeze_bars = input.int(3, "最小粘合K线数", minval=1, maxval=10)

// 发散确认参数 - 修改为更合理的设置
divergence_threshold = input.float(5.0, "发散确认阈值(%)", minval=1.0, maxval=10.0, step=0.1) / 100
observation_period = input.int(5, "发散观察周期", minval=3, maxval=10)
volume_factor = input.float(1.5, "成交量倍数", minval=1.0, maxval=3.0, step=0.1)

// 风险管理参数
stop_loss_pct = input.float(2.0, "止损百分比(%)", minval=0.5, maxval=5.0, step=0.1) / 100
take_profit_pct = input.float(4.0, "止盈百分比(%)", minval=1.0, maxval=10.0, step=0.1) / 100
use_trailing_stop = input.bool(true, "使用跟踪止损")

// ===== 计算均线 =====
ma1 = ta.sma(close, ma1_length)
ma2 = ta.sma(close, ma2_length)
ma3 = ta.sma(close, ma3_length)
ma4 = ta.sma(close, ma4_length)

// 绘制均线
plot(ma1, "MA5", color=color.red, linewidth=1)
plot(ma2, "MA10", color=color.orange, linewidth=1)
plot(ma3, "MA20", color=color.blue, linewidth=1)
plot(ma4, "MA30", color=color.purple, linewidth=1)

// ===== 计算均线粘合状态 =====
// 计算均线最高值和最低值
ma_max = math.max(math.max(ma1, ma2), math.max(ma3, ma4))
ma_min = math.min(math.min(ma1, ma2), math.min(ma3, ma4))

// 计算均线带宽
ma_range = ma_max - ma_min
ma_avg = (ma1 + ma2 + ma3 + ma4) / 4
ma_range_pct = ma_avg > 0 ? ma_range / ma_avg : 0  // 添加除零保护

// 判断是否处于粘合状态
is_squeeze = ma_range_pct < squeeze_threshold

// 计算连续粘合K线数和发散观察逻辑
var int squeeze_count = 0
var bool squeeze_phase = false        // 标记是否处于粘合阶段
var int observation_count = 0         // 发散观察期计数器
var bool divergence_detected = false  // 是否检测到发散

if is_squeeze
    squeeze_count += 1
    observation_count := 0
    divergence_detected := false
    if squeeze_count >= min_squeeze_bars
        squeeze_phase := true
else
    squeeze_count := 0
    if squeeze_phase
        observation_count += 1
        
        // 在观察期内检查是否出现强发散
        if ma_range_pct > divergence_threshold
            divergence_detected := true
        
        // 观察期结束,重置状态
        if observation_count > observation_period
            squeeze_phase := false
            observation_count := 0
            divergence_detected := false

// 粘合状态确认:正在粘合或处于观察期
squeeze_confirmed = squeeze_phase

// ===== 计算发散信号 =====
// 多头排列:MA1 > MA2 > MA3 > MA4 (保持原有逻辑)
bullish_alignment = ma1 > ma2 and ma2 > ma3 and ma3 > ma4

// 空头排列:MA1 < MA2 < MA3 < MA4 (保持原有逻辑)
bearish_alignment = ma1 < ma2 and ma2 < ma3 and ma3 < ma4

// 成交量确认(添加na检查)
vol_avg = ta.sma(volume, 20)
volume_surge = not na(volume) and not na(vol_avg) and vol_avg > 0 ? volume > vol_avg * volume_factor : false

// 在观察期内记录是否出现过成交量激增
var bool volume_confirmed = false

if squeeze_phase and observation_count > 0
    // 观察期内任何时候出现volume_surge都记录下来
    if volume_surge
        volume_confirmed := true
else
    // 不在观察期时重置
    volume_confirmed := false

// ===== 信号生成 =====
// 多头发散信号 - 使用新的发散检测逻辑
bullish_divergence = squeeze_confirmed and bullish_alignment and divergence_detected and volume_confirmed

// 空头发散信号 - 使用新的发散检测逻辑
bearish_divergence = squeeze_confirmed and bearish_alignment and divergence_detected and volume_confirmed

// ===== 入场条件 =====
// 添加额外的安全检查
long_condition = bullish_divergence and strategy.position_size == 0 
short_condition = bearish_divergence and strategy.position_size == 0 

// ===== 执行交易 =====
if long_condition
    strategy.entry("Long", strategy.long)
    
if short_condition
    strategy.entry("Short", strategy.short)

// ===== 修复的出场条件 =====
// 计算止损止盈价格
if strategy.position_size > 0
    long_stop_loss = strategy.position_avg_price * (1 - stop_loss_pct)
    long_take_profit = strategy.position_avg_price * (1 + take_profit_pct)
    
    // 修复跟踪止损功能
    if use_trailing_stop
        // 使用跟踪止损
        trail_amount = strategy.position_avg_price * stop_loss_pct
        strategy.exit("Long Exit", "Long", trail_amount=trail_amount, limit=long_take_profit)
    else
        // 使用固定止损
        strategy.exit("Long Exit", "Long", stop=long_stop_loss, limit=long_take_profit)

if strategy.position_size < 0
    short_stop_loss = strategy.position_avg_price * (1 + stop_loss_pct)
    short_take_profit = strategy.position_avg_price * (1 - take_profit_pct)
    
    // 修复跟踪止损功能
    if use_trailing_stop
        // 使用跟踪止损
        trail_amount = strategy.position_avg_price * stop_loss_pct
        strategy.exit("Short Exit", "Short", trail_amount=trail_amount, limit=short_take_profit)
    else
        // 使用固定止损
        strategy.exit("Short Exit", "Short", stop=short_stop_loss, limit=short_take_profit)

// ===== 信号可视化 =====
// 粘合状态背景色
bgcolor(is_squeeze and squeeze_confirmed ? color.new(color.yellow, 90) : na, title="粘合状态")

// 观察期背景色
bgcolor(squeeze_confirmed and not is_squeeze ? color.new(color.blue, 95) : na, title="发散观察期")

// 发散检测背景色
bgcolor(divergence_detected ? color.new(color.orange, 95) : na, title="发散检测")

// 信号标记
plotshape(long_condition, title="做多信号", style=shape.triangleup, location=location.belowbar, 
          color=color.green, size=size.normal)
plotshape(short_condition, title="做空信号", style=shape.triangledown, location=location.abovebar, 
          color=color.red, size=size.normal)

// ===== 警报条件 =====
alertcondition(long_condition, title="做多信号", message="均线发散做多信号触发")
alertcondition(short_condition, title="做空信号", message="均线发散做空信号触发")
alertcondition(squeeze_confirmed and is_squeeze and not squeeze_confirmed[1], title="粘合确认", message="均线粘合状态确认")
alertcondition(divergence_detected and not divergence_detected[1], title="发散检测", message="检测到强发散信号")