Skip to main content

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.

pine-Higher close / lower close detection
1//@version=5
2indicator("Higher/Lower Close", overlay=true)
3
4higherClose = close > open
5lowerClose = close < open
6doji = math.abs(close - open) <= (high - low) * 0.1
7
8barcolor(higherClose ? color.new(color.green, 20) :
9 lowerClose ? color.new(color.red, 20) :
10 color.new(color.gray, 20))
11
12// Count consecutive bullish/bearish bars
13var int bullStreak = 0
14var int bearStreak = 0
15if higherClose
16 bullStreak := bullStreak + 1
17 bearStreak := 0
18else if lowerClose
19 bearStreak := bearStreak + 1
20 bullStreak := 0
21else
22 bullStreak := 0
23 bearStreak := 0
24
25// Mark streaks of 3+ consecutive bars
26plotshape(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

A bar where the body is less than 10% of the total range is classified as a doji, neither buyers nor sellers won. Adjusting this threshold changes sensitivity. In high-volatility crypto like BTC on a 1-minute chart, you may want 5%; on a daily ETH chart, 10–15% works better because daily wicks tend to be proportionally larger.

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.

pine-Bullish and bearish engulfing detection
1//@version=5
2indicator("Engulfing Patterns", overlay=true)
3
4// Body calculations
5body = math.abs(close - open)
6bodyHigh = math.max(close, open)
7bodyLow = math.min(close, open)
8
9prevBody = math.abs(close[1] - open[1])
10prevBodyHigh = math.max(close[1], open[1])
11prevBodyLow = math.min(close[1], open[1])
12
13// Bullish engulfing: bearish prev bar, bullish current bar,
14// current body fully engulfs previous body
15bullEngulf = close[1] < open[1] and
16 close > open and
17 bodyLow <= prevBodyLow and
18 bodyHigh >= prevBodyHigh and
19 body > prevBody
20
21// Bearish engulfing: bullish prev bar, bearish current bar,
22// current body fully engulfs previous body
23bearEngulf = close[1] > open[1] and
24 close < open and
25 bodyLow <= prevBodyLow and
26 bodyHigh >= prevBodyHigh and
27 body > prevBody
28
29plotshape(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")
35
36alertcondition(bullEngulf, "Bullish Engulfing",
37 "Bullish engulfing candle detected")
38alertcondition(bearEngulf, "Bearish Engulfing",
39 "Bearish engulfing candle detected")
Bodymath.abs(close - open): the absolute distance between open and close. Represents conviction.
Body Highmath.max(close, open): the upper edge of the body, regardless of candle direction.
Body Lowmath.min(close, open): the lower edge of the body, regardless of candle direction.
Engulf conditionCurrent 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.

pine-Fractal engulfing pattern detection
1//@version=5
2indicator("Fractal Engulfing", overlay=true)
3
4fractalLen = input.int(2, "Fractal Lookback", minval=1, maxval=5)
5
6// Detect fractals: a pivot low is a bar whose low is lower than
7// the lows of fractalLen bars on each side
8fractalLow = ta.pivotlow(low, fractalLen, fractalLen)
9fractalHigh = ta.pivothigh(high, fractalLen, fractalLen)
10
11// Track if a fractal occurred recently (within last 3 bars)
12var bool recentFractalLow = false
13var bool recentFractalHigh = false
14var int fractalLowBar = 0
15var int fractalHighBar = 0
16
17if not na(fractalLow)
18 recentFractalLow := true
19 fractalLowBar := bar_index
20if not na(fractalHigh)
21 recentFractalHigh := true
22 fractalHighBar := bar_index
23
24// Reset if too many bars have passed
25if bar_index - fractalLowBar > fractalLen + 3
26 recentFractalLow := false
27if bar_index - fractalHighBar > fractalLen + 3
28 recentFractalHigh := false
29
30// Standard engulfing logic
31body = 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])
36
37bullEngulf = close[1] < open[1] and close > open and
38 bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh
39bearEngulf = close[1] > open[1] and close < open and
40 bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh
41
42// Fractal engulfing: engulfing at a fractal pivot
43fractalBullEngulf = bullEngulf and recentFractalLow
44fractalBearEngulf = bearEngulf and recentFractalHigh
45
46plotshape(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

Fractals identify structural turning points. When an engulfing candle coincides with a fractal, you are seeing a momentum shift at a structurally significant price level. On BTC, these signals at the bottom of a range often precede a move back to the range high. The combination of structural context plus candle momentum makes this a high-confluence signal.

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.

pine-Micro-gap engulfing detection
1//@version=5
2indicator("Micro-Gap Engulfing", overlay=true)
3
4gapThreshold = input.float(0.1, "Min Gap (%)", step=0.05,
5 tooltip="Minimum gap size as % of price")
6
7body = 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])
12
13// Calculate gap between previous close and current open
14gapSize = math.abs(open - close[1])
15gapPct = gapSize / close[1] * 100
16hasGap = gapPct >= gapThreshold
17
18// Bull engulf with gap down: opens below prev close, closes above prev body
19gapDownOpen = open < close[1]
20bullEngulfBody = close > open and bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh
21microGapBullish = bullEngulfBody and gapDownOpen and hasGap
22
23// Bear engulf with gap up: opens above prev close, closes below prev body
24gapUpOpen = open > close[1]
25bearEngulfBody = close < open and bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh
26microGapBearish = bearEngulfBody and gapUpOpen and hasGap
27
28plotshape(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)
34
35bgcolor(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.

pine-All basic patterns: combined indicator
1//@version=5
2indicator("Basic Candle Patterns", overlay=true,
3 max_labels_count=200)
4
5// Inputs
6showStreaks = 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)
13
14// Core body calculations
15body = 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])
21
22bullBar = close > open
23bearBar = close < open
24
25// 1. Streak detection
26var int bullStreak = 0
27var int bearStreak = 0
28bullStreak := bullBar ? bullStreak + 1 : 0
29bearStreak := bearBar ? bearStreak + 1 : 0
30
31streakBull = showStreaks and bullStreak == streakLen
32streakBear = showStreaks and bearStreak == streakLen
33
34// 2. Engulfing
35engulfBase = bodyLow <= prevBodyLow and bodyHigh >= prevBodyHigh and body > prevBody
36bullEngulf = showEngulfing and close[1] < open[1] and bullBar and engulfBase
37bearEngulf = showEngulfing and close[1] > open[1] and bearBar and engulfBase
38
39// 3. Fractal engulfing
40fracLow = ta.pivotlow(low, fractalLen, fractalLen)
41fracHigh = ta.pivothigh(high, fractalLen, fractalLen)
42var bool rFL = false
43var bool rFH = false
44var int fLB = 0
45var int fHB = 0
46if not na(fracLow)
47 rFL := true
48 fLB := bar_index
49if not na(fracHigh)
50 rFH := true
51 fHB := bar_index
52if bar_index - fLB > fractalLen + 3
53 rFL := false
54if bar_index - fHB > fractalLen + 3
55 rFH := false
56
57fracBullEng = showFractal and bullEngulf and rFL
58fracBearEng = showFractal and bearEngulf and rFH
59
60// 4. Micro-gap engulfing
61gapPct = math.abs(open - close[1]) / close[1] * 100
62hasGap = gapPct >= gapThreshold
63mgBull = showMicroGap and bullEngulf and open < close[1] and hasGap
64mgBear = showMicroGap and bearEngulf and open > close[1] and hasGap
65
66// Visual output: use different shapes per pattern
67plotshape(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)
85
86alertcondition(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

When multiple patterns fire on the same bar, the fractal engulfing and micro-gap variants are higher quality than a plain engulfing. The combined indicator above avoids duplicate markers by checking for the more specific pattern first. In live trading on BTC or ETH, prioritise fractal engulfing signals. They fire less often but at structurally better levels.

Put this lesson to work

Free on Thrive, no account needed.