P
PipsGrowth
Back to Patterns

Pattern Detection Tools

Python packages, MT5 methods, and code examples for automated candlestick pattern recognition.

5
Python Libraries
4
MQL5 Examples
60+
Detectable Patterns
Auto
Detection

Python Libraries

TA-Lib

The most comprehensive technical analysis library with 60+ candlestick pattern recognition functions.

pip install TA-Lib61 patterns

✅ Pros

  • Industry standard
  • Fast C library
  • Comprehensive pattern coverage
  • Well documented

⚠️ Cons

  • Complex installation on Windows
  • Requires C compiler

Code Example

Python
import talib
import numpy as np
# Get OHLC data
open_prices = np.array([...])
high_prices = np.array([...])
low_prices = np.array([...])
close_prices = np.array([...])
# Detect Hammer pattern
hammer = talib.CDLHAMMER(open_prices, high_prices, low_prices, close_prices)
# Detect Engulfing pattern
engulfing = talib.CDLENGULFING(open_prices, high_prices, low_prices, close_prices)
# Detect Morning Star
morning_star = talib.CDLMORNINGSTAR(open_prices, high_prices, low_prices, close_prices)
# Value: 100 = bullish signal, -100 = bearish signal, 0 = no pattern

pandas-ta

Modern pandas-native technical analysis library with easy-to-use candlestick pattern recognition.

pip install pandas-ta30+ patterns

✅ Pros

  • Pure Python
  • Easy installation
  • Pandas integration
  • Active development

⚠️ Cons

  • Fewer patterns than TA-Lib
  • Slower than C-based libraries

Code Example

Python
import pandas as pd
import pandas_ta as ta
# Load your OHLC data into a DataFrame
df = pd.DataFrame({
'open': [...],
'high': [...],
'low': [...],
'close': [...]
})
# Detect Doji pattern
df['doji'] = ta.cdl_doji(df['open'], df['high'], df['low'], df['close'])
# Detect all patterns at once (returns DataFrame with all patterns)
df.ta.cdl_pattern(name="all")
# Specific pattern
df.ta.cdl_pattern(name="engulfing")

mplfinance

Matplotlib-based financial visualization library for creating candlestick charts with pattern annotations.

pip install mplfinanceVisualization only

✅ Pros

  • Beautiful charts
  • Easy to use
  • Great for analysis
  • Publication quality

⚠️ Cons

  • Visualization only, no detection
  • Requires matplotlib

Code Example

Python
import mplfinance as mpf
import pandas as pd
# Load OHLC data with DatetimeIndex
df = pd.read_csv('data.csv', index_col=0, parse_dates=True)
# Basic candlestick chart
mpf.plot(df, type='candle', style='charles', title='EURUSD')
# With volume and moving averages
mpf.plot(df, type='candle', volume=True,
mav=(10, 20, 50), style='yahoo')
# Mark patterns with annotations
mpf.plot(df, type='candle',
alines=dict(alines=[('2024-01-15', 1.0850)],
colors=['r'], linewidths=2))

vectorbt

High-performance backtesting library that can incorporate candlestick patterns into trading strategies.

pip install vectorbtVia TA-Lib integration

✅ Pros

  • Fast vectorized operations
  • Great backtesting
  • Pattern strategy testing
  • Visualization

⚠️ Cons

  • Steep learning curve
  • Requires TA-Lib for patterns

Code Example

Python
import vectorbt as vbt
import talib
# Get price data
data = vbt.YFData.download('EURUSD=X', period='1y')
ohlc = data.get()
# Detect patterns using TA-Lib
hammer = talib.CDLHAMMER(ohlc['Open'], ohlc['High'],
ohlc['Low'], ohlc['Close'])
# Create entry signals from patterns
entries = hammer == 100 # Bullish hammer
exits = hammer == -100 # Or use other exit logic
# Backtest the pattern strategy
pf = vbt.Portfolio.from_signals(ohlc['Close'], entries, exits)
print(pf.stats())

candlestick-patterns

Lightweight Python library specifically designed for candlestick pattern recognition.

pip install candlestick-patterns20+ patterns

✅ Pros

  • Lightweight
  • Easy to use
  • Pure Python
  • No dependencies

⚠️ Cons

  • Limited patterns
  • Less maintained

Code Example

Python
from candlestick import candlestick
# Detect patterns on DataFrame
# Returns DataFrame with boolean columns for each pattern
patterns = candlestick.hammer(df, target='signal')
patterns = candlestick.inverted_hammer(df, target='signal')
patterns = candlestick.doji(df, target='signal')
patterns = candlestick.engulfing(df, target='signal')

MT5 / MQL5 Methods

Built-in Pattern Functions

MQL5 provides functions and techniques to detect candlestick patterns programmatically.

MQL5
// MQL5 - Hammer Pattern Detection
bool IsHammer(int bar) {
double open = iOpen(_Symbol, _Period, bar);
double close = iClose(_Symbol, _Period, bar);
double high = iHigh(_Symbol, _Period, bar);
double low = iLow(_Symbol, _Period, bar);
double body = MathAbs(close - open);
double upperShadow = high - MathMax(open, close);
double lowerShadow = MathMin(open, close) - low;
double totalRange = high - low;
// Hammer criteria:
// 1. Small body (< 30% of total range)
// 2. Long lower shadow (> 2x body)
// 3. Little or no upper shadow (< 10% of range)
if(totalRange == 0) return false;
bool smallBody = (body / totalRange) < 0.30;
bool longLowerShadow = lowerShadow >= (body * 2);
bool noUpperShadow = upperShadow < (totalRange * 0.10);
return smallBody && longLowerShadow && noUpperShadow;
}

