Skip to main content

Advanced Candlestick Detection

Coding doji candles, hammers and shooting stars, calculating gaps, piercing line, dark cloud cover, and multi-bar reversal patterns.

Advanced Candlestick Patterns

Beyond basic engulfing patterns, professional traders use a repertoire of nuanced candle formations that encode specific buyer/seller dynamics. Doji candles reveal indecision. Hammers and shooting stars show rejection at key levels. Gaps expose overnight sentiment shifts. Piercing lines and dark cloud covers are two-bar reversal patterns with strict rules. In crypto's volatile markets, these patterns fire frequently: the skill is knowing which parameters to tune and which context filters to apply.

Doji Candle Detection

A doji occurs when the open and close are nearly equal, producing a tiny body relative to the total range. The key parameter is the body-to-range ratio threshold. A ratio below 10% means the body is less than 10% of the high-low range. Doji candles on BTC at round-number levels ($60,000, $70,000) often precede significant directional moves because they represent a moment of equilibrium before one side wins.

pine-Doji candle detection with subtypes
1//@version=5
2indicator("Doji Detection", overlay=true)
3
4dojiThresh = input.float(10.0, "Doji Body/Range %", minval=1, maxval=30, step=1)
5
6body = math.abs(close - open)
7range_ = high - low
8ratio = range_ > 0 ? body / range_ * 100 : 100
9
10isDoji = ratio <= dojiThresh and range_ > 0
11
12// Doji subtypes based on wick proportions
13upperWick = high - math.max(close, open)
14lowerWick = math.min(close, open) - low
15
16// Gravestone doji: long upper wick, tiny lower wick (bearish)
17gravestone = isDoji and upperWick > range_ * 0.6 and lowerWick < range_ * 0.15
18
19// Dragonfly doji: long lower wick, tiny upper wick (bullish)
20dragonfly = isDoji and lowerWick > range_ * 0.6 and upperWick < range_ * 0.15
21
22// Standard doji: balanced wicks
23standard = isDoji and not gravestone and not dragonfly
24
25plotshape(standard, "Doji", shape.cross,
26 location.abovebar, color.yellow, size=size.tiny)
27plotshape(gravestone, "Gravestone", shape.triangledown,
28 location.abovebar, color.red, size=size.tiny, text="GS")
29plotshape(dragonfly, "Dragonfly", shape.triangleup,
30 location.belowbar, color.green, size=size.tiny, text="DF")
Standard DojiEqual-length upper and lower wicks. Signals pure indecision. Context determines direction.
Gravestone DojiLong upper wick, almost no lower wick. Buyers pushed up but were rejected. Bearish at tops.
Dragonfly DojiLong lower wick, almost no upper wick. Sellers pushed down but were rejected. Bullish at bottoms.
Body/Range RatioThe threshold that defines a doji. 10% is standard. Lower values are stricter and produce fewer signals.

Hammer and Shooting Star Detection

A hammer is a single-bar reversal pattern at the bottom of a downtrend: a small body at the top of the range with a long lower wick (at least 2x the body length) and little to no upper wick. It shows that sellers pushed price down but buyers absorbed the selling and drove price back up. A shooting star is the mirror: a small body at the bottom of the range with a long upper wick, signaling rejection at higher prices.

pine-Hammer and shooting star with trend context
1//@version=5
2indicator("Hammer / Shooting Star", overlay=true)
3
4wickRatio = input.float(2.0, "Min Wick/Body Ratio", step=0.5)
5trendLen = input.int(10, "Trend Lookback", minval=5)
6maxBodyPct = input.float(33.0, "Max Body % of Range", step=5)
7
8body = math.abs(close - open)
9range_ = high - low
10upperWick = high - math.max(close, open)
11lowerWick = math.min(close, open) - low
12bodyPct = range_ > 0 ? body / range_ * 100 : 100
13
14// Trend context using simple slope
15inDowntrend = close < ta.sma(close, trendLen) and
16 ta.sma(close, trendLen) < ta.sma(close, trendLen)[trendLen / 2]
17inUptrend = close > ta.sma(close, trendLen) and
18 ta.sma(close, trendLen) > ta.sma(close, trendLen)[trendLen / 2]
19
20// Hammer: small body at top, long lower wick, in a downtrend
21isHammer = bodyPct <= maxBodyPct and
22 body > 0 and
23 lowerWick >= body * wickRatio and
24 upperWick <= body * 0.5 and
25 inDowntrend
26
27// Shooting star: small body at bottom, long upper wick, in an uptrend
28isShootingStar = bodyPct <= maxBodyPct and
29 body > 0 and
30 upperWick >= body * wickRatio and
31 lowerWick <= body * 0.5 and
32 inUptrend
33
34plotshape(isHammer, "Hammer", shape.labelup,
35 location.belowbar, color.new(color.green, 10),
36 text="H", textcolor=color.white, size=size.small)
37plotshape(isShootingStar, "Shooting Star", shape.labeldown,
38 location.abovebar, color.new(color.red, 10),
39 text="SS", textcolor=color.white, size=size.small)
40
41alertcondition(isHammer, "Hammer Detected",
42 "Hammer candle in downtrend context")
43alertcondition(isShootingStar, "Shooting Star Detected",
44 "Shooting star candle in uptrend context")

