Tutorial

Pine Script Engulfing Candle and Inside Bar Detection

Define engulfing and inside bars as exact arithmetic, code both in Pine Script v6 without repainting, and check each marker in replay next to chart levels.

•12 min read

Two candles can look like an engulfing pattern to your eye and still fail every version of the rule you write in code. One person counts the wicks, another counts only the bodies, a third wants the second candle to open exactly at the previous close. When you turn the pattern into a script, you have to pick one definition and stick to it, and the pick changes how many bars light up on your chart.

This guide defines the engulfing candle and the inside bar precisely, codes both in Pine Script v6 so they do not repaint, and shows how to check each marker against the chart before you rely on it. Along the way it covers the filters that stop the script from marking every tiny candle, and how to read a pattern next to the levels around it instead of alone.

What an engulfing candle and an inside bar actually describe

A candle records four prices: open, high, low, close. A pattern is a statement about how one candle relates to the one before it. An engulfing candle says the current body is larger than the previous body and covers it completely. An inside bar says the current candle's whole range, wick to wick, fits inside the previous candle's range.

Neither pattern says anything about what price will do next. They describe what happened on two bars. Traders read an engulfing candle as a sign that one side took over within a single bar, and an inside bar as a pause where the market traded in a narrower range than the bar before it. Those are readings, not rules, and the honest way to use a script is to find the bars quickly and then look at them yourself.

That framing matters for the code. If you write the definition so it is exact, you can check every marker by eye in a few seconds, because each one is a plain arithmetic fact about two candles.

The definition of an engulfing candle, written as arithmetic

There are two common definitions. The wick version says the current high is above the previous high and the current low is below the previous low. That is an outside bar, and it ignores direction entirely. The body version, which most candlestick references use, compares the open and close of each candle and ignores the wicks.

For a bullish engulfing candle, the previous candle closed lower than it opened, the current candle closed higher than it opened, the current open is at or below the previous close, and the current close is at or above the previous open. In other words, the current body covers the previous body. A bearish engulfing candle is the mirror image: a green candle followed by a red one whose body covers the green body.

Two details trip people up. The first is whether the comparison is strict. On crypto charts, where a candle often opens exactly where the last one closed, a strict inequality on the open would reject almost every real case, so the open comparison uses less-than-or-equal. The second is size. Under the plain rule, a one-tick body followed by a two-tick body counts. That is technically an engulfing candle and almost never one you want, which is why the script below also asks for a minimum body measured in ATR, the average true range.

Coding engulfing candles in Pine Script v6

The script below marks bullish and bearish engulfing candles. It requires the current body to be larger than the previous one, and at least a chosen fraction of the average true range, so the minuscule candles are filtered out. An optional trend filter keeps only bullish patterns above a moving average and bearish patterns below it.

pine
//@version=6
indicator("Engulfing Candles", overlay = true)

atrLen = input.int(14, "ATR length", minval = 1)
minBodyAtr = input.float(0.5, "Minimum body, in ATR", minval = 0.0, step = 0.1)
useTrend = input.bool(false, "Only with the trend")
trendLen = input.int(50, "Trend average length", minval = 2)

atrVal = ta.atr(atrLen)
trendAvg = ta.ema(close, trendLen)

body = math.abs(close - open)
prevBody = math.abs(close[1] - open[1])
bigEnough = body >= minBodyAtr * atrVal and body > prevBody

bullEngulf = close[1] < open[1] and close > open and open <= close[1] and close >= open[1] and bigEnough
bearEngulf = close[1] > open[1] and close < open and open >= close[1] and close <= open[1] and bigEnough

bullOk = bullEngulf and (not useTrend or close > trendAvg) and barstate.isconfirmed
bearOk = bearEngulf and (not useTrend or close < trendAvg) and barstate.isconfirmed

plotshape(bullOk, title = "Bullish engulfing", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small)
plotshape(bearOk, title = "Bearish engulfing", style = shape.triangledown, location = location.abovebar, color = color.maroon, size = size.small)
plot(useTrend ? trendAvg : na, title = "Trend average", color = color.gray)

alertcondition(bullOk, "Bullish engulfing", "Bullish engulfing candle closed")
alertcondition(bearOk, "Bearish engulfing", "Bearish engulfing candle closed")

Every line is a statement you can verify on the chart. If a triangle sits under a candle, the previous candle must be red, this one must be green, and the green body must cover the red one. If any of those is false, the script has a bug and you have found it in seconds.

The barstate.isconfirmed term deserves a sentence of its own. On the live bar, the close is just the last price, and it moves with every tick. A candle can look like an engulfing candle for ten seconds and then stop being one before it closes. Requiring a confirmed bar means the marker appears only once the candle has closed, and it stays there. The post on barstate.isconfirmed explains why that single condition is the difference between a marker that stays put and one that vanishes.

