PINE LIBRARY

AllCandlestickPatternsLibrary

178
All Candlestick Patterns Library

The Candlestick Patterns Library is a Pine Script (version 6) library extracted from the All Candlestick Patterns indicator. It provides a comprehensive set of functions to calculate candlestick properties, detect market trends, and identify various candlestick patterns (bullish, bearish, and neutral). The library is designed for reusability, enabling TradingView users to incorporate pattern detection into their own scripts, such as indicators or strategies.
The library is organized into three main sections:

Trend Detection: Functions to determine market trends (uptrend or downtrend) based on user-defined rules.
Candlestick Property Calculations: A function to compute core properties of a candlestick, such as body size, shadow lengths, and doji characteristics.
Candlestick Pattern Detection: Functions to detect specific candlestick patterns, each returning a tuple with detection status, pattern name, type, and description.

Library Structure
1. Trend Detection
This section includes the detectTrend function, which identifies whether the market is in an uptrend or downtrend based on user-specified rules, such as the relationship between the closing price and Simple Moving Averages (SMAs).

Function: detectTrend
Parameters:
downTrend (bool): Initial downtrend condition.
upTrend (bool): Initial uptrend condition.
trendRule (string): The rule for trend detection ("SMA50" or "SMA50, SMA200").
p_close (float): Current closing price.
sma50 (float): Simple Moving Average over 50 periods.
sma200 (float): Simple Moving Average over 200 periods.


Returns: A tuple [bool downTrend, bool upTrend] indicating the detected trend.
Logic:
If trendRule is "SMA50", a downtrend is detected when p_close < sma50, and an uptrend when p_close > sma50.
If trendRule is "SMA50, SMA200", a downtrend is detected when p_close < sma50 and sma50 < sma200, and an uptrend when p_close > sma50 and sma50 > sma200.





2. Candlestick Property Calculations
This section includes the calculateCandleProperties function, which computes essential properties of a candlestick based on OHLC (Open, High, Low, Close) data and configuration parameters.

Function: calculateCandleProperties
Parameters:
p_open (float): Candlestick open price.
p_close (float): Candlestick close price.
p_high (float): Candlestick high price.
p_low (float): Candlestick low price.
bodyAvg (float): Average body size (e.g., from EMA of body sizes).
shadowPercent (float): Minimum shadow size as a percentage of body size.
shadowEqualsPercent (float): Tolerance for equal shadows in doji detection.
dojiBodyPercent (float): Maximum body size as a percentage of range for doji detection.


Returns: A tuple containing 17 properties:
C_BodyHi (float): Higher of open or close price.
C_BodyLo (float): Lower of open or close price.
C_Body (float): Body size (difference between C_BodyHi and C_BodyLo).
C_SmallBody (bool): True if body size is below bodyAvg.
C_LongBody (bool): True if body size is above bodyAvg.
C_UpShadow (float): Upper shadow length (p_high - C_BodyHi).
C_DnShadow (float): Lower shadow length (C_BodyLo - p_low).
C_HasUpShadow (bool): True if upper shadow exceeds shadowPercent of body.
C_HasDnShadow (bool): True if lower shadow exceeds shadowPercent of body.
C_WhiteBody (bool): True if candle is bullish (p_open < p_close).
C_BlackBody (bool): True if candle is bearish (p_open > p_close).
C_Range (float): Candlestick range (p_high - p_low).
C_IsInsideBar (bool): True if current candle body is inside the previous candle's body.
C_BodyMiddle (float): Midpoint of the candle body.
C_ShadowEquals (bool): True if upper and lower shadows are equal within shadowEqualsPercent.
C_IsDojiBody (bool): True if body size is small relative to range (C_Body <= C_Range * dojiBodyPercent / 100).
C_Doji (bool): True if the candle is a doji (C_IsDojiBody and C_ShadowEquals).


Purpose: These properties are used by pattern detection functions to evaluate candlestick formations.



3. Candlestick Pattern Detection
This section contains functions to detect specific candlestick patterns, each returning a tuple [bool detected, string name, string type, string description]. The patterns are categorized as bullish, bearish, or neutral, and include detailed descriptions for use in tooltips or alerts.
Supported Patterns
The library supports the following candlestick patterns, grouped by type:

Bullish Patterns:

