Skip to main content

Building a Candlestick Scanner

Complete project: build a multi-pattern candlestick scanner with configurable filters, table dashboard, and alert system from scratch.

From Thrive on YouTube

Watch the matching Thrive video

Watch the series
Daily and Weekly Loss Limits: Building Circuit Breakers Into Your Trading

Daily and Weekly Loss Limits: Building Circuit Breakers Into Your Trading

Part of Trading Journal and Performance Review. Education only. Not financial advice.

Building a Multi-Pattern Candlestick Scanner

In this lesson you will build a production-ready candlestick scanner from scratch. The scanner detects six patterns simultaneously, applies configurable filters, displays results in a table dashboard, generates alerts for each pattern type, and uses color-coded chart markers. By the end, you will have a TradingView indicator you can immediately deploy on your BTC, ETH, and SOL charts.

We will build this step by step. Each step adds a layer of functionality to the previous one, so follow along in order.

6 pattern types

Engulfing, hammer, shooting star, doji, piercing line, dark cloud cover

Volume filter

Configurable volume threshold relative to average

Trend filter

EMA-based trend direction with slope confirmation

ATR size filter

Minimum candle range relative to recent volatility

Table dashboard

Real-time status board showing all patterns and filter states

Per-pattern alerts

Individual alert conditions for each filtered pattern

Per-pattern toggles

Enable or disable each pattern independently from settings

Color-coded markers

Unique colors and shapes for each pattern type on the chart

1

Script declaration and inputs

Start with the indicator declaration and all user-configurable inputs. Group inputs by category for a clean settings panel. The max_labels_count and max_lines_count parameters prevent hitting TradingView's drawing object limits.
2

Core calculations

Calculate all shared values: body size, wick lengths, ATR, volume average, trend direction, RSI. These are used by every pattern detector, so computing them once and reusing avoids redundant calculations and keeps the script within execution time limits.
3

Pattern detection functions

Define each of the six pattern detectors. Each one returns a boolean indicating whether the pattern fired on the current bar. Keep the logic clean and separated. One variable per pattern.
4

Filter application

Apply volume, trend, and ATR filters to each pattern. Bullish patterns require bullish trend context; bearish patterns require bearish context. Each filter can be toggled independently.
5

Chart markers

Use plotshape() with distinct shapes and colors for each pattern. Bullish patterns use up-arrows below bars; bearish patterns use down-arrows above bars. Different colors distinguish pattern types.
6

Dashboard table

Build a table in the top-right corner showing every pattern's status on the current bar: whether it fired, its direction, and which filters it passed. Update only on the last bar for performance.
7

Alert conditions

Define alertcondition() for each pattern type and an aggregate "any pattern" alert. Use the alert() function for dynamic messages that include the pattern name and current price.

Complete Scanner Code

Below is the full production-ready scanner. Copy it into the Pine Editor, add it to any crypto chart, and you will immediately see pattern markers and the dashboard table.