The inside bar and the mother bar

An inside bar is simpler than an engulfing candle, because it only compares ranges. The current high must be lower than the previous high, and the current low must be higher than the previous low. The bar before it is called the mother bar, and its high and low form the range that the inside bar sits within.

Traders watch the mother bar's boundaries because a close beyond them ends the pause. A close above the mother high is a break upward, a close below the mother low is a break downward. The script does not say which break is coming. It only reports which one happened, and when.

There is a subtlety worth coding for. Several inside bars can follow each other, each smaller than the one before, and all of them are still inside the same mother bar. If your script checks each bar only against the one immediately before it, it treats the second inside bar as a new mother and moves the range inward. A better version keeps the original mother range alive until a bar leaves it, which is what the next script does.

Drawing the mother range and the break

The script below tracks the mother range in var variables, draws it as a box that stretches while price stays inside, and marks the bar that closes outside it. It uses one box at a time, so it never comes near the drawing limits that the post on Pine Script drawing objects covers.

pine
//@version=6
indicator("Inside Bar Mother Range", overlay = true, max_boxes_count = 100)

var float motherHigh = na
var float motherLow = na
var box motherBox = na

insideMother = not na(motherHigh) and high < motherHigh and low > motherLow
insidePrev = high < high[1] and low > low[1]

bool brokeUp = false
bool brokeDown = false

if not na(motherHigh) and not insideMother
    brokeUp := close > motherHigh
    brokeDown := close < motherLow
    motherHigh := na
    motherLow := na
    motherBox := na

if insideMother
    box.set_right(motherBox, bar_index)
else if na(motherHigh) and insidePrev
    motherHigh := high[1]
    motherLow := low[1]
    motherBox := box.new(bar_index - 1, motherHigh, bar_index, motherLow, border_color = color.gray, bgcolor = color.new(color.gray, 85))

plotshape(brokeUp and barstate.isconfirmed, title = "Close above mother high", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small)
plotshape(brokeDown and barstate.isconfirmed, title = "Close below mother low", style = shape.triangledown, location = location.abovebar, color = color.maroon, size = size.small)

alertcondition(brokeUp and barstate.isconfirmed, "Close above mother high", "Bar closed above the inside bar mother range")
alertcondition(brokeDown and barstate.isconfirmed, "Close below mother low", "Bar closed below the inside bar mother range")

The flow is worth reading once. On each bar, the script first asks whether a mother range exists and the current bar has left it. If so, it records whether the close was above or below, then clears the range. Next, if the bar is inside an active range, it stretches the box. Otherwise, if there is no active range and this bar is inside the previous one, it starts a new range from the previous bar. A bar whose wick pokes outside the range but closes back inside still ends the range, with neither flag set, so you can tell a clean close-out from a wick.

Make the patterns less noisy

Run either script on a lower timeframe and you will see hundreds of markers. Most are tiny candles in quiet stretches, which is why the minimum body in ATR terms is an input and not a constant. A value of 0.5 means the engulfing body must be at least half the average true range, and raising it to 1.0 keeps only the larger candles. Lower values show more, higher values show fewer, and nothing about either choice is more correct. What matters is that you set it on purpose and that the number is visible in the script.

For inside bars, the same idea applies to the mother bar. A mother bar that is itself small, say under half an ATR, produces a box too thin to read. Adding motherRange >= 0.8 * atrVal before starting a new range removes those cases, and the check takes one line.

The trend filter in the engulfing script is the other common cut. Requiring the close to sit above a moving average for bullish patterns and below it for bearish ones removes the counter-trend markers. It also removes bars you might have wanted to look at, so leave it off while you are still learning what the raw pattern looks like on your market.

Read the pattern next to the levels around it

An engulfing candle in the middle of nowhere tells you little. The same candle closing right at a level where price has turned several times tells you a lot more, because you can see what it did against something. That is why most people pair candle patterns with support and resistance zones, and why a marker without a level next to it is hard to judge.

This is where the chart agent in PineScripter fits. It works on PineScripter's own chart of crypto spot markets, not on your TradingView chart, and it does the drawing so you do not have to place every line by hand.

Mark the levels on the chart with the agent

Open a chart in PineScripter, for example BTCUSDT on the 4 hour timeframe, and type the request in plain English:

Mark the swing highs and lows on BTCUSDT 4h and draw the levels they cluster into as zones.

The agent starts by reading the chart. It reads the swing levels, including how many times price has touched each one, and it reads the drawings already on the chart. Then it draws the zones with the drawing tools from the toolbar while you watch its cursor click each point, the same way you would. Every batch it draws can be undone, so if a zone is wrong, you remove it in one step.

The agent's markup is a starting point, not an answer, and you check it yourself. The touch count is the first number to look at: a zone built from two swings is a thinner claim than one built from six. Switch the timeframe, or ask the agent to do it, and see whether the same zones still look sensible on the 1 hour chart. Then run the engulfing script from this guide on the same chart and look at what the markers do near the zones. Some will sit on a zone, many will not, and that gap is the useful information. To go deeper on how the zones are built, the guide to drawing support and resistance zones from swings walks through the rule and the code.

Replay is the honest way to check a candle marker. Step through the chart one bar at a time and watch when the marker appears. With barstate.isconfirmed in place, it appears on the bar that closes as the pattern, never earlier, and you can see the pattern form without knowing the next candle in advance. If you meet a marker you do not understand, ask the AI about that bar. The post on checking a script before and after it goes live covers that workflow.

The agent does not find patterns for you, and it does not say where price will go. It marks what you ask for and describes the chart. The pattern detection stays in the script you can read.

Turn the pattern and the zone into one indicator

Once you have the zones on the chart and the markers next to them, the natural next step is to have both in one script. You can ask for it in the same plain English. Something like the following request describes the whole job:

Turn this into an indicator that marks bullish engulfing candles that close inside a swing zone and bearish ones that close inside a zone above, using confirmed bars only.

PineScripter writes Pine Script v6 against the built-in manual, checks the script for compile errors the same way TradingView does, and fixes errors on its own when it finds them. A follow-up such as "make the minimum body 0.8 ATR" changes only the affected lines, and the Code Changes view shows which lines moved. Turning chart drawings into a Pine Script indicator shows that step in detail.

If you would rather write the zone check by hand, the idea is to keep an array of recent confirmed swing highs and lows from ta.pivothigh and ta.pivotlow, and test whether the closing price of an engulfing bar falls within a band of, say, 0.25 ATR around any of them. The pivot functions arrive late by design, as the post on pivot highs and lows explains, so the zone only uses swings that were already confirmed when the candle closed.

Common mistakes when coding candle patterns

The first mistake is forgetting direction in the engulfing test. An outside bar, with a higher high and a lower low, is not an engulfing candle unless the bodies also line up, and mixing the two produces markers on bars that fail the visual test.

The second is comparing the current bar to the wrong bar after a gap in your data. On a thinly traded symbol, a missing bar makes close[1] the close from two periods ago. A symbol with session breaks can do this, and the effect is a marker that looks wrong at the open.

The third is repainting. Code that checks the pattern on the open bar and does not require a confirmed close will flicker during the live candle. It looks fine on history, where every bar is closed, and misbehaves live. The lookback bias post describes the wider family of problems.

The fourth is counting. A marker count by itself means nothing, because two rules that fire on very different numbers of bars often differ mostly in how small a body they accept. Compare the two on the same chart in the same period before drawing any conclusion about either.

Putting it together

Define each pattern as arithmetic, require a minimum body so tiny candles drop out, wait for the bar to close before marking it, and look at every marker next to the levels around it. The scripts above cover the first three, and the chart agent covers the drawing of levels so the fourth takes a minute instead of an hour.

If you want to try the whole loop, from the zones to the markers to the replay, PineScripter has the chart, the agent and the editor in one workspace, and the plans are listed on the pricing page. The patterns are a way of reading bars. They do not tell you which way the next one goes, and no filter in this guide changes that.

Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.

Back to Blog

Frequently asked questions

What is the difference between an engulfing candle and an outside bar?

An outside bar compares the full ranges: the current high is above the previous high and the current low is below the previous low. An engulfing candle compares bodies, open to close, and requires the colours to be opposite. Many engulfing candles are also outside bars, but not all, and not the other way round.

Why does my engulfing marker disappear on the live bar?

On the live bar the close is only the last price, so the candle can match the rule for a few seconds and then stop matching before it closes. Add barstate.isconfirmed to the condition so the marker appears only after the candle closes.

Can an inside bar be a doji or have the same high as the mother bar?

With the strict rule in this guide, high < high[1] and low > low[1], a bar that touches the mother high or low exactly is not an inside bar. If you want to include equal highs and lows, change the comparisons to <= and >=, and decide it on purpose.

What minimum body size should I use for the engulfing filter?

There is no correct value. 0.5 ATR removes the smallest candles, and 1.0 ATR keeps only large ones. Set it as an input, change it on the same chart, and look at how many markers disappear.

Does the chart agent find engulfing candles?

No. The agent reads the chart, including swing levels and their touch counts, draws what you ask for with the drawing tools, and can switch market and timeframe. The pattern detection lives in the Pine Script you run on the chart.

Ask the agent to mark it on the chart, then turn it into Pine Script →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.