Counter-Trend Moving Average and Candlestick Pattern Recognition Quantitative Trading Strategy

EMA ATR RSI SL TP 烛台形态 Candlestick Patterns COUNTER-TREND
Created on: 2025-06-19 14:02:42 Modified on: 2025-06-19 14:02:42
Copy: 0 Number of hits: 303
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Counter-Trend Moving Average and Candlestick Pattern Recognition Quantitative Trading Strategy  Counter-Trend Moving Average and Candlestick Pattern Recognition Quantitative Trading Strategy

Overview

The “Counter-Trend Moving Average and Candlestick Pattern Recognition Quantitative Trading Strategy” is an innovative trading system that cleverly combines multiple Exponential Moving Averages (EMAs) with advanced candlestick pattern recognition techniques to capture reversal opportunities after market overextension by employing counter-trend trading principles. The core of this strategy lies in assessing trends formed by multi-period moving averages, while simultaneously identifying various classic candlestick patterns as confirmation conditions for trading signals, thereby executing counter-trend operations at high-probability market reversal points. The strategy also integrates comprehensive risk management mechanisms, including fixed stop-loss, target profit, and dynamic trailing stops, as well as daily trading limits and signal cooling periods, all designed to ensure long-term stable profitability.

Strategy Principles

The core principle of this strategy is built on the trading philosophy that “overextended markets will eventually revert,” with specific implementation logic as follows:

  1. Trend Identification System: By analyzing the positional relationships between 5 different period Exponential Moving Averages (EMAs of 20, 30, 40, 50, and 200), the strategy determines the current market trend. When shorter-period EMAs are sequentially positioned above longer-period EMAs, it defines a bullish trend; conversely, when shorter-period EMAs are sequentially positioned below longer-period EMAs, it defines a bearish trend.

  2. Candlestick Pattern Recognition: The strategy integrates recognition algorithms for multiple classic candlestick patterns, including:

    • Engulfing: When the current candle completely engulfs the body of the previous candle
    • Doji: When opening and closing prices are extremely close
    • Hammer and Shooting Star: Patterns with small bodies and long lower or upper shadows
    • Morning Star and Evening Star: Three-candle reversal patterns
    • Inside Bar and Outside Bar: When the current candle’s high and low are completely within or surrounding the previous candle
    • Pin Bar: Reversal patterns with long shadows
  3. Counter-Trend Logic: Unlike traditional trend-following approaches, this strategy seeks long opportunities when bearish patterns appear in bearish trends, and short opportunities when bullish patterns appear in bullish trends. This counter-intuitive operation aims to capture rebound or pullback points after market overextension.

  4. Entry Control Mechanism: The strategy implements a maximum trade limit (3 trades) per signal, introduces a cooling period (10 bars) between trades, and controls the maximum number of trades (5) per direction per day, effectively preventing overtrading.

  5. Risk Management System: Employs multi-dimensional risk control measures, including fixed point stop-loss (2800 points), target profit (2000 points), and a trailing stop mechanism that activates after 65 points of profit, ensuring effective risk control while maintaining profitability.

Strategy Advantages

Through in-depth analysis, this strategy demonstrates the following significant advantages:

  1. High Adaptability: The combination of multiple moving averages and various candlestick patterns provides comprehensive judgment, enabling the strategy to adapt to different market environments and changing conditions, enhancing its robustness.

  2. Counter-Intuitive Edge: While most traders tend to follow trends, this strategy operates counter to them by identifying points of market overextension, capturing opportunities that conventional strategies might miss, giving it a unique market edge.

  3. Multi-dimensional Confirmation Mechanism: Trading signals are triggered only when both trend conditions and pattern conditions are simultaneously satisfied, greatly improving signal reliability and reducing interference from false signals.

  4. Flexible Risk Management: The strategy integrates a combination of fixed stop-loss, target profit, and trailing stop mechanisms, controlling losses when markets move adversely while securing profits and tracking continued movement when markets move favorably.

  5. Anti-Overtrading Protection: By setting daily trading limits, signal cooling periods, and maximum trades per signal, the strategy effectively prevents overtrading in volatile markets, ensuring long-term stability.

  6. Visual Intuitiveness: The strategy plots all used moving averages on the chart, allowing traders to visually observe market conditions and potential signals, aiding decision-making.

Strategy Risks

