Below is the TradingView Pine Script code that detects various candlestick patterns based on the trend direction. The script will highlight bullish and bearish patterns on the 4-hour chart, and it will only trigger the relevant patterns if they occur in the correct trend direction.
The basic idea is:
Bullish Patterns like bullish engulfing, morning star, hammer, and piercing line are only valid in an uptrend. Bearish Patterns like bearish engulfing, evening star, shooting star, and dark cloud cover are only valid in a downtrend. The trend will be determined using a 50-period simple moving average (SMA).