// This Pine Script® code is licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// © PineForge contributors 2026
//
// PF probe 22 — bullish/bearish engulfing candle-pattern detection
// Purpose: parity test for inter-bar pattern recognition using `close[1]` /
// `open[1]` history references and `math.abs/min/max` on body & wick sizes,
// gated by a trend-MA filter.
//
//@version=6
strategy("Candlestick Patterns", overlay=true, initial_capital=1000000, process_orders_on_close=false, pyramiding=1, commission_type=strategy.commission.percent, commission_value=0, slippage=0, default_qty_type=strategy.fixed, default_qty_value=1)
// === Inputs ===
trendLen = input.int(20, "Trend MA Length", minval=5)
// === Trend filter ===
trendMA = ta.sma(close, trendLen)
upTrend = close > trendMA
dnTrend = close < trendMA
// === Candle body and wick calculations ===
bodySize = math.abs(close - open)
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
totalRange = high - low
// === Pattern: Bullish Engulfing ===
bullEngulf = close > open and close[1] < open[1] and close > open[1] and open < close[1]
// === Pattern: Bearish Engulfing ===
bearEngulf = close < open and close[1] > open[1] and close < open[1] and open > close[1]
// === Pattern: Hammer (bullish) ===
hammer = lowerWick > bodySize * 2 and upperWick < bodySize * 0.5 and bodySize > 0
// === Pattern: Shooting Star (bearish) ===
shootStar = upperWick > bodySize * 2 and lowerWick < bodySize * 0.5 and bodySize > 0
// === Pattern: Doji ===
doji = bodySize < totalRange * 0.1 and totalRange > 0
// === Pattern: Morning Star (3-bar bullish reversal) ===
morningStar = close[2] < open[2] and bodySize[1] < bodySize[2] * 0.3 and close > open and close > (open[2] + close[2]) / 2
// === Entry Signals ===
bullSignal = (bullEngulf or hammer or morningStar) and dnTrend
bearSignal = (bearEngulf or shootStar) and upTrend
if bullSignal
strategy.entry("Long", strategy.long)
if bearSignal
strategy.entry("Short", strategy.short)
// === Exit ===
if strategy.position_size > 0 and bearSignal
strategy.close("Long")
if strategy.position_size < 0 and bullSignal
strategy.close("Short")
plot(trendMA, "Trend MA", color=color.gray)