Despite its multiple advantages, the strategy still faces the following potential risks and challenges:

  1. Strong Trend Risks: In strongly trending markets, counter-trend strategies may face consecutive losses. Although stop-loss mechanisms are in place, significant drawdowns may still occur in extreme market conditions. A solution is to add trend strength filters that temporarily disable counter-trend signals during extremely strong trends.

  2. Parameter Sensitivity: Strategy performance heavily depends on parameter settings such as moving average periods, stop-loss/take-profit points, and trading limits. Different markets and timeframes may require different parameter combinations. Historical backtesting and optimization are recommended to find the most suitable parameter configuration for specific markets.

  3. Pattern Recognition Errors: Candlestick pattern recognition based on fixed mathematical models may not fully capture all effective pattern variations in the market, resulting in possible false positives or missed opportunities. Consider introducing machine learning algorithms to improve pattern recognition accuracy.

  4. Slippage and Trading Cost Impact: In actual trading, slippage and trading costs can significantly affect strategy profitability, especially for frequent trading strategies. It is advisable to include actual trading costs in backtests and consider reducing unnecessary trading frequency.

  5. Market Environment Dependency: This strategy performs best in ranging or slightly trending markets but may underperform in suddenly strong trending or extremely low volatility markets. A market environment recognition mechanism could be introduced to automatically reduce trading frequency or pause trading under unfavorable market conditions.

Strategy Optimization Directions

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

  1. Adaptive Parameter System: Introduce adaptive mechanisms to dynamically adjust moving average periods and stop-loss/take-profit levels, allowing the strategy to automatically optimize parameters based on changing market volatility. This can be implemented by incorporating the ATR (Average True Range) indicator, increasing stop-loss distances in high-volatility environments and decreasing them in low-volatility environments.

  2. Timeframe Coordination: Introduce multi-timeframe analysis, requiring larger timeframe trend direction to align with the trading direction, or confirming patterns on larger timeframes to increase signal reliability. For example, confirm trend direction on daily charts while looking for entry points on hourly charts.

  3. Pattern Strength Scoring: Introduce a strength scoring system for each candlestick pattern, assigning different weights based on pattern perfection, position, and prior price action, triggering trades only when pattern strength reaches a threshold. This helps filter weak signals and improves trade success rates.

  4. Market Sentiment Integration: Incorporate market sentiment indicators such as Relative Strength Index (RSI), Stochastic, or Bollinger Bands, combining overbought/oversold conditions to further confirm reversal points and improve entry timing precision.

  5. Dynamic Position Sizing: Replace fixed percentage position strategy with a dynamic position sizing system based on market volatility and signal strength, increasing position size when high-confidence signals appear and decreasing it for low-confidence signals, optimizing capital efficiency and risk-reward ratios.

  6. Machine Learning Enhancement: Consider introducing machine learning algorithms to optimize pattern recognition and signal generation processes, training models on historical data to identify the most profitable trading opportunities, further enhancing the strategy’s predictive capabilities and adaptability.

Summary

The “Counter-Trend Moving Average and Candlestick Pattern Recognition Quantitative Trading Strategy” is a comprehensive trading system based on technical analysis and counter-trend trading principles. Through carefully designed multiple moving average trend identification and candlestick pattern confirmation mechanisms, it executes counter-trend operations at key market reversal points, effectively capturing opportunities that traditional trend-following strategies might miss. The strategy incorporates comprehensive risk management and trade control systems, including stop-loss/take-profit, trailing stops, and trading frequency limitations, aiming to achieve long-term stable risk-adjusted returns.

Although this strategy performs excellently under specific market conditions, it still faces challenges such as risks in strong trending environments and parameter sensitivity. By introducing adaptive parameter systems, multi-timeframe analysis, pattern strength scoring, market sentiment indicator integration, and dynamic position sizing, strategy performance can be further improved. Ultimately, this strategy provides a valuable reference framework for quantitative traders seeking non-traditional trading methods, particularly suitable for those looking for high-probability reversal opportunities in overextended markets.

Strategy source code
/*backtest
start: 2024-07-05 18:40:00
end: 2025-06-17 08:00:00
period: 1d
basePeriod: 1d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("Simple MA AI Strategy + All Pattern Recognition (Reversed)", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=1, max_bars_back=500)

// === INPUTS ===
atrLen = input.int(14, "ATR Length")
slPips = input.int(2800, "Stop Loss (pips)")
tpPips = input.int(2000, "Take Profit (pips)")
trailingStart = input.int(65, "Trailing Start (pips)")
trailingOffset = input.int(65, "Trailing Offset (pips)")
maxTradesPerSignal = 3

// === MAs ===
ema20 = ta.ema(close, 20)
ema30 = ta.ema(close, 30)
ema40 = ta.ema(close, 40)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)

// === AI-style Trend Logic ===
bullTrend = ema20 > ema30 and ema30 > ema40 and ema40 > ema50 and ema50 > ema200
bearTrend = ema20 < ema30 and ema30 < ema40 and ema40 < ema50 and ema50 < ema200

// === Major & Minor Chart Patterns ===
bullEngulf = close > open and open[1] > close[1] and close > open[1] and open < close[1]
bearEngulf = close < open and open[1] < close[1] and close < open[1] and open > close[1]

doji = math.abs(open - close) <= (high - low) * 0.1
hammer = close > open and (high - low) > 3 * (open - close) and (close - low) / (0.001 + high - low) > 0.6
shootingStar = open > close and (high - low) > 3 * (open - close) and (high - open) / (0.001 + high - low) > 0.6
morningStar = close[2] < open[2] and doji[1] and close > open and close > (open[2] + close[2]) / 2
eveningStar = close[2] > open[2] and doji[1] and close < open and close < (open[2] + close[2]) / 2

insideBar = high < high[1] and low > low[1]
outsideBar = high > high[1] and low < low[1]
pinBarBull = (high - close) > 2 * (close - open) and close > open and (close - low) / (high - low) > 0.6
pinBarBear = (close - low) > 2 * (open - close) and close < open and (high - close) / (high - low) > 0.6

patternBull = bullEngulf or hammer or morningStar or insideBar or pinBarBull
patternBear = bearEngulf or shootingStar or eveningStar or outsideBar or pinBarBear

// === TP/SL/Trailing Calculation ===
pip = syminfo.mintick * 10
slPoints = slPips * pip
tpPoints = tpPips * pip
trailOffset = trailingOffset * pip
trailStart = trailingStart * pip

// === Entry Tracking ===
var int today = na
curDay = dayofmonth(time)
var int dailyLongTrades = 0
var int dailyShortTrades = 0
dailyTradeLimit = input.int(5, "Max Trades Per Day Per Direction")
var int lastLongBar = na
var int lastShortBar = na
cooldownBars = input.int(10, "Cooldown Bars Between Trades")
var int longCount = 0
var int shortCount = 0

newLong = bearTrend and patternBear and longCount < maxTradesPerSignal and (na(lastLongBar) or bar_index - lastLongBar > cooldownBars) and (dailyLongTrades < dailyTradeLimit)
newShort = bullTrend and patternBull and shortCount < maxTradesPerSignal and (na(lastShortBar) or bar_index - lastShortBar > cooldownBars) and (dailyShortTrades < dailyTradeLimit)

if newLong
    strategy.entry("AI Long (Reversed)", strategy.long)
    strategy.exit("TP/SL", from_entry="AI Long (Reversed)", limit=close + tpPoints, stop=close - slPoints, trail_points=trailOffset, trail_offset=trailStart)
    longCount := longCount + 1
    lastLongBar := bar_index
    dailyLongTrades := dailyLongTrades + 1

if newShort
    strategy.entry("AI Short (Reversed)", strategy.short)
    strategy.exit("TP/SL", from_entry="AI Short (Reversed)", limit=close - tpPoints, stop=close + slPoints, trail_points=trailOffset, trail_offset=trailStart)
    shortCount := shortCount + 1
    lastShortBar := bar_index
    dailyShortTrades := dailyShortTrades + 1

// Reset counts when signal disappears
if na(today) or curDay != today
    today := curDay
    dailyLongTrades := 0
    dailyShortTrades := 0
if not (bearTrend and patternBear)
    longCount := 0
if not (bullTrend and patternBull)
    shortCount := 0

// === Plotting ===
plot(ema20, color=color.green, title="EMA 20")
plot(ema30, color=color.orange, title="EMA 30")
plot(ema40, color=color.blue, title="EMA 40")
plot(ema50, color=color.purple, title="EMA 50")
plot(ema200, color=color.red, title="EMA 200")

// === Alerts ===
alertcondition(bullTrend and patternBull, title="Sell Signal (Reversed)", message="Simple AI MA Strategy Reversed Sell Signal with Pattern")
alertcondition(bearTrend and patternBear, title="Buy Signal (Reversed)", message="Simple AI MA Strategy Reversed Buy Signal with Pattern")