Rising Window: A two-candle continuation pattern in an uptrend with a price gap between the first candle's high and the second candle's low.
Rising Three Methods: A five-candle continuation pattern with a long green candle, three short red candles, and another long green candle.
Tweezer Bottom: A two-candle reversal pattern in a downtrend with nearly identical lows.
Upside Tasuki Gap: A three-candle continuation pattern in an uptrend with a gap between the first two green candles and a red candle closing partially into the gap.
Doji Star (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji gapping down.
Morning Doji Star: A three-candle reversal pattern with a long red candle, a doji gapping down, and a long green candle.
Piercing: A two-candle reversal pattern in a downtrend with a red candle followed by a green candle closing above the midpoint of the first.
Hammer: A single-candle reversal pattern in a downtrend with a small body and a long lower shadow.
Inverted Hammer: A single-candle reversal pattern in a downtrend with a small body and a long upper shadow.
Morning Star: A three-candle reversal pattern with a long red candle, a short candle gapping down, and a long green candle.
Marubozu White: A single-candle pattern with a long green body and minimal shadows.
Dragonfly Doji: A single-candle reversal pattern in a downtrend with a doji where open and close are at the high.
Harami Cross (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a doji inside its body.
Harami (Bullish): A two-candle reversal pattern in a downtrend with a long red candle followed by a small green candle inside its body.
Long Lower Shadow: A single-candle pattern with a long lower shadow indicating buyer strength.
Three White Soldiers: A three-candle reversal pattern with three long green candles in a downtrend.
Engulfing (Bullish): A two-candle reversal pattern in a downtrend with a small red candle followed by a larger green candle engulfing it.
Abandoned Baby (Bullish): A three-candle reversal pattern with a long red candle, a doji gapping down, and a green candle gapping up.
Tri-Star (Bullish): A three-candle reversal pattern with three doji candles in a downtrend, with gaps between them.
Kicking (Bullish): A two-candle reversal pattern with a bearish marubozu followed by a bullish marubozu gapping up.


Bearish Patterns:

On Neck: A two-candle continuation pattern in a downtrend with a long red candle followed by a short green candle closing near the first candle's low.
Falling Window: A two-candle continuation pattern in a downtrend with a price gap between the first candle's low and the second candle's high.
Falling Three Methods: A five-candle continuation pattern with a long red candle, three short green candles, and another long red candle.
Tweezer Top: A two-candle reversal pattern in an uptrend with nearly identical highs.
Dark Cloud Cover: A two-candle reversal pattern in an uptrend with a green candle followed by a red candle opening above the high and closing below the midpoint.
Downside Tasuki Gap: A three-candle continuation pattern in a downtrend with a gap between the first two red candles and a green candle closing partially into the gap.
Evening Doji Star: A three-candle reversal pattern with a long green candle, a doji gapping up, and a long red candle.
Doji Star (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji gapping up.
Hanging Man: A single-candle reversal pattern in an uptrend with a small body and a long lower shadow.
Shooting Star: A single-candle reversal pattern in an uptrend with a small body and a long upper shadow.
Evening Star: A three-candle reversal pattern with a long green candle, a short candle gapping up, and a long red candle.
Marubozu Black: A single-candle pattern with a long red body and minimal shadows.
Gravestone Doji: A single-candle reversal pattern in an uptrend with a doji where open and close are at the low.
Harami Cross (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a doji inside its body.
Harami (Bearish): A two-candle reversal pattern in an uptrend with a long green candle followed by a small red candle inside its body.
Long Upper Shadow: A single-candle pattern with a long upper shadow indicating seller strength.
Three Black Crows: A three-candle reversal pattern with three long red candles in an uptrend.
Engulfing (Bearish): A two-candle reversal pattern in an uptrend with a small green candle followed by a larger red candle engulfing it.
Abandoned Baby (Bearish): A three-candle reversal pattern with a long green candle, a doji gapping up, and a red candle gapping down.
Tri-Star (Bearish): A three-candle reversal pattern with three doji candles in an uptrend, with gaps between them.
Kicking (Bearish): A two-candle reversal pattern with a bullish marubozu followed by a bearish marubozu gapping down.


Neutral Patterns:

Doji: A single-candle pattern with a very small body, indicating indecision.
Spinning Top White: A single-candle pattern with a small green body and long upper and lower shadows, indicating indecision.
Spinning Top Black: A single-candle pattern with a small red body and long upper and lower shadows, indicating indecision.



Pattern Detection Functions
Each pattern detection function evaluates specific conditions based on candlestick properties (from calculateCandleProperties) and trend conditions (from detectTrend). The functions return:

detected (bool): True if the pattern is detected.
name (string): The name of the pattern (e.g., "On Neck").
type (string): The pattern type ("Bullish", "Bearish", or "Neutral").
description (string): A detailed description of the pattern for use in tooltips or alerts.

For example, the detectOnNeckBearish function checks for a bearish On Neck pattern by verifying a downtrend, a long red candle followed by a short green candle, and specific price relationships.
Usage Example
To use the library in a TradingView indicator, you can import it and call its functions as shown below:
//version=6
indicator("Candlestick Pattern Detector", overlay=true)
import CandlestickPatternsLibrary as cp

// Calculate SMA for trend detection
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)
[downTrend, upTrend] = cp.detectTrend(true, true, "SMA50", close, sma50, sma200)

// Calculate candlestick properties
bodyAvg = ta.ema(math.max(close, open) - math.min(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, 100.0, 5.0)

// Detect a pattern (e.g., On Neck Bearish)
[onNeckDetected, onNeckName, onNeckType, onNeckDesc] = cp.detectOnNeckBearish(downTrend, blackBody, longBody, whiteBody, open, close, low, bodyAvg, smallBody, candleRange)
if onNeckDetected
label.new(bar_index, low, onNeckName, style=label.style_label_up, color=color.red, textcolor=color.white, tooltip=onNeckDesc)

// Detect another pattern (e.g., Piercing Bullish)
[piercingDetected, piercingName, piercingType, piercingDesc] = cp.detectPiercingBullish(downTrend, blackBody, longBody, whiteBody, open, low, close, bodyMiddle)
if piercingDetected
label.new(bar_index, low, piercingName, style=label.style_label_up, color=color.blue, textcolor=color.white, tooltip=piercingDesc)

Steps in the Example

Import the Library: Use import CandlestickPatternsLibrary as cp to access the library's functions.
Calculate Trend: Use detectTrend to determine the market trend based on SMA50 or SMA50/SMA200 rules.
Calculate Candlestick Properties: Use calculateCandleProperties to compute properties like body size, shadow lengths, and doji status.
Detect Patterns: Call specific pattern detection functions (e.g., detectOnNeckBearish, detectPiercingBullish) and use the returned values to display labels or alerts.
Visualize Patterns: Use label.new to display detected patterns on the chart with their names, types, and descriptions.

Key Features

Modularity: The library is designed as a standalone module, making it easy to integrate into other Pine Script projects.
Comprehensive Pattern Coverage: Supports over 40 candlestick patterns, covering bullish, bearish, and neutral formations.
Detailed Documentation: Each function includes comments with param and Returns annotations for clarity.
Reusability: Can be used in indicators, strategies, or alerts by importing the library and calling its functions.
Extracted from All Candlestick Patterns: The library is derived from the All Candlestick Patterns indicator, ensuring it inherits a well-tested foundation for pattern detection.

Notes for Developers

Pine Script Version: The library uses Pine Script version 6, as specified by //version=6.
Parameter Naming: Parameters use prefixes like p_ (e.g., p_open, p_close) to avoid conflicts with built-in variables.
Error Handling: The library has been fixed to address issues like undeclared identifiers (C_SmallBody, C_Range), unused arguments (factor), and improper comment formatting.
Testing: Developers should test the library in TradingView to ensure patterns are detected correctly under various market conditions.
Customization: Users can adjust parameters like bodyAvg, shadowPercent, shadowEqualsPercent, and dojiBodyPercent in calculateCandleProperties to fine-tune pattern detection sensitivity.

Conclusion
The Candlestick Patterns Library, extracted from the All Candlestick Patterns indicator, is a powerful tool for traders and developers looking to implement candlestick pattern detection in TradingView. Its modular design, comprehensive pattern support, and detailed documentation make it an ideal choice for building custom indicators or strategies. By leveraging the library's functions, users can analyze market trends, compute candlestick properties, and detect a wide range of patterns to inform their trading decisions.

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.