Automated Dual SMA Crossover Trading System with Integrated Risk Management Strategy
FMZQuant

FMZQuant @fmzquant

Joined:
Apr 25, 2024

Automated Dual SMA Crossover Trading System with Integrated Risk Management Strategy

Publish Date: May 9
2 1

Image description

Image description

Overview
This strategy is an automated trading system based on Simple Moving Average (SMA) crossover signals, designed for the TradingView platform with direct execution through ActivTrades. The strategy generates buy and sell signals by comparing the relationship between fast and slow moving averages, and automatically sets Take Profit and Stop Loss levels to manage risk. Additionally, the strategy includes optional trailing stop functionality, providing an extra layer of risk management, enabling automated trade execution without the need for third-party bots or webhooks.

Strategy Principles
The core principle of this strategy is based on the crossover relationship between two Simple Moving Averages of different periods:

  1. Fast SMA (default 14 periods) and slow SMA (default 28 periods) are used to identify market trend direction.
  2. When the fast SMA crosses above the slow SMA, a buy signal (bullish crossover) is generated, indicating that prices may begin to rise.
  3. When the fast SMA crosses below the slow SMA, a sell signal (bearish crossover) is generated, indicating that prices may begin to fall.
  4. The strategy automatically sets Take Profit and Stop Loss levels for each entry point, calculated in fixed pips.
  5. Take Profit is set at 60 pips by default, with Stop Loss at 30 pips, reflecting a 2:1 risk-reward ratio.
  6. The trailing stop feature activates after price moves 20 pips in the favorable direction, with a trailing distance of 10 pips to lock in profits.

The strategy is written in Pine Script v6, implemented through the strategy function, and is set to use 10% of account equity for each trade, providing an additional layer of money management.

Strategy Advantages

  1. Simple and Effective Trading Logic: Moving average crossovers are a classic and widely validated technical analysis method that is easy to understand and effective at capturing market trend changes.
  2. Fully Automated Execution: The strategy integrates directly with the TradingView platform, requiring no additional third-party tools to execute trades, reducing the risk of delays and execution errors.
  3. Built-in Risk Management Mechanisms: Preset Take Profit and Stop Loss levels ensure a clear risk-to-reward ratio for each trade, with the default 2:1 risk-reward ratio conforming to healthy trading management principles.
  4. Dynamic Profit Protection: The trailing stop feature allows profits to continue growing while maintaining appropriate risk protection, particularly suitable for capturing strong trend continuations.
  5. Visualized Trading Signals: The strategy clearly marks buy and sell signals and moving averages on the chart, making it intuitive for traders to understand and evaluate strategy performance.
  6. High Customizability: All key parameters such as moving average periods, Take Profit and Stop Loss pips, etc., can be adjusted via input parameters, allowing traders to optimize according to different market conditions and risk preferences.
  7. Integrated Money Management: By allocating trade size as a percentage (default 10% of account equity), the strategy automatically implements basic money management, avoiding excessive exposure to a single trade.

Strategy Risks

  1. False Signals in Choppy Markets: In sideways or trendless markets, the SMA crossover strategy may produce multiple false signals, leading to consecutive losses. A solution could be to add additional filters, such as volatility indicators or trend confirmation indicators.
  2. Limitations of Fixed Stop Losses: Using fixed pips to set stop losses may not always be appropriate for all market conditions, potentially resulting in stop losses being set too tight during high volatility periods. Consider dynamically adjusting stop loss levels based on the Average True Range (ATR).
  3. Parameter Sensitivity: Strategy performance is highly dependent on the choice of moving average parameters, which may vary significantly across different markets and timeframes. Thorough backtesting and optimization are required.
  4. Execution Slippage Risk: Real-time trading may face slippage, especially during rapid market fluctuations. Consider simulating slippage effects in backtesting and adjusting expectations accordingly in live trading.
  5. Lack of Market Environment Adaptability: The strategy has no built-in mechanism to identify different market environments (such as trending, oscillating, high volatility, etc.) and may perform poorly in unsuitable market conditions. Market environment recognition logic could be added to adjust or disable trading under specific conditions.
  6. Simplified Money Management: Although the strategy uses a fixed percentage of account equity, it lacks more sophisticated money management such as position size adjustment after consecutive losses. Adaptive money management algorithms could be implemented.