Engulfing Pattern Detection

Detect bullish and bearish engulfing patterns in MQL5.

MQL5
// MQL5 - Engulfing Pattern Detection
int DetectEngulfing(int bar) {
double open1 = iOpen(_Symbol, _Period, bar);
double close1 = iClose(_Symbol, _Period, bar);
double open2 = iOpen(_Symbol, _Period, bar + 1);
double close2 = iClose(_Symbol, _Period, bar + 1);
bool prevBearish = close2 < open2;
bool prevBullish = close2 > open2;
bool currBullish = close1 > open1;
bool currBearish = close1 < open1;
// Bullish Engulfing: Previous bearish, current bullish
// Current candle body completely covers previous
if(prevBearish && currBullish) {
if(open1 <= close2 && close1 >= open2) {
return 1; // Bullish Engulfing
}
}
// Bearish Engulfing
if(prevBullish && currBearish) {
if(open1 >= close2 && close1 <= open2) {
return -1; // Bearish Engulfing
}
}
return 0; // No pattern
}

Morning/Evening Star Detection

Detect three-candle reversal patterns.

MQL5
// MQL5 - Morning Star Detection
bool IsMorningStar(int bar) {
// First candle (oldest) - Long bearish
double o1 = iOpen(_Symbol, _Period, bar + 2);
double c1 = iClose(_Symbol, _Period, bar + 2);
// Second candle (star) - Small body
double o2 = iOpen(_Symbol, _Period, bar + 1);
double c2 = iClose(_Symbol, _Period, bar + 1);
double h2 = iHigh(_Symbol, _Period, bar + 1);
double l2 = iLow(_Symbol, _Period, bar + 1);
// Third candle - Long bullish
double o3 = iOpen(_Symbol, _Period, bar);
double c3 = iClose(_Symbol, _Period, bar);
double body1 = MathAbs(c1 - o1);
double body2 = MathAbs(c2 - o2);
double body3 = MathAbs(c3 - o3);
bool firstBearish = c1 < o1 && body1 > body2 * 2;
bool smallStar = body2 < body1 * 0.5;
bool thirdBullish = c3 > o3 && body3 > body2 * 2;
bool closesIntoFirst = c3 > (o1 + c1) / 2;
return firstBearish && smallStar && thirdBullish && closesIntoFirst;
}

Pattern Scanner EA

Complete Expert Advisor framework for scanning multiple patterns.

MQL5
// MQL5 - Pattern Scanner Framework
enum SIGNAL { NONE, BULLISH, BEARISH };
SIGNAL ScanPatterns(int bar) {
// Check reversal patterns
if(IsHammer(bar)) return BULLISH;
if(IsShootingStar(bar)) return BEARISH;
int engulf = DetectEngulfing(bar);
if(engulf == 1) return BULLISH;
if(engulf == -1) return BEARISH;
if(IsMorningStar(bar)) return BULLISH;
if(IsEveningStar(bar)) return BEARISH;
// Add more patterns...
return NONE;
}
void OnTick() {
// Scan for patterns on the last completed candle
SIGNAL signal = ScanPatterns(1);
if(signal == BULLISH && PositionsTotal() == 0) {
// Open buy position
double sl = iLow(_Symbol, _Period, 1) - 10 * _Point;
double tp = Ask + 2 * (Ask - sl);
trade.Buy(0.1, _Symbol, Ask, sl, tp);
}
}

📋 TA-Lib Pattern Functions Reference

Complete list of candlestick pattern functions available in TA-Lib:

Reversal Patterns
CDLHAMMER
CDLINVERTEDHAMMER
CDLSHOOTINGSTAR
CDLHANGINGMAN
CDLENGULFING
CDLMORNINGSTAR
CDLEVENINGSTAR
CDLPIERCING
CDLDARKCLOUDCOVER
CDLHARAMI
CDLHARAMICROSS
Continuation
CDLRISEFALL3METHODS
CDLTASUKIGAP
CDLSEPARATINGLINES
CDLMATHOLD
CDL3LINESTRIKE
Doji Patterns
CDLDOJI
CDLDOJISTAR
CDLDRAGONFLYDOJI
CDLGRAVESTONEDOJI
CDLLONGLEGGEDDOJI
Multi-Candle
CDL3WHITESOLDIERS
CDL3BLACKCROWS
CDL3INSIDE
CDL3OUTSIDE
CDLABANDONEDBABY
CDLKICKING
Other
CDLSPINNINGTOP
CDLHIGHWAVE
CDLBELTHOLD
CDLCOUNTERATTACK

💡 Pattern Detection Best Practices

For Python/Backtesting

  • 1.Use TA-Lib for production - fastest and most reliable
  • 2.Combine multiple patterns for stronger signals
  • 3.Filter patterns by trend direction
  • 4.Add support/resistance context
  • 5.Backtest before live trading

For MT5 EAs

  • 1.Always check bar 1 (completed candle), not bar 0
  • 2.Use tolerances for pattern detection
  • 3.Add trend filters (moving averages)
  • 4.Consider volume confirmation
  • 5.Test on Strategy Tester first