Strategy vault / Trend following
Dynamic Position Dual Moving Average Crossover Strategy
The Dynamic Position Dual Moving Average Crossover Strategy is a quantitative trading approach that utilizes the crossover signals of two Simple Moving Averages (SMAs) with different periods to execute trades. This…

Overview
The Dynamic Position Dual Moving Average Crossover Strategy is a quantitative trading approach that utilizes the crossover signals of two Simple Moving Averages (SMAs) with different periods to execute trades. This strategy leverages the crossover of short-term and long-term moving averages to determine market trends and dynamically adjusts position direction based on crossover signals and the relationship between price and the long-term average. The strategy operates on a daily timeframe and allows for flexibility in sensitivity and reaction speed through adjustable moving average parameters.
Strategy Principle
- Moving Average Calculation: The strategy employs two SMAs - a 9-day and a 21-day.
- Trade Signal Generation:
- Buy Signal: Short-term MA (9-day SMA) crosses above the long-term MA (21-day SMA)
- Sell Signal: Short-term MA crosses below the long-term MA
- Position Management:
- Opening Positions: Enter long on buy signals; enter short on sell signals
- Closing and Reversing Positions: a) When holding a long position, close and go short if the opening price is below the long-term MA or a sell signal occurs b) When holding a short position, close and go long if the opening price is above the long-term MA or a buy signal occurs
- Risk Control: The strategy does not use fixed stop-losses but controls risk through dynamic position adjustment
Strategy Advantages
- Trend Following: Captures market trends using MA crossovers, potentially yielding significant returns in strong trends
- Dynamic Positioning: Flexibly adjusts positions based on price-MA relationship, enhancing adaptability
- Simplicity: Clear and easy-to-understand logic, facilitating implementation
- Adjustable Parameters: MA periods can be tuned to suit different market environments and instruments
- All-Weather Trading: Operates continuously under various market conditions
- Automated Execution: Can be fully automated, reducing emotional interference
- Risk Management: Avoids slippage losses associated with fixed stop-losses through dynamic position adjustment
Strategy Risks
- Unfavorable in Choppy Markets: May incur losses due to frequent trading in sideways or volatile markets
- Lagging Nature: Moving averages are inherently lagging indicators, potentially missing initial phases of sharp moves
- False Breakout Risk: Short-term price fluctuations may trigger false MA crossovers, leading to erroneous signals
- Lack of Stop-Loss: Absence of fixed stop-losses may result in significant losses in extreme market conditions
- Overtrading: Frequent position adjustments can lead to high transaction costs
- Parameter Sensitivity: Strategy performance is highly dependent on MA period selection
- Single Indicator Limitation: Relying solely on MA crossovers may overlook other crucial market information
Optimization Directions
- Incorporate Additional Indicators: Combine with RSI, MACD, etc., to improve signal reliability
- Optimize Entry Timing: Add volume and volatility filters to reduce false breakouts
- Implement Stop-Loss Mechanisms: Introduce fixed or trailing stop-losses to control per-trade risk
- Adjust Position Sizing: Dynamically size positions based on market volatility for better capital management
- Add Market State Identification: Distinguish between trending and ranging markets, applying different strategies accordingly
- Optimize Parameter Selection: Use historical data backtesting to find optimal MA period combinations
- Introduce Trend Strength Filters: Implement indicators like ADX to trade only in strong trend conditions
- Develop Adaptive Parameters: Automatically adjust MA periods based on market volatility for improved adaptability
Conclusion
The Dynamic Position Dual Moving Average Crossover Strategy is a classic and practical quantitative trading method that captures market trends by leveraging MA crossover signals and dynamically adjusting positions. This strategy is simple to understand, fully automatable, and demonstrates good trend-following capabilities with flexibility. However, it also faces potential risks such as poor performance in choppy markets and lagging signals. By incorporating additional technical indicators, optimizing parameter selection, and implementing stop-loss mechanisms, the strategy's stability and profitability can be further enhanced. Traders employing this strategy should adjust parameters and manage risks according to specific trading instruments and market environments to achieve long-term, stable trading results.
Source Pine Script
/*backtest
start: 2024-06-29 00:00:00
end: 2024-07-29 00:00:00
period: 2h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/
//@version=5
strategy(title="MA Cross Backtest", overlay=true, default_qty_type=strategy.cash, default_qty_value=10)
// Parâmetros das Médias Móveis
shortlen = input.int(9, "Short MA Length", minval=1)
longlen = input.int(21, "Long MA Length", minval=1)
// Cálculo das Médias Móveis
short = ta.sma(close, shortlen)
long = ta.sma(close, longlen)
// Plotagem das Médias Móveis
plot(short, color=color.orange, title="Short MA")
plot(long, color=color.green, title="Long MA")
// Sinal de Compra baseado no cruzamento das médias móveis
buySignal = ta.crossover(short, long)
// Sinal de Venda (Short) baseado no cruzamento das médias móveis
sellSignal = ta.crossunder(short, long)
// Plotagem dos Sinais de Compra e Venda
plotshape(series=buySignal, location=location.belowbar, color=color.blue, style=shape.labelup, text="Buy", title="Buy Signal")
plotshape(series=sellSignal, location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell", title="Sell Signal")
// Condições para alertas
alertcondition(buySignal, title="Buy Signal", message="MA Cross Buy Signal")
alertcondition(sellSignal, title="Sell Signal", message="MA Cross Sell Signal")
// Lógica da Estratégia de Backtest
if (buySignal)
// Se não há posição aberta ou se a posição atual é curta, feche a posição curta antes de abrir uma nova posição longa
if (strategy.position_size < 0)
strategy.close("Short", comment="Closing Short Position before Long Entry")
strategy.entry("Long", strategy.long)
// Alerta de compra
alert("MA Cross Buy Signal", alert.freq_once_per_bar_close)
if (strategy.position_size > 0)
// Se o preço abrir abaixo da média longa
if (open < long)
strategy.close("Long", comment="Price Opened Below Long MA")
strategy.entry("Short", strategy.short, comment="Switched to Short")
// Alerta de venda
alert("Price Opened Below Long MA - Switched to Short", alert.freq_once_per_bar_close)
// Se a média móvel curta cruzar abaixo da média móvel longa
else if (sellSignal)
strategy.close("Long", comment="Short MA Crossed Below Long MA")
strategy.entry("Short", strategy.short, comment="Switched to Short")
// Alerta de venda
alert("Short MA Crossed Below Long MA - Switched to Short", alert.freq_once_per_bar_close)
if (strategy.position_size < 0)
// Se o preço abrir acima da média longa
if (open > long)
strategy.close("Short", comment="Price Opened Above Long MA")
strategy.entry("Long", strategy.long, comment="Switched to Long")
// Alerta de compra
alert("Price Opened Above Long MA - Switched to Long", alert.freq_once_per_bar_close)
Published by ChaoZhang on the FMZ strategy square · last modified 2024-07-30. Collected in the Quant Trading Vault. Unvalidated research: re-test with your own data and costs before trusting it.
Build this with AgenKit
A spec is not a trading system. Paste this into your coding agent and AgenKit runs a specialist team — architecture, test-first build, risk gates, review — with paper trading on by default.
/agenkit build a production-grade trading bot with a backtest engine, risk controls and paper trading by default from strategies/Dynamic-Position-Dual-Moving-Average-Crossover-Strategy.md- npx agenkit install engineering-kit in your project
- Paste the command into your agent and approve each phase
- Get tests, backtest, risk controls and a paper-trading switch
Understand it first
Before you run this, read the lesson behind the idea and how to backtest it honestly. Specs like this one are the survivors of an unknown number of trials; deflate their results accordingly.
Related specs
- ADX MA and EMA Long Only Trend Tracking StrategyPine Script · Trend following · 1d
- ATR and Moving Average Crossover Hybrid StrategyPine Script · Trend following · 1h
- Adaptive FVG Detection and MA Trend Trading Strategy with Dynamic ResistancePine Script · Trend following · 1d
- Adaptive Risk Management Strategy Based on Dynamic ATR and Moving Average CrossoverPine Script · Trend following · 2h
- Adaptive Trading Strategy Based on Stochastic RSI Dual Line CrossoverPine Script · Trend following · 4h
- Adaptive Volatility Based Trend Following Short Strategy with Time Delay and Stop Loss ProtectionPine Script · Trend following · 2m