Detecting Basic Candle Patterns
Programmatically detecting higher close, lower close, basic engulfing candles, fractal engulfing candles, and engulfing micro-gaps.
Why Detect Candle Patterns Programmatically?
Every candlestick on your BTC or ETH chart encodes a micro-story about buyer/seller dynamics within that period. A higher close means buyers won the bar; a lower close means sellers won. Engulfing candles reveal momentum shifts. Detecting these patterns manually across dozens of assets and timeframes is impossible, but PineScript can scan every bar on every chart in milliseconds and mark exactly what you need to see.
In this lesson you will build pattern detectors from the simplest (higher/lower close) to the most nuanced (fractal engulfing candles with micro-gaps). Each pattern includes a complete PineScript code example with visual plotting, detailed logic explanations, and practical context for crypto markets.
Higher Close / Lower Close Detection
The simplest candle classification is whether the bar closed higher or lower than it opened. A higher close (bullish bar) means close > open. A lower close (bearish bar) means close < open. While trivial on its own, this forms the foundation for every pattern that follows. Consecutive higher closes after a pullback on SOL, for example, often signal the start of a momentum leg.
1//@version=52indicator("Higher/Lower Close", overlay=true)34higherClose = close > open5lowerClose = close < open6doji = math.abs(close - open) <= (high - low) * 0.178barcolor(higherClose ? color.new(color.green, 20) :9 lowerClose ? color.new(color.red, 20) :10 color.new(color.gray, 20))1112// Count consecutive bullish/bearish bars13var int bullStreak = 014var int bearStreak = 015if higherClose16 bullStreak := bullStreak + 117 bearStreak := 018else if lowerClose19 bearStreak := bearStreak + 120 bullStreak := 021else22 bullStreak := 023 bearStreak := 02425// Mark streaks of 3+ consecutive bars26plotshape(bullStreak == 3, "3 Bull Streak", shape.triangleup,27 location.belowbar, color.green, size=size.tiny)28plotshape(bearStreak == 3, "3 Bear Streak", shape.triangledown,29 location.abovebar, color.red, size=size.tiny)Doji threshold matters
Basic Engulfing Candle Detection
An engulfing pattern is a two-bar formation where the current bar's body completely encompasses the previous bar's body. A bullish engulfing occurs when a bearish bar is followed by a larger bullish bar that opens below the prior close and closes above the prior open. This signals that buyers overwhelmed sellers with superior force. On BTC, a bullish engulfing at a key support level like the 200-day moving average often precedes a multi-day rally.
1//@version=52indicator("Engulfing Patterns", overlay=true)34// Body calculations5body = math.abs(close - open)6bodyHigh = math.max(close, open)7bodyLow = math.min(close, open)89prevBody = math.abs(close[1] - open[1])10prevBodyHigh = math.max(close[1], open[1])11prevBodyLow = math.min(close[1], open[1])1213// Bullish engulfing: bearish prev bar, bullish current bar,14// current body fully engulfs previous body15bullEngulf = close[1] < open[1] and16 close > open and17 bodyLow <= prevBodyLow and18 bodyHigh >= prevBodyHigh and19 body > prevBody2021// Bearish engulfing: bullish prev bar, bearish current bar,22// current body fully engulfs previous body23bearEngulf = close[1] > open[1] and24 close < open and25 bodyLow <= prevBodyLow and26 bodyHigh >= prevBodyHigh and27 body > prevBody2829plotshape(bullEngulf, "Bull Engulf", shape.triangleup,30 location.belowbar, color.green, size=size.small,31 text="BE")32plotshape(bearEngulf, "Bear Engulf", shape.triangledown,33 location.abovebar, color.red, size=size.small,34 text="BE")3536alertcondition(bullEngulf, "Bullish Engulfing",37 "Bullish engulfing candle detected")38alertcondition(bearEngulf, "Bearish Engulfing",39 "Bearish engulfing candle detected")| Body | math.abs(close - open): the absolute distance between open and close. Represents conviction. |
| Body High | math.max(close, open): the upper edge of the body, regardless of candle direction. |
| Body Low | math.min(close, open): the lower edge of the body, regardless of candle direction. |
| Engulf condition | Current body high >= previous body high AND current body low <= previous body low AND current body > previous body. |
Fractal Engulfing Candles
A standard engulfing pattern fires frequently and produces many false signals. A fractal engulfing adds a structural filter: the engulfing pattern must occur at a fractal pivot point, a local high or low surrounded by lower highs or higher lows on both sides. This dramatically reduces noise because it only fires at significant swing points. On ETH's 4-hour chart, fractal engulfing patterns at range boundaries frequently mark the start of breakout moves.
1//@version=52indicator("Fractal Engulfing", overlay=true)34fractalLen = input.int(2, "Fractal Lookback", minval=1, maxval=5)56// Detect fractals: a pivot low is a bar whose low is lower than7// the lows of fractalLen bars on each side8fractalLow = ta.pivotlow(low, fractalLen, fractalLen)9fractalHigh = ta.pivothigh(high, fractalLen, fractalLen)1011// Track if a fractal occurred recently (within last 3 bars)12var bool recentFractalLow = false13var bool recentFractalHigh = false14var int fractalLowBar = 015var int fractalHighBar = 01617if not na(fractalLow)18 recentFractalLow := true19 fractalLowBar := bar_index20if not na(fractalHigh)21 recentFractalHigh := true22 fractalHighBar := bar_index2324// Reset if too many bars have passed25if bar_index - fractalLowBar > fractalLen + 326 recentFractalLow := false27if bar_index - fractalHighBar > fractalLen + 328 recentFractalHigh := false2930// Standard engulfing logic31body = math.abs(close - open)32bodyHigh = math.max(close, open)33bodyLow = math.min(close, open)34prevBodyHigh = math.max(close[1], open[1])35prevBodyLow = math.min(close[1], open[1])3637bullEngulf = close[1] < open[1] and close > open and38 bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh39bearEngulf = close[1] > open[1] and close < open and40 bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh4142// Fractal engulfing: engulfing at a fractal pivot43fractalBullEngulf = bullEngulf and recentFractalLow44fractalBearEngulf = bearEngulf and recentFractalHigh4546plotshape(fractalBullEngulf, "Fractal Bull Engulf",47 shape.labelup, location.belowbar,48 color.new(color.green, 10), text="FBE",49 textcolor=color.white, size=size.small)50plotshape(fractalBearEngulf, "Fractal Bear Engulf",51 shape.labeldown, location.abovebar,52 color.new(color.red, 10), text="FBE",53 textcolor=color.white, size=size.small)Why fractal engulfing patterns work
Engulfing Candle Micro-Gaps
A micro-gap within an engulfing pattern occurs when there is a small gap between the previous bar's close and the current bar's open. In crypto, which trades 24/7, true gaps are rare, but micro-gaps (a few ticks of separation) do occur on lower timeframes and add confluence. A bullish engulfing with a gap down open that then closes above the prior body shows even more buyer aggression: price opened weak and was immediately bought up. On SOL's 15-minute chart during high-volume periods, these micro-gap engulfing patterns frequently mark local bottoms.
1//@version=52indicator("Micro-Gap Engulfing", overlay=true)34gapThreshold = input.float(0.1, "Min Gap (%)", step=0.05,5 tooltip="Minimum gap size as % of price")67body = math.abs(close - open)8bodyHigh = math.max(close, open)9bodyLow = math.min(close, open)10prevBodyHigh = math.max(close[1], open[1])11prevBodyLow = math.min(close[1], open[1])1213// Calculate gap between previous close and current open14gapSize = math.abs(open - close[1])15gapPct = gapSize / close[1] * 10016hasGap = gapPct >= gapThreshold1718// Bull engulf with gap down: opens below prev close, closes above prev body19gapDownOpen = open < close[1]20bullEngulfBody = close > open and bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh21microGapBullish = bullEngulfBody and gapDownOpen and hasGap2223// Bear engulf with gap up: opens above prev close, closes below prev body24gapUpOpen = open > close[1]25bearEngulfBody = close < open and bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh26microGapBearish = bearEngulfBody and gapUpOpen and hasGap2728plotshape(microGapBullish, "MG Bull", shape.labelup,29 location.belowbar, color.new(#00e676, 10),30 text="MG", textcolor=color.white, size=size.small)31plotshape(microGapBearish, "MG Bear", shape.labeldown,32 location.abovebar, color.new(#ff1744, 10),33 text="MG", textcolor=color.white, size=size.small)3435bgcolor(microGapBullish ? color.new(color.green, 92) :36 microGapBearish ? color.new(color.red, 92) : na)Combined Basic Pattern Indicator
Here is a complete indicator that combines all four basic patterns into a single script with configurable inputs and distinct visual markers for each pattern type.
1//@version=52indicator("Basic Candle Patterns", overlay=true,3 max_labels_count=200)45// Inputs6showStreaks = input.bool(true, "Show Bull/Bear Streaks")7showEngulfing = input.bool(true, "Show Engulfing Patterns")8showFractal = input.bool(true, "Show Fractal Engulfing")9showMicroGap = input.bool(true, "Show Micro-Gap Engulfing")10fractalLen = input.int(2, "Fractal Lookback", minval=1, maxval=5)11gapThreshold = input.float(0.1, "Micro-Gap Min (%)", step=0.05)12streakLen = input.int(3, "Min Streak Length", minval=2, maxval=6)1314// Core body calculations15body = math.abs(close - open)16bodyHigh = math.max(close, open)17bodyLow = math.min(close, open)18prevBodyHigh = math.max(close[1], open[1])19prevBodyLow = math.min(close[1], open[1])20prevBody = math.abs(close[1] - open[1])2122bullBar = close > open23bearBar = close < open2425// 1. Streak detection26var int bullStreak = 027var int bearStreak = 028bullStreak := bullBar ? bullStreak + 1 : 029bearStreak := bearBar ? bearStreak + 1 : 03031streakBull = showStreaks and bullStreak == streakLen32streakBear = showStreaks and bearStreak == streakLen3334// 2. Engulfing35engulfBase = bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh and body > prevBody36bullEngulf = showEngulfing and close[1] < open[1] and bullBar and engulfBase37bearEngulf = showEngulfing and close[1] > open[1] and bearBar and engulfBase3839// 3. Fractal engulfing40fracLow = ta.pivotlow(low, fractalLen, fractalLen)41fracHigh = ta.pivothigh(high, fractalLen, fractalLen)42var bool rFL = false43var bool rFH = false44var int fLB = 045var int fHB = 046if not na(fracLow)47 rFL := true48 fLB := bar_index49if not na(fracHigh)50 rFH := true51 fHB := bar_index52if bar_index - fLB > fractalLen + 353 rFL := false54if bar_index - fHB > fractalLen + 355 rFH := false5657fracBullEng = showFractal and bullEngulf and rFL58fracBearEng = showFractal and bearEngulf and rFH5960// 4. Micro-gap engulfing61gapPct = math.abs(open - close[1]) / close[1] * 10062hasGap = gapPct >= gapThreshold63mgBull = showMicroGap and bullEngulf and open < close[1] and hasGap64mgBear = showMicroGap and bearEngulf and open > close[1] and hasGap6566// Visual output: use different shapes per pattern67plotshape(streakBull, "Streak Bull", shape.diamond,68 location.belowbar, color.lime, size=size.tiny)69plotshape(streakBear, "Streak Bear", shape.diamond,70 location.abovebar, color.orange, size=size.tiny)71plotshape(bullEngulf and not fracBullEng and not mgBull, "Bull Engulf",72 shape.triangleup, location.belowbar, color.green, size=size.small)73plotshape(bearEngulf and not fracBearEng and not mgBear, "Bear Engulf",74 shape.triangledown, location.abovebar, color.red, size=size.small)75plotshape(fracBullEng, "Frac Bull Eng", shape.labelup,76 location.belowbar, color.new(color.green, 0),77 text="F", textcolor=color.white, size=size.small)78plotshape(fracBearEng, "Frac Bear Eng", shape.labeldown,79 location.abovebar, color.new(color.red, 0),80 text="F", textcolor=color.white, size=size.small)81plotshape(mgBull, "MG Bull", shape.arrowup,82 location.belowbar, color.teal, size=size.small)83plotshape(mgBear, "MG Bear", shape.arrowdown,84 location.abovebar, color.purple, size=size.small)8586alertcondition(bullEngulf or fracBullEng or mgBull,87 "Any Bullish Pattern", "Bullish candle pattern detected")88alertcondition(bearEngulf or fracBearEng or mgBear,89 "Any Bearish Pattern", "Bearish candle pattern detected")Pattern hierarchy
Put this lesson to work
Free on Thrive, no account needed.