Trend context is mandatory

A hammer in an uptrend is meaningless. It is just a random wick. Hammers only signal reversals when they appear after a decline. The same applies to shooting stars: they must appear after a rally. Always include a trend filter. The inDowntrend / inUptrend variables above use SMA slope as a simple trend proxy, but you can replace this with any trend definition.

Gap Detection: Gap Up, Gap Down, Gap Fill

True gaps are rare in 24/7 crypto markets, but they do appear on CME Bitcoin futures (which close on weekends) and on lower timeframes during extreme volatility. A gap up occurs when the current bar's low is above the previous bar's high. A gap fill occurs when price later trades back into the gap zone. Unfilled gaps act as magnets: the market tends to revisit them, making gap fill detection a high-probability trading setup on BTC futures.

pine-Gap detection and gap fill tracking
1//@version=5
2indicator("Gap Detector", overlay=true, max_boxes_count=50)
3
4minGapPct = input.float(0.5, "Min Gap Size (%)", step=0.1)
5showFills = input.bool(true, "Highlight Gap Fills")
6
7// Gap up: current low > previous high
8gapUpSize = low - high[1]
9gapUpPct = gapUpSize / high[1] * 100
10isGapUp = gapUpPct >= minGapPct
11
12// Gap down: current high < previous low
13gapDownSize = low[1] - high
14gapDownPct = gapDownSize / low[1] * 100
15isGapDown = gapDownPct >= minGapPct
16
17// Track unfilled gaps
18var float gapUpTop = na
19var float gapUpBottom = na
20var bool gapUpActive = false
21var float gapDnTop = na
22var float gapDnBottom = na
23var bool gapDnActive = false
24
25if isGapUp
26 gapUpTop := low
27 gapUpBottom := high[1]
28 gapUpActive := true
29
30if isGapDown
31 gapDnTop := low[1]
32 gapDnBottom := high
33 gapDnActive := true
34
35// Gap fill detection
36gapUpFilled = gapUpActive and low <= gapUpBottom
37gapDnFilled = gapDnActive and high >= gapDnTop
38
39if gapUpFilled
40 gapUpActive := false
41if gapDnFilled
42 gapDnActive := false
43
44// Visual markers
45plotshape(isGapUp, "Gap Up", shape.arrowup,
46 location.belowbar, color.green, size=size.tiny)
47plotshape(isGapDown, "Gap Down", shape.arrowdown,
48 location.abovebar, color.red, size=size.tiny)
49
50bgcolor(showFills and gapUpFilled ? color.new(color.green, 88) :
51 showFills and gapDnFilled ? color.new(color.red, 88) : na)

Piercing Line and Dark Cloud Cover

The piercing line is a bullish two-bar reversal: a bearish bar followed by a bullish bar that opens below the prior low and closes above the midpoint of the prior bar's body. The dark cloud cover is the bearish mirror: a bullish bar followed by a bearish bar that opens above the prior high and closes below the midpoint of the prior body. The penetration threshold (how far into the prior body the close must reach) is a configurable parameter that controls signal quality.

pine-Piercing line and dark cloud cover
1//@version=5
2indicator("Piercing / Dark Cloud", overlay=true)
3
4penetration = input.float(50.0, "Min Penetration %", minval=30, maxval=90, step=5)
5
6prevBody = math.abs(close[1] - open[1])
7prevMid = math.min(close[1], open[1]) + prevBody * (penetration / 100)
8prevMidBear = math.max(close[1], open[1]) - prevBody * (penetration / 100)
9
10// Piercing line: bearish prev bar, bullish current bar
11// Opens below prev low, closes above penetration threshold into prev body
12piercingLine = close[1] < open[1] and
13 close > open and
14 open <= low[1] and
15 close >= prevMid and
16 close < open[1]
17
18// Dark cloud cover: bullish prev bar, bearish current bar
19// Opens above prev high, closes below penetration threshold into prev body
20darkCloud = close[1] > open[1] and
21 close < open and
22 open >= high[1] and
23 close <= prevMidBear and
24 close > open[1]
25
26plotshape(piercingLine, "Piercing Line", shape.labelup,
27 location.belowbar, color.new(color.teal, 10),
28 text="PL", textcolor=color.white, size=size.small)
29plotshape(darkCloud, "Dark Cloud", shape.labeldown,
30 location.abovebar, color.new(color.purple, 10),
31 text="DC", textcolor=color.white, size=size.small)
Penetration threshold

Higher % = stricter filter (fewer but higher-quality signals). 50% is the classic definition.

Open requirement

Piercing line must open below the previous low; dark cloud must open above the previous high.

Close constraint

The close must not exceed the previous open, otherwise it becomes an engulfing pattern instead.

Crypto context

These patterns work best on 4H+ timeframes on BTC and ETH. Lower timeframes produce too much noise.

