Triple Moving Average Fan Pin Bar Momentum Quantitative Strategy with Dynamic Risk Management

SMA EMA ATR PIN BAR Trailing Stop Dynamic Leverage
Created on: 2025-05-14 11:07:47 Modified on: 2025-05-14 11:07:47
Copy: 2 Number of hits: 266
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Triple Moving Average Fan Pin Bar Momentum Quantitative Strategy with Dynamic Risk Management  Triple Moving Average Fan Pin Bar Momentum Quantitative Strategy with Dynamic Risk Management

Overview

The Triple Moving Average Fan Pin Bar Momentum Quantitative Strategy with Dynamic Risk Management is a comprehensive trading system that combines technical analysis and risk management. The core of the strategy is based on a triple moving average system (Fast EMA, Medium EMA, and Slow SMA) for trend confirmation, coupled with the classic Pin Bar pattern as entry signals, and integrated with multi-layered risk control mechanisms. The strategy employs anti-repainting techniques to ensure all signals are generated based on confirmed candle data, effectively improving signal reliability. The system supports flexible leverage adjustment from 0.1 to 100 times, while implementing position management based on equity percentage and dual stop-loss protection mechanisms.

Strategy Principles

The trading principles of this strategy are based on the following core components:

  1. Triple Moving Average Trend Confirmation System: The strategy uses three moving averages with different periods to establish trend environment, requiring a clear alignment of Fast EMA (default 6 periods), Medium EMA (default 18 periods), and Slow SMA (default 50 periods). For bullish trends: Fast EMA > Medium EMA > Slow SMA; for bearish trends: Fast EMA < Medium EMA < Slow SMA.

  2. Pin Bar Pattern Recognition: After establishing the trend direction, the strategy looks for Pin Bar patterns aligned with the trend direction as specific entry points. The Pin Bar pattern requires that the shadow of the candle accounts for more than 66% of the total length, ensuring sufficient reversal momentum.

  3. Delayed Signal Confirmation Mechanism: To prevent repainting issues, the strategy uses fully formed candle data (confirmedClose, confirmedOpen, etc.) to generate signals, and delays signal confirmation by 1 candle, ensuring trades are based on confirmed market behavior.

  4. Dynamic Risk Management System:

    • Equity risk control: Calculates risk amount based on user-defined risk percentage (usr_risk) and leverage multiplier
    • Position calculation formula: Risk amount = Total equity × Risk percentage × Leverage
    • Dynamically calculates specific trading units based on stop loss distance: Units = Risk amount ÷ Stop loss distance
  5. Dual Stop Loss Protection:

    • Fixed stop loss: Initial protection based on ATR multiple (atr_mult)
    • Trailing stop loss: Profit protection through slPoints and slOffset parameters
  6. Time Window Control:

    • Signal expiration mechanism: Automatically cancels expired signals through the ent_canc parameter
    • Automatic position closing on Friday closing, avoiding weekend gap risks

Strategy Advantages

  1. Anti-Repainting Design: The strategy is completely based on confirmed candle data, avoiding common indicator repainting issues, improving the consistency between backtest results and live trading performance.

  2. Comprehensive Risk Control System:

    • Supports fine-tuned leverage adjustment from 0.1 to 100 times, adapting to different risk preferences
    • Through equity percentage risk control, automatically increases position size when equity grows and reduces position size when equity decreases
    • Dual stop loss mechanism provides multi-layered capital protection
  3. High-Quality Signal Filtering:

    • Triple trend confirmation mechanism avoids trading in unclear trends
    • Pin Bar pattern requires 66% shadow ratio, filtering out weak signals
    • Signal and trend direction matching requirements reduce the risk of counter-trend trading
  4. Flexible Time Management:

    • Automatically cancels expired signals, avoiding entry at inappropriate times
    • Automatic position closing on Friday to avoid weekend risks
    • Breakout EMA crossover automatic exit function, quickly responding to trend changes
  5. Adaptive Position Management: The system automatically adjusts position size based on market volatility (ATR), reducing positions when volatility is high and increasing positions when volatility is low, achieving dynamic risk balance.

Strategy Risks

  1. Excessive Dependence on Trend Environment: The strategy may generate frequent false signals in ranging markets, leading to consecutive stop losses. Solution: Add trend strength filters, such as the ADX indicator, and only trade when trend strength is sufficient.

  2. Limitations of Pin Bar Pattern: Although Pin Bar is a powerful reversal signal, it may appear frequently in highly volatile markets without actual significance. Solution: Add volume confirmation or increase the shadow ratio requirement for Pin Bars.

  3. Leverage Risk: Although the strategy supports leverage up to 100 times, excessive leverage may lead to dramatic account fluctuations or even margin calls. Solution: Use leverage conservatively, with initial settings not exceeding 5 times, and adjust based on historical backtest results.

  4. Parameter Optimization and Curve Fitting Risk: Multiple adjustable parameters (EMA periods, ATR periods, etc.) expose the strategy to over-optimization risk. Solution: Test parameter stability across multiple timeframes and markets, and use Walk Forward analysis to validate parameters.

  5. Stop Loss Setting Risk: Too small ATR multiples may lead to frequent stop losses, while too large ones may cause excessive losses. Solution: Based on market characteristics and trading cycles, find a balance point for stop loss settings, and test multiple settings in combination with equity risk limits.

Strategy Optimization Directions

  1. Add Market Environment Filtering:

    • Incorporate volatility filtering conditions, such as judging whether the market is suitable for trading based on ATR/price ratio
    • Implement market regime recognition functionality to distinguish between trending and ranging environments
    • This optimization can avoid trading in market environments unsuitable for this strategy, improving win rates
  2. Signal Quality Enhancement:

    • Add volume confirmation requirements to ensure Pin Bar signals have sufficient market participation
    • Add key level support/resistance validation, prioritizing signals near important price levels
    • This optimization can significantly improve signal quality and reliability
  3. Dynamic Parameter Adaptation:

    • Implement adaptive adjustment of EMA periods based on market volatility
    • Develop intelligent stop loss systems that dynamically adjust stop loss distance based on market structure
    • This optimization can help the strategy better adapt to different market phases, improving long-term stability
  4. Multi-Timeframe Coordination:

    • Add higher timeframe trend filtering conditions
    • Implement signal confirmation mechanisms across different timeframes
    • Timeframe coordination can reduce noise and improve signal reliability
  5. Fund Management Optimization:

    • Develop a dynamic position system based on risk-reward ratios, adjusting risk percentages based on expected risk-reward
    • Implement composite risk models, comprehensively considering market volatility, trend strength, and signal quality
    • This can more precisely control risk under different market conditions

Summary

The Triple Moving Average Fan Pin Bar Momentum Quantitative Strategy with Dynamic Risk Management is a professional quantitative trading system that integrates multiple technical analysis and risk management approaches. By combining triple moving average trend confirmation with Pin Bar pattern recognition, the strategy can capture high-quality trading opportunities in strong trending markets. Its core advantages lie in its comprehensive risk control system, anti-repainting design, and flexible signal filtering mechanisms, giving it the characteristics of a professional quantitative strategy.

This strategy is most suitable for application in clearly trending market environments and is particularly effective for financial products with significant volatility. However, users need to be aware of the strategy’s limitations in ranging markets, as well as the potential risks of leverage usage and parameter settings. Through the suggested optimization directions, such as adding market environment filtering, enhancing signal quality, and implementing parameter adaptation, the strategy still has significant room for improvement.

Overall, this is a well-structured, risk-controlled, and logically clear quantitative trading strategy, suitable for traders with certain experience to apply in live trading after thorough testing. Through reasonable parameter settings and careful leverage usage, the strategy has the potential to become a powerful tool in a trader’s arsenal.

Strategy source code
/*backtest
start: 2024-05-14 00:00:00
end: 2025-05-12 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"DOGE_USDT"}]
*/

//@version=5

strategy("Rich Harvester", overlay=true, 
  initial_capital=200, 
  commission_type=strategy.commission.percent, 
  commission_value=0.1,
  slippage=2,
  default_qty_type=strategy.cash)

// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
// 抗重绘核心修改(使用已确认K线数据)
// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
confirmedClose = close[1]
confirmedOpen = open[1]
confirmedHigh = high[1]
confirmedLow = low[1]

// User Input (新增参数)
leverage = input.float(title='杠杆倍数', minval=0.1, maxval=100.0, step=0.1, defval=1.0, group="★ 风险控制")

// User Input (原有参数完全保留)
usr_risk = input.int(title='Equity Risk (%)', minval=1, maxval=100, step=1, defval=3, confirm=false)
atr_mult = input.float(title='Stop Loss (x*ATR, Float)', minval=0.1, maxval=100, step=0.1, defval=0.5, confirm=false)
slPoints = input.int(title='Stop Loss Trail Points (Pips)', minval=1, maxval=1000, step=1, defval=1, confirm=false)
slOffset = input.int(title='Stop Loss Trail Offset (Pips)', minval=1, maxval=1000, step=1, defval=1, confirm=false)
sma_slow = input.int(title='Slow SMA (Period)', minval=1, maxval=500, step=1, defval=50, confirm=false)
ema_medm = input.int(title='Medm EMA (Period)', minval=1, maxval=500, step=1, defval=18, confirm=false)
ema_fast = input.int(title='Fast EMA (Period)', minval=1, maxval=500, step=1, defval=6, confirm=false)
atr_valu = input.int(title='ATR (Period)', minval=1, maxval=500, step=1, defval=14, confirm=false)
ent_canc = input.int(title='Cancel Entry After X Bars (Period)', minval=1, maxval=500, step=1, defval=3, confirm=false)

// Create Indicators (使用确认数据)
slowSMA = ta.sma(confirmedClose, sma_slow)
medmEMA = ta.ema(confirmedClose, ema_medm)
fastEMA = ta.ema(confirmedClose, ema_fast)
atr = ta.atr(atr_valu)[1]  // 使用前值

// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
// 信号系统优化(延迟信号确认)
// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
bullishPinBar = (confirmedClose > confirmedOpen and (confirmedOpen - confirmedLow) > 0.66 * (confirmedHigh - confirmedLow)) or
              (confirmedClose < confirmedOpen and (confirmedClose - confirmedLow) > 0.66 * (confirmedHigh - confirmedLow))

bearishPinBar = (confirmedClose > confirmedOpen and (confirmedHigh - confirmedClose) > 0.66 * (confirmedHigh - confirmedLow)) or
               (confirmedClose < confirmedOpen and (confirmedHigh - confirmedOpen) > 0.66 * (confirmedHigh - confirmedLow))

// 趋势过滤条件(使用确认数据)
fanUpTrend = fastEMA > medmEMA and medmEMA > slowSMA
fanDnTrend = fastEMA < medmEMA and medmEMA < slowSMA

// 延迟信号确认(等待K线闭合)
longCondition = fanUpTrend and bullishPinBar[1]  // 延迟1根K线
shortCondition = fanDnTrend and bearishPinBar[1]

// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
// 交易执行系统(仅修改风险计算部分)
// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
enterlong() =>
    risk = usr_risk * 0.01 * strategy.equity * leverage  // 添加杠杆影响
    stopLoss = confirmedLow - atr * atr_mult
    entryPrice = confirmedHigh
    units = risk / (entryPrice - stopLoss)
    strategy.entry('long', strategy.long, units, stop=entryPrice)
    strategy.exit('exit long', from_entry='long', trail_points=slPoints, trail_offset=slOffset)

entershort() =>
    risk = usr_risk * 0.01 * strategy.equity * leverage  // 添加杠杆影响
    stopLoss = confirmedHigh + atr * atr_mult
    entryPrice = confirmedLow
    units = risk / (stopLoss - entryPrice)
    strategy.entry('short', strategy.short, units, stop=entryPrice)
    strategy.exit('exit short', from_entry='short', trail_points=slPoints, trail_offset=slOffset)



// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
// 交易执行系统
// ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
if longCondition 
    enterlong()

if shortCondition 
    entershort()
strategy.cancel('long', ta.barssince(longCondition) > ent_canc)
strategy.cancel('short', ta.barssince(shortCondition) > ent_canc)

strategy.close_all(when=hour == 16 and dayofweek == dayofweek.friday, comment='exit all, market-closed')
strategy.close_all(when=ta.crossunder(fastEMA, medmEMA), comment='exit long, re-cross')
strategy.close_all(when=ta.crossover(fastEMA, medmEMA), comment='exit short, re-cross')

plot(fastEMA, "快EMA", color.new(#FF6B00, 0), 2)
plot(medmEMA, "中EMA", color.new(#0096FF, 0), 2)
plot(slowSMA, "慢SMA", color.new(#00C800, 0), 2)

plotshape(longCondition, "多信号", shape.labelup, location.belowbar, color=#00FF00, text="▲", textcolor=#FFFFFF)
plotshape(shortCondition, "空信号", shape.labeldown, location.abovebar, color=#FF0000, text="▼", textcolor=#FFFFFF)