Dual SMA Crossover Trend-Following Quantitative Strategy with Risk Management

SMA 移动平均线 双均线交叉 趋势跟踪 止盈止损 风险管理 技术分析 TP/SL
Created on: 2025-07-09 09:46:56 Modified on: 2025-07-09 09:46:56
Copy: 0 Number of hits: 250
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Dual SMA Crossover Trend-Following Quantitative Strategy with Risk Management  Dual SMA Crossover Trend-Following Quantitative Strategy with Risk Management

Strategy Overview

This strategy is a quantitative trading approach based on the Simple Moving Average (SMA) crossover, which identifies market trend reversal points through the intersection of fast and slow moving averages, combined with a fixed percentage take-profit and stop-loss mechanism for risk and reward management. The core logic is straightforward: when the fast moving average crosses above the slow moving average, a buy signal is generated, indicating a potential uptrend; when the fast moving average crosses below the slow moving average, a sell signal is generated, indicating a potential downtrend. Additionally, each trade is protected by predefined take-profit and stop-loss levels based on the entry price, safeguarding capital and securing profits.

Strategy Principles

The technical foundation of this strategy relies on the characteristics of moving averages as trend indicators. The implementation details are as follows:

  1. Dual SMA System: The strategy employs two simple moving averages with different periods, by default 10 periods (fast line) and 30 periods (slow line).
  2. Signal Generation Logic:
    • Buy Signal: When the fast SMA crosses above the slow SMA (determined using the ta.crossover function)
    • Sell Signal: When the fast SMA crosses below the slow SMA (determined using the ta.crossunder function)
  3. Trade Execution Mechanism:
    • Upon a buy signal, a long position is entered
    • Upon a sell signal, a short position is entered
  4. Risk Management System:
    • Take-Profit Setting: A fixed percentage (default 0.10%) of the entry price sets the profit target
    • Stop-Loss Setting: A fixed percentage (default 0.10%) of the entry price sets the maximum loss limit
  5. Visualization Components:
    • Dual SMA Display: Different colors (blue and orange) and line widths identify the fast and slow averages
    • Signal Markers: Long and short signals are marked with different shapes and colored arrows
    • Bar Coloring: Price bars are colored based on the current trend direction

From the code implementation, this strategy uses TradingView Pine Script version 6, utilizing the strategy function family for trading logic, plot and plotshape functions for visualization, and sets up alertcondition for trade notifications.

Strategy Advantages

Analyzing the code implementation, the following significant advantages can be identified:

  1. Simplicity and Efficiency: The strategy logic is clear and easy to understand and implement, without complex calculations, resulting in high computational efficiency.
  2. Strong Adaptability: The dual SMA system can adapt to different market environments and timeframes, with adjustable parameters.
  3. Comprehensive Risk Control: Integrated take-profit and stop-loss mechanisms set clear exit conditions for each trade, effectively controlling single-trade risk.
  4. Multi-Market Applicability: The code structure is applicable to various trading instruments, including stocks, cryptocurrencies, forex, and indices.
  5. High Visualization: Provides clear visual feedback, including moving average trends, entry signal markers, and bar color changes, allowing traders to intuitively understand market conditions.
  6. Flexible Capital Management: Uses a percentage of equity model for position sizing, defaulting to 100% of funds, but adjustable as needed.
  7. Full Automation: The strategy can be executed completely automatically, reducing human intervention and emotional factors.
  8. Real-time Alert Functionality: Built-in trade signal alert conditions help traders seize market opportunities promptly.

Strategy Risks

Despite its reasonable design, the strategy still has the following potential risks and limitations:

  1. False Signals in Ranging Markets: In sideways or oscillating markets, the dual SMA system may generate frequent crossover signals, leading to consecutive stop-losses. The solution is to add filtering conditions, such as trend confirmation indicators or volume confirmation.
  2. Lagging Issue: As lagging indicators, moving averages typically respond slowly at trend reversal points, potentially missing ideal entry points or delaying exits. Consider combining leading indicators or shortening the moving average periods to mitigate this problem.
  3. Inflexible Fixed Percentage Risk Settings: The current take-profit and stop-loss settings use fixed percentages, not accounting for differences in market volatility. An improvement direction is to introduce dynamic stop-loss mechanisms based on ATR or volatility.
  4. Lack of Drawdown Control: The strategy does not set maximum drawdown limits or overall risk control mechanisms. Adding maximum loss limits or consecutive loss number limits is recommended.
  5. Parameter Sensitivity: The dual SMA period settings significantly impact strategy performance, and different markets and timeframes may require different parameters. Thorough parameter optimization and backtesting are necessary.
  6. Overtrading Risk: Under certain market conditions, the strategy may trigger excessive trades, increasing transaction costs. Trading frequency can be controlled by adding trade filters or cooling periods.
  7. Transaction Costs Not Considered: The code does not explicitly incorporate the impact of trading fees and slippage, potentially leading to overly optimistic backtest results. These factors should be taken into account in practical applications.

Strategy Optimization Directions

Based on code analysis, the strategy can be optimized in the following directions:

  1. Dynamic Take-Profit/Stop-Loss: Replace fixed percentage take-profit and stop-loss with dynamic mechanisms based on ATR or historical volatility to adapt to volatility changes in different market conditions. This is important because fixed percentages may perform inconsistently in high and low volatility markets.
  2. Trend Strength Filtering: Introduce ADX or similar indicators to measure trend strength, executing trades only when trends are clear, reducing false signals in oscillating markets. This can effectively improve the strategy’s win rate.
  3. Volume Confirmation: Add volume conditions as auxiliary confirmation for crossover signals to improve signal reliability. Volume is often important evidence of trend authenticity.
  4. Parameter Adaptive Mechanism: Develop a mechanism to automatically adjust moving average periods based on market conditions, improving strategy adaptability. For example, longer moving average periods may be needed in high-volatility markets.
  5. Re-entry Logic: Design re-entry logic for when stop-loss is triggered but the trend signal remains valid, to capture continuous trends.
  6. Enhanced Risk Management: Add daily maximum loss limits, consecutive loss number limits, and other risk control mechanisms to protect account funds.
  7. Time Filters: Add time filters for specific markets to avoid trading during low liquidity or high volatility periods.
  8. Multi-Timeframe Analysis: Integrate trend directions from higher timeframes as trading filter conditions, only trading when trends across multiple timeframes are consistent.
  9. Optimized Position Sizing: Dynamically adjust the percentage of funds for each trade based on signal strength, market volatility, or historical win rates, rather than using a fixed 100% of funds.
  10. Add Smoothing Algorithms: Consider using EMA instead of SMA, or smoothing crossover signals to reduce erroneous trading signals.

These optimization directions primarily target improving signal quality, enhancing risk management, and increasing strategy adaptability, and can be selectively implemented based on actual trading needs.

Conclusion

The Dual SMA Crossover Trend-Following Quantitative Strategy with Risk Management is a trading system that combines classical technical analysis theory with modern risk management. The strategy monitors the relationship between fast and slow moving averages to determine market trends, generates trading signals at key crossover points, and sets predetermined profit targets and loss limits for each trade.

The main advantages of the strategy lie in its clear logic, ease of understanding and implementation, good visualization effects, and risk control mechanisms. However, as a system based on moving averages, it also faces typical challenges such as signal lag and frequent false signals in oscillating markets.

By introducing dynamic stop-loss mechanisms, trend strength filtering, multi-timeframe analysis, and other optimization measures, the performance and adaptability of the strategy can be significantly enhanced. For traders, understanding the operating principles and limitations of the strategy, and making appropriate adjustments based on personal risk preferences, are key to successfully applying this strategy.

Finally, it should be emphasized that any trading strategy needs thorough historical backtesting and forward validation before actual application, and should be specifically adjusted according to the characteristics of different market environments and trading instruments.

Strategy source code
/*backtest
start: 2024-07-09 00:00:00
end: 2025-07-04 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=6
strategy("SMA Crossover Strategy with TP/SL", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// --- Inputs ---
fast_length = input.int(10, title="Fast SMA Length", minval=1)
slow_length = input.int(30, title="Slow SMA Length", minval=1)
take_profit_percent = input.float(0.10, title="Take Profit (%)", minval=0.01) / 100
stop_loss_percent = input.float(0.10, title="Stop Loss (%)", minval=0.01) / 100

// --- SMA Calculations ---
fast_sma = ta.sma(close, fast_length)
slow_sma = ta.sma(close, slow_length)

// --- Signals ---
buy_signal  = ta.crossover(fast_sma, slow_sma)
sell_signal = ta.crossunder(fast_sma, slow_sma)

// --- Strategy Entries ---
if buy_signal
    strategy.entry("Long", strategy.long)

if sell_signal
    strategy.entry("Short", strategy.short)

// --- Take Profit and Stop Loss Logic ---
long_entry_price  = strategy.position_avg_price
long_tp_price     = long_entry_price * (1 + take_profit_percent)
long_sl_price     = long_entry_price * (1 - stop_loss_percent)

short_entry_price = strategy.position_avg_price
short_tp_price    = short_entry_price * (1 - take_profit_percent)
short_sl_price    = short_entry_price * (1 + stop_loss_percent)

if strategy.position_size > 0
    strategy.exit("Exit Long", from_entry="Long", limit=long_tp_price, stop=long_sl_price)

if strategy.position_size < 0
    strategy.exit("Exit Short", from_entry="Short", limit=short_tp_price, stop=short_sl_price)

// --- Plotting SMAs ---
plot(fast_sma, title="Fast SMA", color=color.blue, linewidth=2)
plot(slow_sma, title="Slow SMA", color=color.orange, linewidth=2)

// --- Plotting Entry Signals ---
plotshape(buy_signal and strategy.position_size[1] <= 0, title="Buy Signal", location=location.belowbar,
     color=color.green, style=shape.triangleup, size=size.small)

plotshape(sell_signal and strategy.position_size[1] >= 0, title="Sell Signal", location=location.abovebar,
     color=color.red, style=shape.triangledown, size=size.small)

// --- Bar Coloring ---
bar_color = fast_sma > slow_sma ? color.teal : fast_sma < slow_sma ? color.maroon : na
barcolor(bar_color)

// --- Alerts ---
alertcondition(buy_signal, title="SMA Crossover Buy", message="Fast SMA crossed above Slow SMA - Buy!")
alertcondition(sell_signal, title="SMA Crossover Sell", message="Fast SMA crossed below Slow SMA - Sell!")