Strategy · Pine Script v6 · On the chart

Sweep and Engulf Strategy

by rosijay17-cmd

A strategy that looks for a one-bar sweep and engulf pattern: a bar that takes out the previous low and closes above the previous high is bullish, and the mirror case is bearish.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code121
Settings8inputs
LicenceGPL-3.0
Last update7 days ago22 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

121 lines of Pine Script v6 from Sweep_and_Engulf_Strategy.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Sweep_and_Engulf_Strategy.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ MPL-2.0
//@version=6
strategy("Sweep and Engulf Strategy", overlay = true, initial_capital = 1000000, default_qty_type = strategy.fixed, default_qty_value = 1, max_boxes_count = 500)

// --- Inputs ---
// Filters
bool   invertTrades     = input.bool(true, title = "Invert Strategy (Trade Opposite)", tooltip = "If enabled, takes a Short on a bullish pattern and a Long on a bearish pattern.", group = "Signal Filters")
string prevCandleFilter = input.string("Any", title = "Previous Candle Direction", options = ["Any", "Same Direction"], tooltip = "If 'Same Direction' is selected, a bullish sweep requires the previous candle to be bullish, and a bearish sweep requires the previous candle to be bearish.", group = "Signal Filters")

// EMA Settings
bool   useEma           = input.bool(false, title = "Use & Show EMA Trend Filter", tooltip = "If enabled, displays the EMA and filters signals: bullish only appear when price is above the EMA, and bearish only appear when price is below.", group = "EMA Trend Filter")
int    emaLength        = input.int(200, title = "EMA Length", minval = 1, group = "EMA Trend Filter")

// Risk Management
string slType           = input.string("ATR", title = "Stop Loss Method", options = ["ATR", "Candle High/Low"], tooltip = "Choose how the Stop Loss is calculated. 'Candle High/Low' places the stop at the extreme of the signal candle.", group = "Risk Management")
int    atrLength        = input.int(14, title = "ATR Length", group = "Risk Management")
float  slMult           = input.float(1.5, title = "ATR Multiplier", step = 0.1, group = "Risk Management")
float  rrRatio          = input.float(2.0, title = "Risk/Reward Ratio", step = 0.1, group = "Risk Management")

// --- State Variables ---
var bool  inTrade    = false
var int   tradeDir   = 0
var float entryPrice = na
var float slPrice    = na
var float tpPrice    = na
var int   entryBar   = na
var box   boxTp      = na
var box   boxSl      = na

// --- Logic ---
// EMA Calculation
float emaValue = ta.ema(close, emaLength)
bool  isUptrend = close > emaValue
bool  isDowntrend = close < emaValue

// Determine previous candle direction
bool prevBullish = close[1] > open[1]
bool prevBearish = close[1] < open[1]

// Check if the previous candle matches our filter requirements
bool reqBullish = prevCandleFilter == "Any" or prevBullish
bool reqBearish = prevCandleFilter == "Any" or prevBearish

// Trend filter conditions
bool trendBullish = not useEma or isUptrend
bool trendBearish = not useEma or isDowntrend

// ATR Calculation
float atr = ta.atr(atrLength)

// Trade Management (Exit Logic)
if inTrade and bar_index > entryBar
    bool hitTP = (tradeDir == 1 and high >= tpPrice) or (tradeDir == -1 and low <= tpPrice)
    bool hitSL = (tradeDir == 1 and low <= slPrice) or (tradeDir == -1 and high >= slPrice)

    if hitTP or hitSL
        // Close the trade and lock box to current bar
        inTrade  := false
        tradeDir := 0
        boxTp.set_right(bar_index)
        boxSl.set_right(bar_index)
    else
        // Keep pushing the boxes forward while in trade
        boxTp.set_right(bar_index + 5)
        boxSl.set_right(bar_index + 5)

// Sweep & Engulf Conditions
bool bullishSweep = low < low[1] and close > high[1] and reqBullish and trendBullish and not na(atr)
bool bearishSweep = high > high[1] and close < low[1] and reqBearish and trendBearish and not na(atr)

// Apply inversion if enabled
bool rawLong  = invertTrades ? bearishSweep : bullishSweep
bool rawShort = invertTrades ? bullishSweep : bearishSweep

// Filter signals based on current trade state
bool longSignal  = rawLong and not inTrade
bool shortSignal = rawShort and not inTrade