Complete Advanced Pattern Detector

This indicator combines all advanced patterns (doji subtypes, hammer/shooting star, gaps, piercing line, and dark cloud cover) into a single production-ready script with per-pattern toggles.

pine-Advanced candle pattern detector: full script
1//@version=5
2indicator("Advanced Candle Patterns", overlay=true, max_labels_count=200)
3
4// Inputs per pattern group
5grpDoji = "Doji Settings"
6dojiOn = input.bool(true, "Show Doji", group=grpDoji)
7dojiThr = input.float(10, "Body/Range %", group=grpDoji, step=1)
8
9grpHam = "Hammer / Shooting Star"
10hamOn = input.bool(true, "Show Hammer/SS", group=grpHam)
11wkRatio = input.float(2.0, "Wick/Body Ratio", group=grpHam, step=0.5)
12trdLen = input.int(10, "Trend Lookback", group=grpHam)
13
14grpGap = "Gap Detection"
15gapOn = input.bool(true, "Show Gaps", group=grpGap)
16minGap = input.float(0.5, "Min Gap %", group=grpGap, step=0.1)
17
18grpPC = "Piercing / Dark Cloud"
19pcOn = input.bool(true, "Show Piercing/DC", group=grpPC)
20penThr = input.float(50, "Penetration %", group=grpPC, step=5)
21
22// Shared calculations
23body = math.abs(close - open)
24range_ = high - low
25bodyHigh = math.max(close, open)
26bodyLow = math.min(close, open)
27upperWick = high - bodyHigh
28lowerWick = bodyLow - low
29bodyPct = range_ > 0 ? body / range_ * 100 : 100
30
31// Trend context
32smaVal = ta.sma(close, trdLen)
33upTrend = close > smaVal and smaVal > smaVal[trdLen / 2]
34dnTrend = close < smaVal and smaVal < smaVal[trdLen / 2]
35
36// Doji
37isDoji = dojiOn and bodyPct <= dojiThr and range_ > 0
38gravestone = isDoji and upperWick > range_ * 0.6 and lowerWick < range_ * 0.15
39dragonfly = isDoji and lowerWick > range_ * 0.6 and upperWick < range_ * 0.15
40stdDoji = isDoji and not gravestone and not dragonfly
41
42// Hammer / Shooting Star
43ham = hamOn and bodyPct <= 33 and body > 0 and
44 lowerWick >= body * wkRatio and upperWick <= body * 0.5 and dnTrend
45ss = hamOn and bodyPct <= 33 and body > 0 and
46 upperWick >= body * wkRatio and lowerWick <= body * 0.5 and upTrend
47
48// Gaps
49gapUp = gapOn and (low - high[1]) / high[1] * 100 >= minGap
50gapDown = gapOn and (low[1] - high) / low[1] * 100 >= minGap
51
52// Piercing / Dark Cloud
53prevBody_ = math.abs(close[1] - open[1])
54pMid = math.min(close[1], open[1]) + prevBody_ * (penThr / 100)
55dMid = math.max(close[1], open[1]) - prevBody_ * (penThr / 100)
56pier = pcOn and close[1] < open[1] and close > open and
57 open <= low[1] and close >= pMid and close < open[1]
58dark = pcOn and close[1] > open[1] and close < open and
59 open >= high[1] and close <= dMid and close > open[1]
60
61// Plot all patterns
62plotshape(stdDoji, "Doji", shape.cross, location.abovebar,
63 color.yellow, size=size.tiny)
64plotshape(gravestone, "Gravestone", shape.xcross, location.abovebar,
65 color.red, size=size.tiny)
66plotshape(dragonfly, "Dragonfly", shape.xcross, location.belowbar,
67 color.green, size=size.tiny)
68plotshape(ham, "Hammer", shape.labelup, location.belowbar,
69 color.new(color.green, 10), text="H", textcolor=color.white, size=size.small)
70plotshape(ss, "Shooting Star", shape.labeldown, location.abovebar,
71 color.new(color.red, 10), text="SS", textcolor=color.white, size=size.small)
72plotshape(gapUp, "Gap Up", shape.arrowup, location.belowbar,
73 color.teal, size=size.tiny)
74plotshape(gapDown, "Gap Down", shape.arrowdown, location.abovebar,
75 color.orange, size=size.tiny)
76plotshape(pier, "Piercing", shape.labelup, location.belowbar,
77 color.new(color.teal, 10), text="PL", textcolor=color.white, size=size.small)
78plotshape(dark, "Dark Cloud", shape.labeldown, location.abovebar,
79 color.new(color.purple, 10), text="DC", textcolor=color.white, size=size.small)

Parameter tuning for crypto

Crypto markets have wider wicks and more volatile candles than equities. Increase the doji threshold to 12–15% for BTC on lower timeframes. For hammers, a wick/body ratio of 2.5 or 3.0 filters out weak signals. On ETH's daily chart, a piercing line with 60% penetration is a particularly strong reversal signal at support levels.

Put this lesson to work

Free on Thrive, no account needed.