pine-Multi-Pattern Candlestick Scanner: Complete Script
1//@version=5
2indicator("Candle Pattern Scanner", overlay=true,
3 max_labels_count=500, max_lines_count=100)
4
5// ─── INPUTS ──────────────────────────────────────────────
6grpPat = "Pattern Toggles"
7enEngulf = input.bool(true, "Engulfing", group=grpPat)
8enHammer = input.bool(true, "Hammer", group=grpPat)
9enSS = input.bool(true, "Shooting Star", group=grpPat)
10enDoji = input.bool(true, "Doji", group=grpPat)
11enPierce = input.bool(true, "Piercing Line", group=grpPat)
12enDark = input.bool(true, "Dark Cloud Cover", group=grpPat)
13
14grpFilt = "Filters"
15useVol = input.bool(true, "Volume Filter", group=grpFilt)
16useTrend = input.bool(true, "Trend Filter", group=grpFilt)
17useAtr = input.bool(true, "ATR Size Filter", group=grpFilt)
18volLen = input.int(20, "Volume SMA Length", group=grpFilt)
19volMult = input.float(1.0, "Volume Multiplier", group=grpFilt, step=0.1)
20trendLen = input.int(50, "Trend EMA Length", group=grpFilt)
21atrLen = input.int(14, "ATR Length", group=grpFilt)
22atrMult = input.float(0.5, "Min Range (ATR mult)", group=grpFilt, step=0.1)
23
24grpAdv = "Advanced"
25dojiThr = input.float(10, "Doji Body/Range %", group=grpAdv, step=1)
26wickRat = input.float(2.0, "Hammer Wick Ratio", group=grpAdv, step=0.5)
27penThr = input.float(50, "Piercing Penetration %", group=grpAdv, step=5)
28showTable = input.bool(true, "Show Dashboard", group=grpAdv)
29
30// ─── CORE CALCULATIONS ──────────────────────────────────
31body = math.abs(close - open)
32range_ = high - low
33bodyHigh = math.max(close, open)
34bodyLow = math.min(close, open)
35upperWick = high - bodyHigh
36lowerWick = bodyLow - low
37bodyPct = range_ > 0 ? body / range_ * 100 : 100
38
39pBody = math.abs(close[1] - open[1])
40pBodyHigh = math.max(close[1], open[1])
41pBodyLow = math.min(close[1], open[1])
42
43avgVol = ta.sma(volume, volLen)
44atr = ta.atr(atrLen)
45ema = ta.ema(close, trendLen)
46slope = ema - ema[5]
47bullTrend = slope > 0 and close > ema
48bearTrend = slope < 0 and close < ema
49
50// ─── FILTER FLAGS ────────────────────────────────────────
51volOk = not useVol or volume >= avgVol * volMult
52atrOk = not useAtr or range_ >= atr * atrMult
53tBullOk = not useTrend or bullTrend
54tBearOk = not useTrend or bearTrend
55
56// ─── PATTERN DETECTION ──────────────────────────────────
57// 1. Engulfing
58engulfBase = bodyLow <= pBodyLow and bodyHigh >= pBodyHigh and body > pBody
59rawBullEng = enEngulf and close[1] < open[1] and close > open and engulfBase
60rawBearEng = enEngulf and close[1] > open[1] and close < open and engulfBase
61
62// 2. Hammer
63rawHammer = enHammer and bodyPct <= 33 and body > 0 and
64 lowerWick >= body * wickRat and upperWick <= body * 0.5
65
66// 3. Shooting Star
67rawSS = enSS and bodyPct <= 33 and body > 0 and
68 upperWick >= body * wickRat and lowerWick <= body * 0.5
69
70// 4. Doji
71rawDoji = enDoji and range_ > 0 and bodyPct <= dojiThr
72
73// 5. Piercing Line
74pMid = pBodyLow + pBody * (penThr / 100)
75rawPierce = enPierce and close[1] < open[1] and close > open and
76 open <= low[1] and close >= pMid and close < open[1]
77
78// 6. Dark Cloud Cover
79dMid = pBodyHigh - pBody * (penThr / 100)
80rawDark = enDark and close[1] > open[1] and close < open and
81 open >= high[1] and close <= dMid and close > open[1]
82
83// ─── APPLY FILTERS ──────────────────────────────────────
84fBullEng = rawBullEng and volOk and tBullOk and atrOk
85fBearEng = rawBearEng and volOk and tBearOk and atrOk
86fHammer = rawHammer and volOk and tBullOk and atrOk
87fSS = rawSS and volOk and tBearOk and atrOk
88fDojiBull = rawDoji and volOk and bullTrend
89fDojiBear = rawDoji and volOk and bearTrend
90fPierce = rawPierce and volOk and tBullOk and atrOk
91fDark = rawDark and volOk and tBearOk and atrOk
92
93anyBull = fBullEng or fHammer or fDojiBull or fPierce
94anyBear = fBearEng or fSS or fDojiBear or fDark
95
96// ─── CHART MARKERS ──────────────────────────────────────
97plotshape(fBullEng, "Bull Engulf", shape.labelup,
98 location.belowbar, color.new(#00e676, 0),
99 text="ENG", textcolor=color.white, size=size.small)
100plotshape(fBearEng, "Bear Engulf", shape.labeldown,
101 location.abovebar, color.new(#ff1744, 0),
102 text="ENG", textcolor=color.white, size=size.small)
103plotshape(fHammer, "Hammer", shape.labelup,
104 location.belowbar, color.new(#00bcd4, 0),
105 text="HAM", textcolor=color.white, size=size.small)
106plotshape(fSS, "Shooting Star", shape.labeldown,
107 location.abovebar, color.new(#ff9800, 0),
108 text="SS", textcolor=color.white, size=size.small)
109plotshape(fDojiBull, "Doji Bull", shape.diamond,
110 location.belowbar, color.new(#ffeb3b, 0), size=size.tiny)
111plotshape(fDojiBear, "Doji Bear", shape.diamond,
112 location.abovebar, color.new(#ffeb3b, 0), size=size.tiny)
113plotshape(fPierce, "Piercing", shape.labelup,
114 location.belowbar, color.new(#7c4dff, 0),
115 text="PL", textcolor=color.white, size=size.small)
116plotshape(fDark, "Dark Cloud", shape.labeldown,
117 location.abovebar, color.new(#e040fb, 0),
118 text="DC", textcolor=color.white, size=size.small)
119
120// Trend EMA overlay
121plot(ema, "Trend EMA", bullTrend ? color.new(color.green, 40) :
122 bearTrend ? color.new(color.red, 40) : color.new(color.gray, 60), 1)
123
124// ─── DASHBOARD TABLE ────────────────────────────────────
125if showTable and barstate.islast
126 t = table.new(position.top_right, 4, 8,
127 bgcolor=color.new(#0d0b14, 10),
128 border_width=1,
129 border_color=color.new(color.gray, 70))
130
131 hdr(col, txt) =>
132 table.cell(t, col, 0, txt, text_color=color.gray,
133 text_size=size.small, text_halign=text.align_center)
134 hdr(0, "Pattern")
135 hdr(1, "Signal")
136 hdr(2, "Direction")
137 hdr(3, "Filters")
138
139 row(r, name, fired, isBull, filtersOk) =>
140 table.cell(t, 0, r, name, text_color=color.white,
141 text_size=size.small)
142 table.cell(t, 1, r, fired ? "ACTIVE" : "-",
143 text_color=fired ? color.yellow : color.gray,
144 text_size=size.small, text_halign=text.align_center)
145 table.cell(t, 2, r, fired ? (isBull ? "▲ BULL" : "▼ BEAR") : "-",
146 text_color=fired ? (isBull ? color.green : color.red) : color.gray,
147 text_size=size.small, text_halign=text.align_center)
148 fStr = (volOk ? "V" : "-") + " " + (atrOk ? "A" : "-") + " " +
149 (isBull ? (tBullOk ? "T" : "-") : (tBearOk ? "T" : "-"))
150 table.cell(t, 3, r, filtersOk ? fStr : "-",
151 text_color=filtersOk ? color.teal : color.gray,
152 text_size=size.small, text_halign=text.align_center)
153
154 row(1, "Engulfing", rawBullEng or rawBearEng, rawBullEng, fBullEng or fBearEng)
155 row(2, "Hammer", rawHammer, true, fHammer)
156 row(3, "Shooting Star", rawSS, false, fSS)
157 row(4, "Doji", rawDoji, bullTrend, fDojiBull or fDojiBear)
158 row(5, "Piercing Line", rawPierce, true, fPierce)
159 row(6, "Dark Cloud", rawDark, false, fDark)
160
161 // Summary row
162 total = (fBullEng ? 1 : 0) + (fBearEng ? 1 : 0) + (fHammer ? 1 : 0) +
163 (fSS ? 1 : 0) + (fDojiBull or fDojiBear ? 1 : 0) +
164 (fPierce ? 1 : 0) + (fDark ? 1 : 0)
165 table.cell(t, 0, 7, "Total Active", text_color=color.white,
166 text_size=size.small)
167 table.cell(t, 1, 7, str.tostring(total), text_color=color.yellow,
168 text_size=size.small, text_halign=text.align_center)
169 table.cell(t, 2, 7, anyBull and anyBear ? "MIXED" :
170 anyBull ? "BULLISH" : anyBear ? "BEARISH" : "NONE",
171 text_color=anyBull and not anyBear ? color.green :
172 anyBear and not anyBull ? color.red : color.gray,
173 text_size=size.small, text_halign=text.align_center)
174 table.cell(t, 3, 7, "", text_size=size.small)
175
176// ─── ALERTS ─────────────────────────────────────────────
177alertcondition(fBullEng, "Bull Engulfing (Filtered)",
178 "Filtered bullish engulfing candle")
179alertcondition(fBearEng, "Bear Engulfing (Filtered)",
180 "Filtered bearish engulfing candle")
181alertcondition(fHammer, "Hammer (Filtered)",
182 "Filtered hammer candle")
183alertcondition(fSS, "Shooting Star (Filtered)",
184 "Filtered shooting star candle")
185alertcondition(fDojiBull or fDojiBear, "Doji (Filtered)",
186 "Filtered doji candle")
187alertcondition(fPierce, "Piercing Line (Filtered)",
188 "Filtered piercing line pattern")
189alertcondition(fDark, "Dark Cloud (Filtered)",
190 "Filtered dark cloud cover pattern")
191alertcondition(anyBull or anyBear, "Any Pattern (Filtered)",
192 "Any filtered candle pattern detected")
193
194// Dynamic alert with pattern name
195if anyBull or anyBear
196 patName = fBullEng ? "Bull Engulfing" :
197 fBearEng ? "Bear Engulfing" :
198 fHammer ? "Hammer" :
199 fSS ? "Shooting Star" :
200 fPierce ? "Piercing Line" :
201 fDark ? "Dark Cloud" :
202 "Doji"
203 dir = anyBull ? "BULLISH" : "BEARISH"
204 alert(syminfo.ticker + " | " + patName + " (" + dir + ") | $" +
205 str.tostring(close, "#.##"),
206 alert.freq_once_per_bar_close)

How the Scanner Works: Section Breakdown

Pattern TogglesSix boolean inputs let users enable or disable each pattern independently from the settings panel.
Filter FlagsvolOk, atrOk, tBullOk, tBearOk: computed once and reused by every pattern. Each flag is true when the filter is disabled OR the condition passes.
Raw vs FilteredrawBullEng is the unfiltered pattern. fBullEng is rawBullEng AND all filters passed. The table shows both states so you can see what the filters removed.
Dashboard ColumnsPattern name, whether the raw signal fired, the direction, and which filters passed (V=Volume, A=ATR, T=Trend).
Dynamic alert()The alert() function constructs a message string with the pattern name, direction, and price. This fires once per bar close for the first active pattern.
alertcondition()One per pattern type plus an aggregate "Any Pattern" condition. Users select which alert to subscribe to when setting up the alert in TradingView.

Customization Guide

The scanner is designed to be extended. Here are the most common modifications you can make to tailor it to your trading style.

1

Add new patterns

To add a seventh pattern (e.g., morning star), define a new rawMorningStar boolean with the detection logic, create a fMorningStar filtered version, add a plotshape, a table row, and an alertcondition. Follow the same structure as the existing patterns.
2

Add RSI zone filter

Add rsi = ta.rsi(close, 14) to core calculations. Create rsiBullOk = rsi < 45 and rsiBearOk = rsi > 55. Add these to the filter chain for each pattern.
3

Multi-timeframe confirmation

Use request.security() to check if the same pattern fired on a higher timeframe. A bullish engulfing on both the 1H and 4H charts simultaneously is exceptionally strong. Add a "MTF Confirmed" column to the dashboard table.
4

Historical accuracy tracking

Use var arrays to store signal outcomes. When a pattern fires, record the price. After N bars, check if price moved in the expected direction. Display a rolling win rate in the dashboard. This turns the scanner into a backtesting tool.
5

Webhook integration

TradingView alerts can send webhooks to external services. Configure the alert message as JSON: {"pattern":"Bull Engulfing","price":42000}. Route webhooks to a Telegram bot, Discord channel, or automated trading system.

Deploying the Scanner

1

Copy into Pine Editor

Open TradingView, click the Pine Editor tab at the bottom, create a new script, and paste the entire scanner code. Click "Save" and give it a name like "Candle Scanner v1."
2

Add to chart

Click "Add to chart." The indicator should immediately render on your BTC/USDT chart with pattern markers and the dashboard table in the top-right corner.
3

Configure settings

Click the indicator's gear icon to open settings. Enable/disable patterns you care about. Adjust filter parameters: start with Volume Multiplier at 1.0, ATR Mult at 0.5, and Trend EMA at 50. Tighten these if you get too many signals.
4

Set up alerts

Right-click the indicator name on the chart and select "Add alert." Choose the condition (e.g., "Any Pattern (Filtered)"), set the expiration, and choose your notification method (push, email, or webhook).
5

Apply to multiple charts

Add the scanner to your ETH, SOL, and other watchlist assets. Each instance runs independently with its own settings. Use TradingView's layout feature to monitor multiple charts with the scanner running on each one.

Recommended starting configuration

For BTC on the daily chart: enable all patterns, Volume Multiplier 1.2, ATR Mult 0.5, Trend EMA 50. For ETH on the 4H chart: same settings but Volume Multiplier 1.0 (ETH volume is more consistent). For SOL on the 1H chart: increase ATR Mult to 0.7 and Volume Multiplier to 1.5 to filter out the higher noise on shorter timeframes.

No indicator replaces judgment

The scanner surfaces high-probability candle patterns. It does not tell you to trade. Always cross-reference scanner signals with support/resistance levels, market structure, and your overall thesis. A filtered bullish engulfing at a weekly support level on BTC is a strong signal. The same pattern in the middle of nowhere is just a candle.
Module Quiz

1.In PineScript, how would you detect a bullish engulfing pattern?

2.What does 'request.security()' allow you to do in a PineScript candlestick scanner?

3.Why is a volume filter important when detecting candlestick patterns in PineScript?

4.What is the purpose of 'alertcondition()' in a candle pattern scanner?

5.How does a trend filter using EMA improve a candlestick pattern scanner?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.