
This strategy is a comprehensive trend-following and momentum-synergy trading system primarily based on moving average trend determination and Relative Strength Index (RSI) momentum confirmation to identify high-probability trading opportunities. The core strategy adheres to the “trade with the trend” philosophy, only entering positions after confirming the market’s primary trend direction, waiting for pullbacks, and combining momentum indicators to find optimal entry points. Additionally, the strategy employs an Average True Range (ATR)-based risk management system, ensuring consistency in risk per trade while optimizing capital management efficiency through partial profit-taking and trailing stop mechanisms.
The strategy operates based on four key modules: trend identification, entry condition determination, risk management, and profit optimization.
Trend Identification:
Entry Condition Determination:
Risk Management:
Profit Optimization:
The strategy implementation uses precise mathematical calculations to determine optimal position sizes, ensuring risk control at preset levels while allowing parameter adjustments to adapt to different market conditions.
This strategy offers the following significant advantages:
High-Quality Trade Signals: Through trend and momentum synergistic confirmation, positions are only opened in high-probability directions, significantly improving win rates. Code combinations like long_trend_ok and long_rsi_recovery ensure trade signal quality.
Adaptive Risk Management: The ATR-based stop-loss design allows the strategy to automatically adjust risk parameters according to market volatility. It uses wider stops in highly volatile market environments and tighter stops in calm markets, achieving optimal risk control.
Capital Management Optimization: The partial profit mechanism (50% position takes profit at 2.1R, remaining portion uses trailing stops) achieves a balance between securing profits and maximizing trend capture. Variables like long_tp1_hit and long_trail_stop precisely control this process.
Clear Objective Rules: The strategy is fully quantified, eliminating emotional interference in trading with strong disciplinary execution. All trading decisions are based on clear mathematical calculations and logical conditions, avoiding subjective judgment.
Visual Decision Support: The strategy provides a comprehensive visual feedback system, including trend background coloring, entry signal marking, and stop-loss/profit target visualization, facilitating trader understanding and strategy monitoring.
Parameter Adaptability: Core parameters such as EMA periods, RSI thresholds, and ATR multiples are all adjustable, allowing the strategy to adapt to different market environments and personal risk preferences.
Despite its multiple advantages, the strategy still has the following potential risks:
Trend Identification Lag: Using EMAs as trend determination tools has inherent lag, potentially missing opportunities during early trend stages or maintaining original directional positions after trends end. The solution is to consider adding short-term trend confirmation indicators or adjusting EMA parameters to increase sensitivity.
False Breakout Risk: RSI reversal signals may experience false breakouts, leading to incorrect trades. To address this risk, confirmation conditions like volume changes or other momentum indicators can be added for synergistic confirmation.
Unsuitable for Ranging Markets: The strategy performs best in clear trending markets but may generate frequent false signals and losing trades during sideways consolidation phases. It’s recommended to pause the strategy when markets are in obvious range-bound patterns, potentially identifying such situations through trend strength filters.
Parameter Sensitivity: Strategy performance is relatively sensitive to parameter selection, especially EMA periods and RSI thresholds. It’s recommended to optimize parameters through historical backtesting under different market conditions to avoid overfitting.
Capital Management Risk: Fixed percentage risk management may still lead to cumulative consecutive losses under extreme market conditions. Consider implementing dynamic risk adjustment mechanisms, gradually reducing position sizes after consecutive losses.
Based on strategy code analysis, the following are potential optimization directions:
Multi-Timeframe Synergistic Confirmation: Integrate trend and momentum signals from multiple timeframes to improve trading decision accuracy. For example, check whether daily trend and 4-hour momentum are consistent, only trading when directions align.
Add Trend Strength Filtering: Introduce trend strength indicators like ADX (Average Directional Index), only opening positions when trends are strong enough to avoid false signals in weak trends or ranging markets. Code can add strength determination to uptrend and downtrend conditions.
Dynamic Risk Parameter Adjustment: Dynamically adjust risk percentage per trade based on market volatility, account equity curve, or strategy performance metrics, moderately increasing risk when the strategy performs well and reducing risk when performance is poor.
Integrate Market Environment Analysis: Introduce macro market environment recognition modules, such as volatility indices or market structure analysis, to automatically adjust strategy parameters or selectively enable based on different market phases.
Optimize Profit-Taking Mechanism: The current strategy uses a fixed 2.1R as the first profit target; consider dynamically adjusting profit target positions based on support/resistance or volatility, taking profits near key price levels.
Add Trading Timing Filters: Consider time filters or volume conditions to avoid low liquidity periods or abnormal volume situations, improving signal quality.
Machine Learning Optimization: Utilize machine learning algorithms to dynamically predict optimal parameter combinations or trading weights, adaptively adjusting based on real-time market conditions.
The Trend-Momentum Synergy with Weighted Risk Management Quantitative Trading Strategy is a complete trading system integrating trend identification, momentum confirmation, precise risk control, and intelligent capital management. It determines market direction through EMA moving averages, confirms optimal entry timing with RSI momentum indicators, while employing ATR-based dynamic stop-losses and partial profit-taking mechanisms to achieve an optimal balance between risk and reward.
The strategy’s greatest advantage lies in its systematic approach and discipline, eliminating emotional interference in the trading process through clear quantitative rules, suitable for quantitative traders pursuing a stable trading style. Meanwhile, the strategy’s risk management module ensures limited single-trade losses with unlimited profit potential, aligning with core principles of successful trading.
Despite some inherent limitations such as trend determination lag and poor adaptation to ranging markets, through the optimization directions proposed above—such as multi-timeframe analysis, trend strength filtering, and dynamic risk adjustment—the strategy’s robustness and adaptability can be further enhanced. Future development should focus on enhancing the strategy’s self-adaptive capabilities, enabling it to maintain stable performance across different market environments.
For investors pursuing systematic trading methods, this strategy provides a solid foundation framework that can be further customized and optimized according to personal risk preferences and market understanding.
/*backtest
start: 2024-06-17 00:00:00
end: 2025-06-15 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"DOGE_USDT"}]
*/
//@version=5
strategy("Crypto Swing Trading Strategy (1-5 Day)", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, pyramiding=0, calc_on_every_tick=false, calc_on_order_fills=false)
// ============================================================================
// STRATEGY INPUTS
// ============================================================================
// Trend Filter Settings
ema_fast_length = input.int(50, title="Fast EMA Length", minval=1, group="Trend Filter")
ema_slow_length = input.int(200, title="Slow EMA Length", minval=1, group="Trend Filter")
// RSI Settings
rsi_length = input.int(14, title="RSI Length", minval=1, group="Momentum")
rsi_oversold = input.int(45, title="RSI Oversold Level", minval=1, maxval=50, group="Momentum")
rsi_overbought = input.int(70, title="RSI Overbought Level", minval=50, maxval=99, group="Momentum")
// ATR Settings
atr_length = input.int(14, title="ATR Length", minval=1, group="Risk Management")
atr_stop_mult = input.float(1.5, title="ATR Stop Loss Multiplier", minval=0.1, step=0.1, group="Risk Management")
atr_trail_mult = input.float(1.0, title="ATR Trailing Stop Multiplier", minval=0.1, step=0.1, group="Risk Management")
// Risk Management
risk_per_trade = input.float(1.0, title="Risk Per Trade (%)", minval=0.1, maxval=5.0, step=0.1, group="Risk Management")
reward_ratio = input.float(2.1, title="Initial Take Profit Ratio (R:R)", minval=1.0, step=0.1, group="Risk Management")
// Strategy Settings
pullback_distance = input.float(1.0, title="Max Distance from 50 EMA for Pullback (ATR)", minval=0.1, step=0.1, group="Entry Conditions")
enable_shorts = input.bool(true, title="Enable Short Trades", group="Strategy Settings")
enable_longs = input.bool(true, title="Enable Long Trades", group="Strategy Settings")
// ============================================================================
// INDICATOR CALCULATIONS
// ============================================================================
// Moving Averages
ema_fast = ta.ema(close, ema_fast_length)
ema_slow = ta.ema(close, ema_slow_length)
// RSI
rsi = ta.rsi(close, rsi_length)
// ATR
atr = ta.atr(atr_length)
// ============================================================================
// TREND IDENTIFICATION
// ============================================================================
// Primary trend based on EMA relationship
uptrend = ema_fast > ema_slow
downtrend = ema_fast < ema_slow
// ============================================================================
// ENTRY CONDITIONS
// ============================================================================
// Long Entry Conditions
long_trend_ok = uptrend and enable_longs
long_pullback = math.abs(close - ema_fast) <= (pullback_distance * atr) and close < ema_fast[1]
long_rsi_oversold = rsi[1] < rsi_oversold
long_rsi_recovery = rsi > rsi_oversold and rsi[1] <= rsi_oversold
long_entry_condition = long_trend_ok and long_pullback and long_rsi_oversold and long_rsi_recovery
// Short Entry Conditions
short_trend_ok = downtrend and enable_shorts
short_pullback = math.abs(close - ema_fast) <= (pullback_distance * atr) and close > ema_fast[1]
short_rsi_overbought = rsi[1] > rsi_overbought
short_rsi_decline = rsi < rsi_overbought and rsi[1] >= rsi_overbought
short_entry_condition = short_trend_ok and short_pullback and short_rsi_overbought and short_rsi_decline
// ============================================================================
// POSITION SIZING
// ============================================================================
// Calculate position size based on risk per trade and ATR stop distance
calculate_position_size(entry_price, stop_price, risk_percent) =>
risk_amount = strategy.equity * (risk_percent / 100)
stop_distance = math.abs(entry_price - stop_price)
position_size = stop_distance > 0 ? risk_amount / stop_distance : 0
position_size
// ============================================================================
// STRATEGY VARIABLES
// ============================================================================
var float long_entry_price = na
var float long_stop_price = na
var float long_tp1_price = na
var float long_trail_stop = na
var bool long_tp1_hit = false
var float short_entry_price = na
var float short_stop_price = na
var float short_tp1_price = na
var float short_trail_stop = na
var bool short_tp1_hit = false
// ============================================================================
// LONG TRADE MANAGEMENT
// ============================================================================
// Long Entry
if long_entry_condition and strategy.position_size == 0
long_entry_price := close
long_stop_price := close - (atr_stop_mult * atr)
long_tp1_price := close + (reward_ratio * (close - long_stop_price))
long_trail_stop := long_stop_price
long_tp1_hit := false
// Calculate position size
pos_size = calculate_position_size(long_entry_price, long_stop_price, risk_per_trade)
strategy.entry("Long", strategy.long, qty=pos_size)
strategy.exit("Long Stop", "Long", stop=long_stop_price)
// Long TP1 Management (Take 50% profit at 2:1 R:R)
if strategy.position_size > 0 and not long_tp1_hit and high >= long_tp1_price
long_tp1_hit := true
strategy.close("Long", qty_percent=50, comment="TP1 - 50%")
// Move stop to breakeven
long_trail_stop := long_entry_price
strategy.cancel("Long Stop")
// Long Trailing Stop (for remaining 50% position)
if strategy.position_size > 0 and long_tp1_hit
// Calculate new trailing stop
highest_since_tp1 = ta.highest(high, 1)
new_trail_stop = highest_since_tp1 - (atr_trail_mult * atr)
// Only move stop up, never down
if new_trail_stop > long_trail_stop
long_trail_stop := new_trail_stop
// Exit on trailing stop or trend reversal
if close <= long_trail_stop or not uptrend
strategy.close("Long", comment=not uptrend ? "Trend Reversal" : "Trailing Stop")
// ============================================================================
// SHORT TRADE MANAGEMENT
// ============================================================================
// Short Entry
if short_entry_condition and strategy.position_size == 0
short_entry_price := close
short_stop_price := close + (atr_stop_mult * atr)
short_tp1_price := close - (reward_ratio * (short_stop_price - close))
short_trail_stop := short_stop_price
short_tp1_hit := false
// Calculate position size
pos_size = calculate_position_size(short_entry_price, short_stop_price, risk_per_trade)
strategy.entry("Short", strategy.short, qty=pos_size)
strategy.exit("Short Stop", "Short", stop=short_stop_price)
// Short TP1 Management (Take 50% profit at 2:1 R:R)
if strategy.position_size < 0 and not short_tp1_hit and low <= short_tp1_price
short_tp1_hit := true
strategy.close("Short", qty_percent=50, comment="TP1 - 50%")
// Move stop to breakeven
short_trail_stop := short_entry_price
strategy.cancel("Short Stop")
// Short Trailing Stop (for remaining 50% position)
if strategy.position_size < 0 and short_tp1_hit
// Calculate new trailing stop
lowest_since_tp1 = ta.lowest(low, 1)
new_trail_stop = lowest_since_tp1 + (atr_trail_mult * atr)
// Only move stop down, never up
if new_trail_stop < short_trail_stop
short_trail_stop := new_trail_stop
// Exit on trailing stop or trend reversal
if close >= short_trail_stop or not downtrend
strategy.close("Short", comment=not downtrend ? "Trend Reversal" : "Trailing Stop")
// ============================================================================
// PLOTTING
// ============================================================================
// Plot EMAs
plot(ema_fast, title="EMA 50", color=color.blue, linewidth=2)
plot(ema_slow, title="EMA 200", color=color.red, linewidth=2)
// Color background based on trend
bgcolor(uptrend ? color.new(color.green, 95) : downtrend ? color.new(color.red, 95) : na, title="Trend Background")
// Plot RSI levels (scaled to price for visualization)
hline(rsi_overbought, title="RSI Overbought", color=color.red, linestyle=hline.style_dashed)
hline(rsi_oversold, title="RSI Oversold", color=color.green, linestyle=hline.style_dashed)
// Plot entry signals
plotshape(long_entry_condition, title="Long Entry", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.normal)
plotshape(short_entry_condition, title="Short Entry", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.normal)
// Plot stop losses and targets for current position
plot(strategy.position_size > 0 ? long_trail_stop : na, title="Long Trailing Stop", color=color.red, style=plot.style_stepline, linewidth=2)
plot(strategy.position_size < 0 ? short_trail_stop : na, title="Short Trailing Stop", color=color.red, style=plot.style_stepline, linewidth=2)
plot(strategy.position_size > 0 and not long_tp1_hit ? long_tp1_price : na, title="Long TP1", color=color.green, style=plot.style_cross, linewidth=2)
plot(strategy.position_size < 0 and not short_tp1_hit ? short_tp1_price : na, title="Short TP1", color=color.green, style=plot.style_cross, linewidth=2)
// ============================================================================
// INFORMATION DISPLAY (Using Labels instead of Table)
// ============================================================================
// Display key information using labels on the last bar
if barstate.islast
// Create info label with key metrics
trend_text = uptrend ? "UP" : downtrend ? "DOWN" : "SIDE"
position_text = strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "NONE"
info_text = "Trend: " + trend_text + "\nRSI: " + str.tostring(math.round(rsi, 1)) + "\nATR: " + str.tostring(math.round(atr, 2)) + "\nPosition: " + position_text
label.new(bar_index, high + atr, info_text,
color=uptrend ? color.new(color.green, 80) : downtrend ? color.new(color.red, 80) : color.new(color.gray, 80),
textcolor=color.white, style=label.style_label_down, size=size.normal)
// ============================================================================
// ALERTS
// ============================================================================
// Alert conditions
alertcondition(long_entry_condition, title="Long Entry Signal", message="LONG: Swing trading signal for {{ticker}} at {{close}}")
alertcondition(short_entry_condition, title="Short Entry Signal", message="SHORT: Swing trading signal for {{ticker}} at {{close}}")
alertcondition(strategy.position_size > 0 and long_tp1_hit, title="Long TP1 Hit", message="LONG TP1: First target hit for {{ticker}} at {{close}}")
alertcondition(strategy.position_size < 0 and short_tp1_hit, title="Short TP1 Hit", message="SHORT TP1: First target hit for {{ticker}} at {{close}}")
// ============================================================================
// STRATEGY SUMMARY
// ============================================================================
// This strategy implements the full swing trading approach described in the document:
// 1. Trend filtering using 50/200 EMA (only trade with the trend)
// 2. RSI momentum for entry timing (buy oversold in uptrend, sell overbought in downtrend)
// 3. ATR-based position sizing and stop losses (volatility-adjusted risk management)
// 4. Partial profit taking at 2:1 R:R (50% of position)
// 5. Trailing stops for remaining position using ATR
// 6. Trend reversal exits (close all when trend changes)
//
// Key Features:
// - Configurable parameters for different market conditions
// - Risk management with consistent 1% risk per trade
// - Visual indicators for trend, signals, and trade management
// - Information table showing key metrics
// - Alert system for automated notifications
//
// Recommended for: BTC, ETH, XRP on daily timeframes
// Holding period: 1-5 days typical