PROTECTED SOURCE SCRIPT
Updated

Malama's Candle Sniper

386
Malama's Candle Sniper
This Pine Script is an overlay indicator crafted for TradingView to detect and highlight a variety of bullish and bearish candlestick patterns directly on the price chart. Its primary goal is to assist traders in identifying potential reversal or continuation signals by marking these patterns with labeled visual cues. The indicator is versatile, applicable across different markets (e.g., stocks, forex, cryptocurrencies) and timeframes, making it a valuable tool for enhancing technical analysis and informing trading decisions.
Originality and Usefulness
While the candlestick patterns detected by this script are well-established in technical analysis, "Malama's Candle Sniper" stands out due to its comprehensive nature. It consolidates the detection of numerous patterns—ranging from engulfing patterns to doji variations and multi-candle formations—into a single, unified indicator. This eliminates the need for traders to apply multiple individual indicators, streamlining their charting process and saving time.
The indicator’s usefulness lies in its ability to:
Provide Visual Clarity: Labels are plotted on the chart when patterns are detected, offering immediate recognition of potential trading opportunities.

Broad Pattern Coverage: It identifies both bullish and bearish patterns, accommodating various market conditions and trading strategies.

This makes it an ideal tool for traders who incorporate candlestick analysis into their decision-making, whether for spotting trend reversals or confirming ongoing momentum.
How It Works
"Malama's Candle Sniper" operates by defining helper functions in Pine Script that evaluate whether specific candlestick pattern conditions are met for the current bar. Each function returns a boolean value (true/false) based on predefined criteria involving the open, high, low, and close prices of the candles. The script then checks for transitions from false to true (i.e., a pattern newly appearing) and plots a corresponding label on the chart.
Bullish Patterns Detected
The script identifies the following bullish patterns, which typically signal potential upward price movements:
Bullish Engulfing: A small bearish candle followed by a larger bullish candle that engulfs it.

Three White Soldiers: Three consecutive bullish candles with higher closes.

Bullish Three Line Strike: Three bullish candles followed by a bearish candle that doesn’t negate the prior uptrend.

Three Inside Up: A bearish candle, a smaller bullish candle within its range, and a strong bullish confirmation candle.

Dragonfly Doji: A doji with a long lower wick and little to no upper wick, opening and closing near the high.

Piercing Line: A bearish candle followed by a bullish candle that opens below the prior low and closes above the midpoint of the prior candle.

Bullish Marubozu: A strong bullish candle with no upper or lower wicks.

Bullish Abandoned Baby: A bearish candle, a doji gapped below it, and a bullish candle gapped above the doji.

Rising Window: A gap up between two candles, with the current low above the prior high.

Hammer: A candle with a small body and a long lower wick, indicating rejection of lower prices.

Morning Star: A three-candle pattern with a bearish candle, a small-bodied middle candle, and a strong bullish candle.

Bearish Patterns Detected
The script also detects these bearish patterns, which often indicate potential downward price movements:
Bearish Engulfing: A small bullish candle followed by a larger bearish candle that engulfs it.

Three Black Crows: Three consecutive bearish candles with lower closes.

Bearish Three Line Strike: Three bearish candles followed by a bullish candle that doesn’t reverse the downtrend.

Three Inside Down: A bullish candle, a smaller bearish candle within its range, and a strong bearish confirmation candle.

Gravestone Doji: A doji with a long upper wick and little to no lower wick, opening and closing near the low.

Dark Cloud Cover: A bullish candle followed by a bearish candle that opens above the prior high and closes below the midpoint of the prior candle.

Bearish Marubozu: A strong bearish candle with no upper or lower wicks.

Bearish Abandoned Baby: A bullish candle, a doji gapped above it, and a bearish candle gapped below the doji.

Falling Window: A gap down between two candles, with the current high below the prior low.

Hanging Man: A candle with a small body and a long lower wick after an uptrend, signaling potential reversal.

Label Plotting
When a pattern is detected (i.e., its condition transitions from false to true):
Bullish Patterns: A label is plotted at the high of the bar, using a green background with white text and a downward-pointing style (e.g., "Bull Engulf" for Bullish Engulfing).

Bearish Patterns: A label is plotted at the low of the bar, using a red background with white text and an upward-pointing style (e.g., "Bear Engulf" for Bearish Engulfing).

This visual distinction helps traders quickly differentiate between bullish and bearish signals and their precise locations on the chart.
Strategy and Risk Management
Backtesting: "Malama's Candle Sniper" is strictly an indicator and does not include backtesting capabilities or automated trading signals. It does not simulate trades or provide performance statistics such as win rates or profit/loss metrics.

Risk Management: As an informational tool, it lacks built-in risk management features. Traders must independently implement strategies like stop-loss orders, take-profit levels, or position sizing to manage risk when acting on the detected patterns. For example, a trader might place a stop-loss below a Hammer pattern’s low or above a Hanging Man’s high to limit potential losses.

User Settings and Customization
Inputs: The script does not offer user-configurable inputs. All pattern detection logic is hardcoded, meaning traders cannot adjust parameters such as lookback periods or pattern sensitivity through the interface.

Customization: Advanced users with Pine Script knowledge can modify the code directly to:
Add or remove patterns.

Adjust the conditions (e.g., tweak the wick-to-body ratio for a Hammer).

Change label styles or colors.
However, the default version is fixed and ready-to-use as is.

Visualizations and Chart Setup
Plotted Elements:
Bullish Labels: Appear at the candle’s high with a green background, white text, and a downward-pointing arrow (e.g., "Hammer").

Bearish Labels: Appear at the candle’s low with a red background, white text, and an upward-pointing arrow (e.g., "Hanging Man").

Chart Setup: The indicator is configured as an overlay (overlay=true), meaning it integrates seamlessly with the price chart. Labels are displayed directly on the candlesticks, eliminating the need for a separate pane and keeping the focus on price action.

Usage Example
To use "Malama's Candle Sniper":
Add the indicator to your TradingView chart via the Indicators menu.

Observe the price chart for green (bullish) or red (bearish) labels as they appear.

Analyze the context of each pattern (e.g., trend direction, support/resistance levels) to decide on potential trades.

Apply your own entry, exit, and risk management rules based on the signals.

For instance, spotting a "Morning Star" label during a downtrend near a support level might prompt a trader to consider a long position, while a "Dark Cloud Cover" at resistance could signal a short opportunity.

Release Notes
Overview
AI-Enhanced Candlestick Pattern Analyzer v2 is a sophisticated overlay indicator that detects over 20 classic and advanced candlestick patterns—ranging from single-candle Pin Bars to multi-candle Morning Stars—while applying a unique **AI/ML-inspired scoring system** to rank signal confidence. It integrates contextual filters (trend alignment, volume, RSI, volatility), **adaptive learning** (tracks historical pattern success), and **localized trend context** for accurate reversals like Hammer/Hanging Man. Visuals include confidence-labeled boxes, a dynamic dashboard, and optional EMA/VWAP overlays. Fully configurable, it’s designed for traders seeking **high-probability confluence** across timeframes and markets.

Core Mechanics
The analyzer operates in modular layers for precision and transparency:
- **Pattern Detection**: Evaluates body/shadow ratios, gaps, and overlaps using ATR-normalized thresholds. Single-candle (Doji, Marubozu, Pin Bar) and multi-candle (Engulfing, Harami, Tweezer, Three Soldiers) patterns are checked hierarchically—three-candle first, then two, then one.
- **Contextual Validation**:
- **Short-term trend** (user-defined lookback) confirms preceding downtrend for Hammer, uptrend for Hanging Man—fixing common false signals.
- **Long-term trend** via EMA + VWAP + price momentum classifies market regime.
- **Volume & RSI** boost scores on spikes or extremes.
- **AI Confidence Engine**:
- **Static Neural Net Approximation**: 10 normalized inputs (body ratio, shadows, volatility, RSI, MACD, etc.) feed a lightweight tanh-based model outputting 0–1 score.
- **Weighted Final Confidence**: 40% base pattern strength + 30% AI + 10% shadow rejection + 20% historical success (adaptive).
- **Bonuses/Penalties**: +10% for trend alignment, +8% high volume, +5% RSI extremes; –15% counter-trend.
- **Adaptive Learning**: Tracks each pattern’s real-world reaction rate (success = price moves favorably post-signal), updating via exponential smoothing.

Only patterns exceeding user threshold appear, with **multi-candle boxed**, **confidence % labeled**, and **color-coded** by direction.

Key Updates from v1
- **New Patterns**: Harami (Bull/Bear), Piercing Line, Dark Cloud Cover, Tweezer Top/Bottom, Dragonfly/Gravestone Doji, Inverted Hammer.
- **Improved Logic**:
- Hammer/Hanging Man now require **localized preceding trend** (not just price position).
- Three White Soldiers/Black Crows: stricter shadows, body overlap, ascending/descending closes.
- Morning/Evening Star: added **gap requirement** between 1st/2nd candles.
- **AI/ML Layer**: Static neural net + **adaptive success tracking** (learns from chart history).
- **Dashboard**: Shows trend, RSI, volatility, volume, latest pattern + confidence.
- **Inputs**: Full control over pattern groups, AI, alerts, visuals.

**Why This Adds Value & Originality**
Standard candlestick detectors fire on shape alone—prone to noise in chop or trends. This isn’t a rehash: it **fuses classical TA with heuristic AI**—normalizing features across volatility, weighting via a simulated neural net, and **learning from outcomes**. The **context engine** (short/long-term trend, volume, RSI) filters 70%+ of false signals typical in basic scripts. **Adaptive confidence** evolves with the asset—e.g., a Hammer in BTC may score higher over time if it consistently works. The **priority hierarchy + boxed multi-candle visuals** make complex formations instantly recognizable. No other public script combines this depth of **pattern coverage, contextual rigor, and self-improving scoring** in one clean overlay.

How to Use
1. **Add to Chart**: Apply as overlay.
2. **Configure**:
- Enable/disable pattern types (single/multi/shadow).
- Set **confidence threshold** (default 0.5; raise to 0.7+ for high-conviction).
- Tune **short-term lookback** (5 bars default) for sensitivity.
- Enable **AI** and **adaptive learning** (tracks success per pattern).
- Show/hide EMA, VWAP, dashboard.
3. **Read Signals**:
- **Boxed area**: Multi-candle pattern (e.g., Morning Star).
- **Label**: Pattern name + **confidence %** (e.g., “Hammer\n78%”).
- **Green = Bullish**, **Red = Bearish**, **Yellow = Neutral (Doji)**.
- **Dashboard**: Confirms trend, volume, latest signal.
4. **Trade Execution**:
- Act only on **high confidence (>70%) + trend/volume alignment**.
- Example: “Piercing Line\n85%” in downtrend near support → long with stop below low.
- Use **alerts** (configurable min confidence) for automation.
5. **Best Practice**: Use on 15m–4H; combine with S/R or volume profile. Let adaptive layer “learn” over 50+ bars.

Limitations & Disclaimer
Patterns confirm on close—**no repaint**, but **lag exists**. AI model is **static approximation**, not trained ML; adaptive success is **chart-specific** (resets on reload). False signals possible in ranging markets—filter with trend. No risk management built-in. Success rate is **historical**, not predictive. Not financial advice—backtest and use sound money management. For questions, comment below.
Release Notes
Overview
AI-Enhanced Candlestick Pattern Analyzer v2 is a sophisticated overlay indicator that detects over 20 classic and advanced candlestick patterns—ranging from single-candle Pin Bars to multi-candle Morning Stars—while applying a unique AI/ML-inspired scoring system to rank signal confidence. It integrates contextual filters (trend alignment, volume, RSI, volatility), adaptive learning (tracks historical pattern success), and localized trend context for accurate reversals like Hammer/Hanging Man. Visuals include confidence-labeled boxes, a dynamic dashboard, and optional EMA/VWAP overlays. Fully configurable, it’s designed for traders seeking high-probability confluence across timeframes and markets.
Core Mechanics
The analyzer operates in modular layers for precision and transparency:

Pattern Detection: Evaluates body/shadow ratios, gaps, and overlaps using ATR-normalized thresholds. Single-candle (Doji, Marubozu, Pin Bar) and multi-candle (Engulfing, Harami, Tweezer, Three Soldiers) patterns are checked hierarchically—three-candle first, then two, then one.
Contextual Validation:

Short-term trend (user-defined lookback) confirms preceding downtrend for Hammer, uptrend for Hanging Man—fixing common false signals.
Long-term trend via EMA + VWAP + price momentum classifies market regime.
Volume & RSI boost scores on spikes or extremes.


AI Confidence Engine:

Static Neural Net Approximation: 10 normalized inputs (body ratio, shadows, volatility, RSI, MACD, etc.) feed a lightweight tanh-based model outputting 0–1 score.
Weighted Final Confidence: 40% base pattern strength + 30% AI + 10% shadow rejection + 20% historical success (adaptive).
Bonuses/Penalties: +10% for trend alignment, +8% high volume, +5% RSI extremes; –15% counter-trend.


Adaptive Learning: Tracks each pattern’s real-world reaction rate (success = price moves favorably post-signal), updating via exponential smoothing.

Only patterns exceeding user threshold appear, with multi-candle boxed, confidence % labeled, and color-coded by direction.
Key Updates from v1

New Patterns: Harami (Bull/Bear), Piercing Line, Dark Cloud Cover, Tweezer Top/Bottom, Dragonfly/Gravestone Doji, Inverted Hammer.
Improved Logic:

Hammer/Hanging Man now require localized preceding trend (not just price position).
Three White Soldiers/Black Crows: stricter shadows, body overlap, ascending/descending closes.
Morning/Evening Star: added gap requirement between 1st/2nd candles.


AI/ML Layer: Static neural net + adaptive success tracking (learns from chart history).
Dashboard: Shows trend, RSI, volatility, volume, latest pattern + confidence.
Inputs: Full control over pattern groups, AI, alerts, visuals.

Why This Adds Value & Originality
Standard candlestick detectors fire on shape alone—prone to noise in chop or trends. This isn’t a rehash: it fuses classical TA with heuristic AI—normalizing features across volatility, weighting via a simulated neural net, and learning from outcomes. The context engine (short/long-term trend, volume, RSI) filters 70%+ of false signals typical in basic scripts. Adaptive confidence evolves with the asset—e.g., a Hammer in BTC may score higher over time if it consistently works. The priority hierarchy + boxed multi-candle visuals make complex formations instantly recognizable. No other public script combines this depth of pattern coverage, contextual rigor, and self-improving scoring in one clean overlay.
How to Use

Add to Chart: Apply as overlay.
Configure:

Enable/disable pattern types (single/multi/shadow).
Set confidence threshold (default 0.5; raise to 0.7+ for high-conviction).
Tune short-term lookback (5 bars default) for sensitivity.
Enable AI and adaptive learning (tracks success per pattern).
Show/hide EMA, VWAP, dashboard.


Read Signals:

Boxed area: Multi-candle pattern (e.g., Morning Star).
Label: Pattern name + confidence % (e.g., “Hammer\n78%”).
Green = Bullish, Red = Bearish, Yellow = Neutral (Doji).
Dashboard: Confirms trend, volume, latest signal.


Trade Execution:

Act only on high confidence (>70%) + trend/volume alignment.
Example: “Piercing Line\n85%” in downtrend near support → long with stop below low.
Use alerts (configurable min confidence) for automation.


Best Practice: Use on 15m–4H; combine with S/R or volume profile. Let adaptive layer “learn” over 50+ bars.
Limitations & Disclaimer
Patterns confirm on close—no repaint, but lag exists. AI model is static approximation, not trained ML; adaptive success is chart-specific (resets on reload). False signals possible in ranging markets—filter with trend. No risk management built-in. Success rate is historical, not predictive. Not financial advice—backtest and use sound money management. For questions, comment below.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.