Strategy Optimization Directions

  1. Add Trend Filters: Introduce ADX (Average Directional Index) or similar indicators to assess trend strength, executing trades only in confirmed trend environments to reduce false signals in oscillating markets. This could be implemented by only allowing signals to take effect when ADX values exceed a specific threshold (such as 25).
  2. Dynamic Stop Loss Levels: Replace fixed pip stop losses with dynamic ones based on market volatility, such as using multiples of ATR. This will better adapt the strategy to different volatility environments, tightening stops in low volatility and widening them in high volatility.
  3. Implement Trading Time Filters: Implement trading time window restrictions to avoid high volatility market opening and closing sessions, or adjust trading activity according to the market's main trading sessions.
  4. Add Volume Confirmation: Incorporate volume indicators to verify the validity of moving average crossover signals, executing trades only when supported by sufficient volume, improving signal quality.
  5. Implement Adaptive Parameters: Develop a mechanism to automatically adjust moving average periods and Take Profit/Stop Loss levels based on recent market performance, enabling the strategy to adapt to changing market conditions.
  6. Integrate Multi-Timeframe Analysis: Add higher timeframe trend confirmation, trading only in directions consistent with higher timeframe trends, increasing win rates and risk-reward ratios.
  7. Enhanced Money Management: Implement more sophisticated money management systems that dynamically adjust trade size based on recent trading performance, market volatility, and account status, protecting capital and optimizing long-term returns.
  8. Incorporate Market Sentiment Indicators: Integrate market sentiment indicators such as RSI and Stochastic to identify potential overbought/oversold conditions, avoiding trading in extreme market states or adjusting entry points.

Summary
The Automated Dual SMA Crossover Trading System with Integrated Risk Management Strategy is a well-designed automated trading solution that identifies potential trading opportunities through the classic moving average crossover technique, implementing comprehensive risk management through Take Profit, Stop Loss, and trailing stop functionalities. The main advantages of the strategy lie in its simple and intuitive logic, fully automated execution capability, and integrated risk management framework.

However, the strategy also has some inherent limitations, such as potentially generating false signals in oscillating markets, sensitivity to parameter selection, and lack of adaptability to different market environments. These limitations can be mitigated through a series of optimization measures, including adding trend filters, implementing dynamic risk management, integrating multi-timeframe analysis, and improving money management algorithms.

For traders seeking a basic but effective automated trading strategy, this system provides a good starting point while offering rich optimization potential. Through continuous monitoring, testing, and improvement, traders can develop this strategy into a more robust and personalized trading system aligned with their trading style and risk tolerance.

Strategy source code

/*backtest
start: 2024-04-26 00:00:00
end: 2025-04-26 00:00:00
period: 2h
basePeriod: 2h
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDT"}]
*/

//@version=6
strategy("Auto Trading ActivTrades – SMA Crossover", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// === CONFIGURATION PARAMETERS === //
fastLength = input.int(14, title="SMA Rápida")
slowLength = input.int(28, title="SMA Lenta")
takeProfitPips = input.int(60, title="Take Profit (pips)")
stopLossPips = input.int(30, title="Stop Loss (pips)")
trailStart = input.int(20, title="Trailing Start (pips)")
trailOffset = input.int(10, title="Trailing Offset (pips)")

// === INPUT LOGIC === //
fastSMA = ta.sma(close, fastLength)
slowSMA = ta.sma(close, slowLength)

buySignal = ta.crossover(fastSMA, slowSMA)
sellSignal = ta.crossunder(fastSMA, slowSMA)

// === ENTRIES === //
if buySignal
    strategy.entry("Long", strategy.long)

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

// === TAKE PROFIT, STOP LOSS, TRAILING === //
pip = syminfo.mintick

strategy.exit("TP/SL Long", from_entry="Long", 
     limit=close + takeProfitPips * pip, 
     stop=close - stopLossPips * pip,
     trail_points=trailStart * pip,
     trail_offset=trailOffset * pip)

strategy.exit("TP/SL Short", from_entry="Short", 
     limit=close - takeProfitPips * pip, 
     stop=close + stopLossPips * pip,
     trail_points=trailStart * pip,
     trail_offset=trailOffset * pip)

// === DISPLAY === //
plotshape(buySignal, location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(sellSignal, location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)
plot(fastSMA, title="SMA Rápida", color=color.orange)
plot(slowSMA, title="SMA Lenta", color=color.blue)
Enter fullscreen mode Exit fullscreen mode

Strategy parameters

Image description

The original address: Automated Dual SMA Crossover Trading System with Integrated Risk Management Strategy

Comments 1 total

  • Rebecca Chow
    Rebecca ChowJun 5, 2025

    Clean and systematic approach! The dual SMA crossover with integrated risk management makes this strategy both simple and effective. I appreciate how you've balanced trend-following with disciplined exits.

Add comment