Q2A_CandlestickPatterns

A comprehensive Pine Script v6 library for detecting 44 candlestick patterns with trend detection and property calculations.
## 📋 Overview
The **Q2A_CandlestickPatterns** library provides a complete toolkit for identifying traditional Japanese candlestick patterns in TradingView. It includes both reversal and continuation patterns, organized by the number of candles required (1, 2, 3, and 5 candles).
### Key Features
- ✅ **44 Pattern Detection Functions** - Comprehensive coverage of major candlestick patterns
- ✅ **Organized by Candle Count** - Easy navigation (1, 2, 3, and 5 candle patterns)
- ✅ **Bullish/Bearish/Neutral Classification** - Clear signal categorization
- ✅ **Detailed Pattern Descriptions** - Each pattern returns name, type, and explanation
- ✅ **Property Calculation Helper** - Core function for analyzing candle characteristics
- ✅ **Clean Q2A Code Style** - Professional, maintainable, and well-documented
## 🚀 Quick Start
### Installation
```pinescript
import Quant2Alpha/Q2A_CandlestickPatterns/1 as candlePatterns
```
### Basic Usage Example
```pinescript
//version=6
indicator("Candlestick Pattern Detector", overlay=true)
import Quant2Alpha/Q2A_CandlestickPatterns/1 as cp
// Calculate candle properties
[bodyHi, bodyLo, body, smallBody, longBody, upShadow, dnShadow, hasUpShadow, hasDnShadow, whiteBody, blackBody, candleRange, isInsideBar, bodyMiddle, shadowEquals, isDojiBody, doji] = cp.calculateCandleProperties(open, close, high, low, ta.ema(close - open, 14), 5.0, 10.0, 10.0)
// Define trend
upTrend = close > ta.sma(close, 50)
downTrend = close < ta.sma(close, 50)
// Detect patterns
[hammerDetected, hammerName, hammerType, hammerDesc] = cp.detectHammerBullish(smallBody, body, bodyLo, hl2, dnShadow, 2.0, hasUpShadow, downTrend)
[shootingStarDetected, shootingStarName, shootingStarType, shootingStarDesc] = cp.detectShootingStarBearish(smallBody, body, bodyHi, hl2, upShadow, 2.0, hasDnShadow, upTrend)
// Visualize
if hammerDetected
label.new(bar_index, low, hammerName, style=label.style_label_up, color=color.green, textcolor=color.white, size=size.small, tooltip=hammerDesc)
if shootingStarDetected
label.new(bar_index, high, shootingStarName, style=label.style_label_down, color=color.red, textcolor=color.white, size=size.small, tooltip=shootingStarDesc)
```
## 📚 Library Structure
### Core Function
#### `calculateCandleProperties()`
Calculates essential candlestick properties for pattern detection.
**Parameters:**
- `p_open`, `p_close`, `p_high`, `p_low` - OHLC prices
- `bodyAvg` - Average body size (e.g., EMA of body sizes)
- `shadowPercent` - Minimum shadow size as % of body (typically 5.0)
- `shadowEqualsPercent` - Tolerance for equal shadows (typically 10.0)
- `dojiBodyPercent` - Max body size as % of range for doji (typically 10.0)
**Returns:** 17 properties including body dimensions, shadows, and candle characteristics
## 📊 Available Patterns
### Single Candle Patterns (13 patterns)
#### Bullish (5)
| Pattern | Function | Description |
| --------------------- | -------------------------------- | ----------------------------------------------------------- |
| **Hammer** | `detectHammerBullish()` | Small body at top, long lower shadow, forms in downtrend |
| **Inverted Hammer** | `detectInvertedHammerBullish()` | Small body at bottom, long upper shadow, forms in downtrend |
| **Marubozu White** | `detectMarubozuWhiteBullish()` | Long green body with little to no shadows |
| **Long Lower Shadow** | `detectLongLowerShadowBullish()` | Lower shadow is 75%+ of total range |
| **Dragonfly Doji** | `detectDragonflyDojiBullish()` | Doji with long lower shadow, no upper shadow |
#### Bearish (5)
| Pattern | Function | Description |
| --------------------- | -------------------------------- | --------------------------------------------------------- |
| **Hanging Man** | `detectHangingManBearish()` | Small body at top, long lower shadow, forms in uptrend |
| **Shooting Star** | `detectShootingStarBearish()` | Small body at bottom, long upper shadow, forms in uptrend |
| **Marubozu Black** | `detectMarubozuBlackBearish()` | Long red body with little to no shadows |
| **Long Upper Shadow** | `detectLongUpperShadowBearish()` | Upper shadow is 75%+ of total range |
| **Gravestone Doji** | `detectGravestoneDojiBearish()` | Doji with long upper shadow, no lower shadow |
#### Neutral (3)
| Pattern | Function | Description |
| ---------------------- | -------------------------- | --------------------------------------------- |
| **Doji** | `detectDoji()` | Open equals close, indicates indecision |
| **Spinning Top White** | `detectSpinningTopWhite()` | Small green body with long shadows both sides |
| **Spinning Top Black** | `detectSpinningTopBlack()` | Small red body with long shadows both sides |
### Two Candle Patterns (15 patterns)
#### Bullish (7)
| Pattern | Function | Description |
| ------------------------ | ------------------------------ | ------------------------------------------------------ |
| **Rising Window** | `detectRisingWindowBullish()` | Gap up between two candles in uptrend |
| **Tweezer Bottom** | `detectTweezerBottomBullish()` | Two candles with identical lows in downtrend |
| **Piercing** | `detectPiercingBullish()` | Green candle closes above midpoint of prior red candle |
| **Doji Star Bullish** | `detectDojiStarBullish()` | Doji gaps down after red candle in downtrend |
| **Engulfing Bullish** | `detectEngulfingBullish()` | Large green candle engulfs prior small red candle |
| **Harami Bullish** | `detectHaramiBullish()` | Small green candle contained in prior large red candle |
| **Harami Cross Bullish** | `detectHaramiCrossBullish()` | Doji contained in prior large red candle |
#### Bearish (8)
| Pattern | Function | Description |
| ------------------------ | ------------------------------- | ------------------------------------------------------ |
| **On Neck** | `detectOnNeckBearish()` | Small green closes near prior red candle's low |
| **Falling Window** | `detectFallingWindowBearish()` | Gap down between two candles in downtrend |
| **Tweezer Top** | `detectTweezerTopBearish()` | Two candles with identical highs in uptrend |
| **Dark Cloud Cover** | `detectDarkCloudCoverBearish()` | Red candle closes below midpoint of prior green candle |
| **Doji Star Bearish** | `detectDojiStarBearish()` | Doji gaps up after green candle in uptrend |
| **Engulfing Bearish** | `detectEngulfingBearish()` | Large red candle engulfs prior small green candle |
| **Harami Bearish** | `detectHaramiBearish()` | Small red candle contained in prior large green candle |
| **Harami Cross Bearish** | `detectHaramiCrossBearish()` | Doji contained in prior large green candle |
### Three Candle Patterns (14 patterns)
#### Bullish (7)
| Pattern | Function | Description |
| -------------------------- | ----------------------------------- | ------------------------------------------------ |
| **Upside Tasuki Gap** | `detectUpsideTasukiGapBullish()` | Three candles with gap that fails to close |
| **Morning Doji Star** | `detectMorningDojiStarBullish()` | Red, gapped doji, green - stronger morning star |
| **Morning Star** | `detectMorningStarBullish()` | Red, small middle, green - classic reversal |
| **Three White Soldiers** | `detectThreeWhiteSoldiersBullish()` | Three consecutive long green candles |
| **Abandoned Baby Bullish** | `detectAbandonedBabyBullish()` | Doji gaps away from both surrounding candles |
| **Tri-Star Bullish** | `detectTriStarBullish()` | Three dojis with gaps between them |
| **Kicking Bullish** | `detectKickingBullish()` | Black marubozu followed by gapped white marubozu |
#### Bearish (7)
| Pattern | Function | Description |
| -------------------------- | ---------------------------------- | ------------------------------------------------ |
| **Downside Tasuki Gap** | `detectDownsideTasukiGapBearish()` | Three candles with gap that fails to close |
| **Evening Doji Star** | `detectEveningDojiStarBearish()` | Green, gapped doji, red - stronger evening star |
| **Evening Star** | `detectEveningStarBearish()` | Green, small middle, red - classic reversal |
| **Three Black Crows** | `detectThreeBlackCrowsBearish()` | Three consecutive long red candles |
| **Abandoned Baby Bearish** | `detectAbandonedBabyBearish()` | Doji gaps away from both surrounding candles |
| **Tri-Star Bearish** | `detectTriStarBearish()` | Three dojis with gaps between them |
| **Kicking Bearish** | `detectKickingBearish()` | White marubozu followed by gapped black marubozu |
### Five Candle Patterns (2 patterns)
#### Bullish (1)
| Pattern | Function | Description |
| ------------------------ | ----------------------------------- | ----------------------------------------------------- |
| **Rising Three Methods** | `detectRisingThreeMethodsBullish()` | Long green, three small reds inside range, long green |
#### Bearish (1)
| Pattern | Function | Description |
| ------------------------- | ------------------------------------ | --------------------------------------------------- |
| **Falling Three Methods** | `detectFallingThreeMethodsBearish()` | Long red, three small greens inside range, long red |
## 💡 Advanced Usage Examples
### Multi-Pattern Strategy
```pinescript
//version=6
strategy("Multi-Pattern Strategy", overlay=true)
import Quant2Alpha/Q2A_CandlestickPatterns/1 as cp
// Setup
bodyAvg = ta.ema(math.abs(close - open), 14)
[bodyHi, bodyLo, body, smallBody, longBody, upShadow, dnShadow, hasUpShadow, hasDnShadow, whiteBody, blackBody, candleRange, isInsideBar, bodyMiddle, shadowEquals, isDojiBody, doji] = cp.calculateCandleProperties(open, close, high, low, bodyAvg, 5.0, 10.0, 10.0)
// Trends
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
upTrend = close > sma50 and sma50 > sma200
downTrend = close < sma50 and sma50 < sma200
// Detect bullish patterns
[hammer, _, _, _] = cp.detectHammerBullish(smallBody, body, bodyLo, hl2, dnShadow, 2.0, hasUpShadow, downTrend)
[engulfing, _, _, _] = cp.detectEngulfingBullish(downTrend, whiteBody, longBody, blackBody, smallBody, close, open)
[morningStar, _, _, _] = cp.detectMorningStarBullish(longBody, smallBody, downTrend, blackBody, whiteBody, bodyHi, bodyLo, bodyMiddle)
// Detect bearish patterns
[shootingStar, _, _, _] = cp.detectShootingStarBearish(smallBody, body, bodyHi, hl2, upShadow, 2.0, hasDnShadow, upTrend)
[darkCloud, _, _, _] = cp.detectDarkCloudCoverBearish(upTrend, whiteBody, longBody, blackBody, open, high, close, bodyMiddle)
[eveningStar, _, _, _] = cp.detectEveningStarBearish(longBody, smallBody, upTrend, whiteBody, blackBody, bodyLo, bodyHi, bodyMiddle)
// Entry signals
bullishSignal = hammer or engulfing or morningStar
bearishSignal = shootingStar or darkCloud or eveningStar
// Execute trades
if bullishSignal and strategy.position_size == 0
strategy.entry("Long", strategy.long)
if bearishSignal and strategy.position_size > 0
strategy.close("Long")
```
### Pattern Scanner Indicator
```pinescript
//version=6
indicator("Pattern Scanner", overlay=true)
import Quant2Alpha/Q2A_CandlestickPatterns/1 as cp
// Configuration
showBullish = input.bool(true, "Show Bullish Patterns")
showBearish = input.bool(true, "Show Bearish Patterns")
showNeutral = input.bool(false, "Show Neutral Patterns")
// Calculate properties
bodyAvg = ta.ema(math.abs(close - open), 14)
[bodyHi, bodyLo, body, smallBody, longBody, upShadow, dnShadow, hasUpShadow, hasDnShadow, whiteBody, blackBody, candleRange, isInsideBar, bodyMiddle, shadowEquals, isDojiBody, doji] = cp.calculateCandleProperties(open, close, high, low, bodyAvg, 5.0, 10.0, 10.0)
// Trends
upTrend = close > ta.sma(close, 50)
downTrend = close < ta.sma(close, 50)
// Scan for all patterns and display
// (Add pattern detection and visualization logic here)
```
## 🔧 Configuration Best Practices
### Recommended Parameter Values
| Parameter | Typical Value | Description |
| ---------------------- | ----------------------------- | ------------------------------- |
| `bodyAvg` | `ta.ema(abs(close-open), 14)` | 14-period EMA of body size |
| `shadowPercent` | `5.0` | 5% of body for shadow detection |
| `shadowEqualsPercent` | `10.0` | 10% tolerance for equal shadows |
| `dojiBodyPercent` | `10.0` | Body ≤10% of range = doji |
| `factor` (hammer/star) | `2.0` | Shadow should be 2x body size |
### Trend Definition
```pinescript
// Simple SMA crossover
upTrend = close > ta.sma(close, 50)
downTrend = close < ta.sma(close, 50)
// Double SMA confirmation
upTrend = close > ta.sma(close, 50) and ta.sma(close, 50) > ta.sma(close, 200)
downTrend = close < ta.sma(close, 50) and ta.sma(close, 50) < ta.sma(close, 200)
// EMA trend
upTrend = close > ta.ema(close, 20)
downTrend = close < ta.ema(close, 20)
```
## 📖 Function Return Format
All pattern detection functions return a tuple with 4 elements:
```pinescript
[detected, name, type, description]
```
- **detected** (bool) - `true` if pattern is found, `false` otherwise
- **name** (string) - Pattern name (e.g., "Hammer", "Shooting Star")
- **type** (string) - "Bullish", "Bearish", or "Neutral"
- **description** (string) - Detailed explanation of the pattern
### Example
```pinescript
[isHammer, patternName, patternType, patternInfo] = cp.detectHammerBullish(...)
if isHammer
log.info("Pattern: " + patternName) // "Hammer"
log.info("Type: " + patternType) // "Bullish"
log.info("Info: " + patternInfo) // Full description
```
## 🎯 Pattern Reliability
### High Reliability (Strong Signals)
- Engulfing patterns (Bullish/Bearish)
- Morning/Evening Star formations
- Three White Soldiers / Three Black Crows
- Hammer / Shooting Star (with confirmation)
### Medium Reliability (Use with Confirmation)
- Harami patterns
- Piercing / Dark Cloud Cover
- Tweezer Top/Bottom
- Doji Star patterns
### Context-Dependent (Require Trend Analysis)
- Window patterns (gaps)
- Kicking patterns
- Tasuki Gap patterns
- Three Methods patterns
## 📝 Notes
- **Trend Context is Critical**: Most reversal patterns require proper trend identification for accuracy
- **Confirmation Recommended**: Wait for next candle confirmation before taking action
- **Volume Matters**: Consider volume alongside patterns (not included in this library)
- **Multiple Timeframes**: Check patterns across multiple timeframes for stronger signals
- **Risk Management**: Always use stop losses regardless of pattern strength
## 🔗 Integration with Other Indicators
This library works well with:
- Moving averages (trend confirmation)
- RSI/Stochastic (overbought/oversold)
- Volume indicators (confirmation)
- Support/Resistance levels (context)
- ATR (position sizing)
## 📄 License
This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org/MPL/2.0/
## 👤 Author
© Quant2Alpha
## 🆘 Support
For issues, questions, or contributions, please refer to the QUANT2ALPHA documentation or community channels.
---
**Version:** 1.0
**Pine Script Version:** 6
**Last Updated:** 2025
Библиотека Pine
В истинном духе TradingView автор опубликовал этот код Pine как библиотеку с открытым исходным кодом, чтобы другие программисты Pine из нашего сообщества могли её использовать. Браво автору! Вы можете использовать эту библиотеку для личного пользования или в других публикациях с открытым исходным кодом, но повторное использование этого кода в публикациях регулируется Правилами поведения.
Отказ от ответственности
Библиотека Pine
В истинном духе TradingView автор опубликовал этот код Pine как библиотеку с открытым исходным кодом, чтобы другие программисты Pine из нашего сообщества могли её использовать. Браво автору! Вы можете использовать эту библиотеку для личного пользования или в других публикациях с открытым исходным кодом, но повторное использование этого кода в публикациях регулируется Правилами поведения.