// Trade Entry Logic
if longSignal
    inTrade    := true
    tradeDir   := 1
    entryBar   := bar_index
    entryPrice := close
    slPrice    := slType == "Candle High/Low" ? low : entryPrice - (atr * slMult)
    float risk = entryPrice - slPrice
    tpPrice    := entryPrice + (risk * rrRatio)

    // Execute Strategy Orders
    strategy.entry("Long", strategy.long)
    strategy.exit("Exit Long", from_entry = "Long", limit = tpPrice, stop = slPrice)

    // Draw TP/SL boxes
    boxTp := box.new(left = bar_index, top = tpPrice, right = bar_index + 5, bottom = entryPrice, border_color = na, bgcolor = color.new(#089981, 75))
    boxSl := box.new(left = bar_index, top = entryPrice, right = bar_index + 5, bottom = slPrice, border_color = na, bgcolor = color.new(#f23645, 75))

if shortSignal
    inTrade    := true
    tradeDir   := -1
    entryBar   := bar_index
    entryPrice := close
    slPrice    := slType == "Candle High/Low" ? high : entryPrice + (atr * slMult)
    float risk = slPrice - entryPrice
    tpPrice    := entryPrice - (risk * rrRatio)

    // Execute Strategy Orders
    strategy.entry("Short", strategy.short)
    strategy.exit("Exit Short", from_entry = "Short", limit = tpPrice, stop = slPrice)

    // Draw TP/SL boxes
    boxTp := box.new(left = bar_index, top = entryPrice, right = bar_index + 5, bottom = tpPrice, border_color = na, bgcolor = color.new(#089981, 75))
    boxSl := box.new(left = bar_index, top = slPrice, right = bar_index + 5, bottom = entryPrice, border_color = na, bgcolor = color.new(#f23645, 75))

// --- Visuals ---
// Plot EMA
color emaColor = close > emaValue ? color.new(#089981, 0) : color.new(#f23645, 0)
plot(useEma ? emaValue : na, title = "Trend EMA", color = emaColor, linewidth = 2)

// Plot shapes above/below the triggering candle
plotshape(longSignal, title = "Long Entry", style = shape.triangleup, location = location.belowbar, color = color.new(#089981, 0), size = size.small)
plotshape(shortSignal, title = "Short Entry", style = shape.triangledown, location = location.abovebar, color = color.new(#f23645, 0), size = size.small)

Overview

By default the trades are inverted, so a bullish pattern opens a short and a bearish one a long. Optional filters require the previous candle to run the same way or price to sit on the correct side of an EMA. The stop is an ATR multiple or the signal candle extreme, and the target is a reward-to-risk multiple. Stop and target boxes draw on the chart.

Details

Published by

rosijay17-cmd on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Invert Strategy (Trade Opposite)booltrueinvertTrades
Previous Candle DirectionstringAnyprevCandleFilter
Use & Show EMA Trend FilterboolfalseuseEma
EMA Lengthint200emaLength
Stop Loss MethodstringATRslType
ATR Lengthint14atrLength
ATR Multiplierfloat1.5slMult
Risk/Reward Ratiofloat2.0rrRatio
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

1 stars

This strategy identifies trend phases using consecutive directional candle sequences, tracks the trend extreme, and monitors for order blocks confirmed by candle displacement. When price returns to test the identified order block, it enters long or short on a

Strategy v6 SMC / ICT / price actionCandlestick patterns
Updated 3 weeks ago · None stated GitHub repository of Höhlenmensch Strategie
1 stars

This Pine Script strategy detects ICT smart money concepts including order test zones, fair value gaps, and wicks on BTC and XAUUSD price charts. It calculates swings using pivot high and low. Signals enter long or short when the order test zone is hit with su

Strategy v5 SMC / ICT / price actionCandlestick patterns
Updated 6 months ago · None stated GitHub repository of ICT v4-weinkya BTC Improved

VCP probe 02 fvg zones

by pineforge-4pass
1 stars

This strategy detects Fair Value Gaps on the price chart using 3-bar candle imbalances filtered by ATR. It maintains a capped array of active FVG zones with their tops, bottoms, and bullish flags. Long entries occur when the current bar overlaps an active bull

Strategy v6 SMC / ICT / price actionCandlestick patterns
Updated 6 days ago · Apache-2.0 GitHub repository of VCP probe 02 fvg zones
330 stars

Exceeded Candle [Alorse] is a mean-reversion strategy that identifies candlestick engulfing patterns combined with Bollinger Bands filters. It enters a long position when a green candle surpasses the body of the previous red candle while price is below the mid

Strategy v4 Mean reversionCandlestick patterns
Updated 2 months ago · None stated GitHub repository of Exceeded candle [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

More Candlestick patterns scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers