Strategy · Pine Script v5 · On the chart

Buy&Sell Bullish Engulfing - The Quant Science

by hasnocool· code credited to thequantscience

This Pine Script strategy detects bullish engulfing candlestick patterns to generate buy and sell signals overlaid directly on the price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code100
Settings11inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

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

100 lines of Pine Script v5 from Buy&Sell Bullish Engulfing - The Quant Science.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Buy&Sell Bullish Engulfing - The Quant Science.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
// ██████╗ ██╗   ██╗██╗     ██╗     ██╗███████╗██╗  ██╗    ███████╗███╗   ██╗ ██████╗ ██╗   ██╗██╗     ███████╗██╗███╗   ██╗ ██████╗ 
// ██╔══██╗██║   ██║██║     ██║     ██║██╔════╝██║  ██║    ██╔════╝████╗  ██║██╔════╝ ██║   ██║██║     ██╔════╝██║████╗  ██║██╔════╝ 
// ██████╔╝██║   ██║██║     ██║     ██║███████╗███████║    █████╗  ██╔██╗ ██║██║  ███╗██║   ██║██║     █████╗  ██║██╔██╗ ██║██║  ███╗
// ██╔══██╗██║   ██║██║     ██║     ██║╚════██║██╔══██║    ██╔══╝  ██║╚██╗██║██║   ██║██║   ██║██║     ██╔══╝  ██║██║╚██╗██║██║   ██║
// ██████╔╝╚██████╔╝███████╗███████╗██║███████║██║  ██║    ███████╗██║ ╚████║╚██████╔╝╚██████╔╝███████╗██║     ██║██║ ╚████║╚██████╔╝
// ╚═════╝  ╚═════╝ ╚══════╝╚══════╝╚═╝╚══════╝╚═╝  ╚═╝    ╚══════╝╚═╝  ╚═══╝ ╚═════╝  ╚═════╝ ╚══════╝╚═╝     ╚═╝╚═╝  ╚═══╝ ╚═════╝ 
                                                                                                                                  
//@version=5
strategy(
     "Buy&Sell Bullish Engulfing - The Quant Science",
     overlay = true,
     default_qty_type = strategy.percent_of_equity, 
     default_qty_value = 100,
     pyramiding = 1,
     currency = currency.EUR,
     initial_capital = 10000,
     commission_type = strategy.commission.percent,
     commission_value = 0.07,
     process_orders_on_close = true, 
     close_entries_rule = "ANY"
     )
startDate  = input.int(title="D: ", defval=1,    minval=1,    maxval=31,   inline = 'Start', group = "START DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
startMonth = input.int(title="M: ", defval=1,    minval=1,    maxval=12,   inline = 'Start', group = "START DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
startYear  = input.int(title="Y: ", defval=2022, minval=1800, maxval=2100, inline = 'Start', group = "START DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
endDate    = input.int(title="D: ", defval=31,   minval=1,    maxval=31,   inline = 'End',   group = "END DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
endMonth   = input.int(title="M: ", defval=12,   minval=1,    maxval=12,   inline = 'End',   group = "END DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
endYear    = input.int(title="Y: ", defval=2023, minval=1800, maxval=2100, inline = 'End',   group = "END DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
PROFIT   = input.float(defval = 1, minval = 0, title = "Target profit (%): ", step = 0.10, group = "TAKE PROFIT-STOP LOSS")
STOPLOSS = input.float(defval = 1, minval = 0, title = "Stop Loss (%): ",     step = 0.10, group = "TAKE PROFIT-STOP LOSS")
var float equity_trades = 0
equity_trades := strategy.initial_capital
var float equity   = 0
var float qty_order   = 0
t_ordersize = "Percentage size of each new order. With 'Reinvestment Profit' activate, the size will be calculate on the equity, with 'Reinvestment Profit' deactivate the size will be calculate on the initial capital."
orders_size = input.float(defval = 2, title = "Orders size (%): ", minval = 0.10, step = 0.10,  maxval = 100, group = "RISK MANAGEMENT", tooltip = t_ordersize)
qty_order := ((equity_trades * orders_size) / 100 ) / close 
C_DownTrend = true
C_UpTrend   = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = input.string(trendRule1, "Detect Trend Based On", options=[trendRule1, trendRule2, "No detection"], group = "BULLISH ENGULFING")
if trendRule == trendRule1
    priceAvg = ta.sma(close, 50)
    C_DownTrend := close < priceAvg
    C_UpTrend := close > priceAvg
if trendRule == trendRule2
    sma200 = ta.sma(close, 200)
    sma50  = ta.sma(close, 50)
    C_DownTrend := close < sma50 and sma50 < sma200
    C_UpTrend := close > sma50 and sma50 > sma200
C_Len = 14
C_ShadowPercent = 5.0 
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 
C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high-low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
patternLabelPosLow  = low  - (ta.atr(30) * 0.6)
patternLabelPosHigh = high + (ta.atr(30) * 0.6)
label_color_bullish = input.color(color.rgb(43, 255, 0), title = "Label Color Bullish", group = "BULLISH ENGULFING")
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_DownTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close >= open[1] and open <= close[1] and ( close > open[1] or open < close[1] )
if C_EngulfingBullish
    var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
    label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
bgcolor(ta.highest(C_EngulfingBullish?1:0, C_EngulfingBullishNumberOfCandles)!=0 ? color.new(#21f321, 90) : na, offset=-(C_EngulfingBullishNumberOfCandles-1))
var float c       = 0
var float o       = 0
var float c_exit  = 0
var float c_stopl = 0
if C_EngulfingBullish and strategy.opentrades==0 and inDateRange 
    c := strategy.equity
    o := close
    c_exit  := c + (c * PROFIT / 100)
    c_stopl := c - (c * STOPLOSS / 100)
    strategy.entry(id = "LONG", direction = strategy.long, qty = qty_order, limit = o)
if ta.crossover(strategy.equity, c_exit)
    strategy.exit(id = "CLOSE-LONG", from_entry = "LONG", limit = close)
if ta.crossunder(strategy.equity, c_stopl)
    strategy.exit(id = "CLOSE-LONG", from_entry = "LONG", limit = close)
Expand (115 lines)

Overview

Buy&Sell Bullish Engulfing - The Quant Science supports backtesting over a user-defined date range with inputs for profit target, stop loss percentage, order size, and trend detection rules. The strategy uses percent of equity for position sizing and explicitly sets pyramiding to one, allowing multiple entries in the same direction. It plots buy and sell markers on the chart for trading decisions. The main settings control the backtest period and trade parameters. A notable limit is that exact entry and exit conditions rely on the engulfing pattern logic which may require manual verification.

Details

Published by

hasnocool on GitHub

Code credit

thequantscience, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Candlestick patterns

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
D: int1startDate
M: int1startMonth
Y: int2022startYear
D: int31endDate
M: int12endMonth
Y: int2023endYear
Target profit (%): float1PROFIT
Stop Loss (%): float1STOPLOSS
Orders size (%): float2orders_size
Detect Trend Based OnstringtrendRule1trendRule
Label Color Bullishcolorcolor.rgb(43, 255, 0)label_color_bullish
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

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

ESU2023-10M - V1

by dearvn
257 stars

ESU2023-10M - V1 is an intraday trend-reversal strategy designed for index futures contracts on the price chart. It calculates a 3-period moving average of candle highs and lows alongside specific three-bar price action patterns to detect short-term swing high

Strategy v5 TrendCandlestick patterns
Updated 6 weeks ago · None stated GitHub repository of ESU2023-10M - V1

STRG One Bar Pursuit

by harryguiacorn
219 stars

The STRG One Bar Pursuit strategy identifies single-bar momentum reversals by monitoring shifts between bullish and bearish candlesticks starting from the year 2024. It enters a long position when a bullish candle follows a bearish candle and enters a short po

Strategy v5 Candlestick patternsMean reversion
Updated 1 year ago · None stated GitHub repository of STRG One Bar Pursuit
218 stars

This strategy identifies trade opportunities based on candlestick wick imbalances relative to the Average True Range. It enters positions when candle wicks exceed defined thresholds and filters out doji candles using a minimum body ATR requirement. Exits are h

Strategy v6 Candlestick patternsVolatility & bands Repaints
Updated 3 months ago · None stated GitHub repository of Super Negative R:R Wick Strategy

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers