Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-hammer

$ Pinescript: Hammer Candlestick Pattern

Unlock powerful bullish reversal signals with this comprehensive guide to detecting and strategizing with Hammer patterns in TradingView's Pinescript.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

Why the Hammer Pattern Matters in Pinescript

The Hammer candlestick pattern is a single-candle bullish reversal pattern that typically forms after a downtrend. It signals a potential bottom and a shift in momentum from sellers to buyers. The Hammer's unique shape indicates that despite selling pressure during the trading period, buyers stepped in strongly to push prices back up, often near the opening price. This makes Hammer patterns invaluable for:

  • Identifying potential bullish trend reversals.
  • Signaling a rejection of lower prices (support).
  • Generating entry signals in long strategies.
02

Understanding the Hammer Candlestick Pattern

A Hammer candle has a small real body (the difference between open and close) and a long lower shadow (wick) that is typically at least twice the length of the real body. It has little or no upper shadow. The color of the body (bullish or bearish) is less important than its shape and location after a downtrend.

03

Hammer Pattern Illustrations

Hammer (Bullish Body)

Open below close, indicating buying strength from the low.

Hammer (Bearish Body)

Open above close, but still shows strong rejection of lower prices.

04

Key Characteristics

Key Characteristics

Small Real Body: The distance between the open and close is small.
Long Lower Shadow: The lower wick is at least twice the length of the real body.
Little or No Upper Shadow: Ideally, there should be no upper wick, or it should be very short.
Context: Most significant when appearing after a clear downtrend.

05

Basic Hammer Pattern Detection in Pinescript

pine-script@terminal
//@version=5
indicator("Hammer Pattern Detector", overlay=true)

// Calculate candle body and wick lengths
realBody = math.abs(close - open)
upperShadow = math.max(open, close) - high
lowerShadow = low - math.min(open, close) // Corrected calculation for lower shadow length

// Define Hammer criteria
// 1. Small real body
isSmallBody = realBody <= (high - low) * 0.3 // Body is at most 30% of total candle range

// 2. Long lower shadow (at least 2x or 3x the body size, or total range)
// Using 2x body size as a common heuristic
isLongLowerShadow = lowerShadow >= realBody * 2

// 3. Little to no upper shadow (upper shadow is less than 10-20% of real body or total range)
isSmallUpperShadow = upperShadow <= realBody * 0.5 // Upper shadow is at most 50% of body, or less than 10% of total range
// Alternative for upper shadow: upperShadow < (high - low) * 0.1

// Combine criteria for Hammer
isHammer = isSmallBody and isLongLowerShadow and isSmallUpperShadow

// Plot signal on the chart
plotshape(isHammer, title="Hammer", location=location.belowbar, color=color.new(color.blue, 0), style=shape.triangleup, size=size.small)

// Alert condition (optional)
alertcondition(isHammer, title="Hammer Detected", message="Hammer Candlestick Pattern Detected!")
$ ✓ Compiled successfully
06

Advanced Hammer Strategies

While basic detection is useful, combining Hammer patterns with other indicators and market context provides stronger, more reliable signals for potential reversals.

07

1. Hammer with Downtrend Confirmation (Using Moving Average)

pine-script@terminal
//@version=5
strategy("Hammer with Trend Confirmation", overlay=true)

// Input for Moving Average length
maLength = input(50, "MA Length (for trend)")
ma = ta.ema(close, maLength) // Using EMA for downtrend detection

// Hammer Pattern Detection (from basic example)
realBody = math.abs(close - open)
upperShadow = math.max(open, close) - high
lowerShadow = low - math.min(open, close)

isSmallBody = realBody <= (high - low) * 0.3
isLongLowerShadow = lowerShadow >= realBody * 2
isSmallUpperShadow = upperShadow <= realBody * 0.5

isHammer = isSmallBody and isLongLowerShadow and isSmallUpperShadow

// Trend Confirmation: Price should be below the MA (downtrend)
// AND the MA itself should be sloping downwards (optional, but stronger)
isDowntrend = close < ma and ma < ma[1]

// Strategy Logic with Trend Confirmation
longSignal = isHammer and isDowntrend

if (longSignal)
    strategy.entry("Long", strategy.long)

// Plot MA
plot(ma, "Trend MA", color.blue)

// Plot confirmed signals
plotshape(longSignal, title="Confirmed Hammer", location=location.belowbar, color=color.new(color.navy, 0), style=shape.arrowup, size=size.normal)
$ ✓ Compiled successfully
08

2. Hammer with Volume Confirmation

pine-script@terminal
//@version=5
indicator("Hammer with Volume Confirmation", overlay=true)

// Hammer Pattern Detection (from basic example)
realBody = math.abs(close - open)
upperShadow = math.max(open, close) - high
lowerShadow = low - math.min(open, close)

isSmallBody = realBody <= (high - low) * 0.3
isLongLowerShadow = lowerShadow >= realBody * 2
isSmallUpperShadow = upperShadow <= realBody * 0.5

isHammer = isSmallBody and isLongLowerShadow and isSmallUpperShadow

// Volume Confirmation:
// Hammer candle's volume should be significantly higher than average volume
avgVolume = ta.sma(volume, 20) // 20-period Simple Moving Average of Volume
isVolumeConfirmed = volume > avgVolume * 1.5 // Volume is 1.5x average

// Combined signal
confirmedHammer = isHammer and isVolumeConfirmed

// Plot confirmed signals
barcolor(confirmedHammer ? color.new(color.aqua, 60) : na)

plotshape(confirmedHammer, title="Hammer (Vol Confirmed)", location=location.belowbar, color=color.new(color.green, 0), style=shape.labelup, size=size.small, text="Hammer Vol")

// Optional: Plot volume for visual check
plot(volume, title="Volume", color=color.gray, style=plot.style_columns)
plot(avgVolume, title="Avg Volume", color=color.orange, style=plot.style_line)
$ ✓ Compiled successfully
09

3. Hammer with RSI Confirmation

pine-script@terminal
//@version=5
indicator("Hammer with RSI Confirmation", overlay=true)

// RSI Inputs
rsiLength = input(14, "RSI Length")
oversold = input(30, "RSI Oversold Level")

// Calculate RSI
rsiValue = ta.rsi(close, rsiLength)

// Hammer Pattern Detection
realBody = math.abs(close - open)
upperShadow = math.max(open, close) - high
lowerShadow = low - math.min(open, close)

isSmallBody = realBody <= (high - low) * 0.3
isLongLowerShadow = lowerShadow >= realBody * 2
isSmallUpperShadow = upperShadow <= realBody * 0.5

isHammer = isSmallBody and isLongLowerShadow and isSmallUpperShadow

// RSI Confirmation: RSI should be in oversold territory or rising from it
rsiConfirmation = rsiValue <= oversold or (rsiValue[1] <= oversold and rsiValue > rsiValue[1])

// Combined signal
signalHammer = isHammer and rsiConfirmation

// Plot signals
plotshape(signalHammer, title="Hammer (RSI Confirmed)", location=location.belowbar, color=color.new(color.fuchsia, 0), style=shape.arrowup, size=size.normal)

// Plot RSI in a separate pane
plot(rsiValue, "RSI", color.blue, linewidth=2, display=display.pane)
hline(oversold, "Oversold", color.green)
$ ✓ Compiled successfully
10

Optimizing Hammer Pattern Performance

To maximize the effectiveness of Hammer patterns in your Pinescript strategies:

  • Confirm Downtrend: The Hammer is a reversal pattern, so it's most reliable when it appears after a clear downtrend. Trading a Hammer in an uptrend or sideways market is usually less effective.
  • Volume Confirmation: A Hammer candle formed with higher than average volume indicates stronger conviction from buyers and increases the reliability of the signal.
  • Support Levels: Hammers that form at significant support levels (e.g., previous lows, moving averages, Fibonacci levels) are more powerful.
  • Subsequent Candle Confirmation: A strong bullish candle after the Hammer further confirms the reversal. Some traders wait for this confirmation before entering.
  • Timeframe: While visible on all timeframes, Hammer signals on higher timeframes (e.g., daily, weekly) generally carry more weight and are more reliable than those on lower timeframes.
11

Common Hammer Pattern Pitfalls to Avoid

Warning: Not all Hammer-shaped candles are valid Hammer patterns. Context and confirmation are crucial. A Hammer in an uptrend is known as a "Hanging Man" and indicates a bearish reversal.
  • Ignoring Trend Context: A Hammer pattern is a *bullish reversal* signal. If it appears in an uptrend, it is NOT a Hammer and likely a Hanging Man, indicating potential bearishness.
  • Insufficient Lower Shadow: A lower shadow that is not at least twice the real body's length might not indicate strong enough rejection of lower prices.
  • Large Real Body: If the real body is too large, it suggests less indecision and less of a "hammering out" of a bottom.
  • Lack of Confirmation: Relying solely on the Hammer pattern without other indicators (volume, support/resistance, follow-through candles) can lead to false signals.
  • Trading in Choppy Markets: In ranging or sideways markets, Hammer patterns are less reliable as there's no clear trend to reverse.
12

Conclusion

Conclusion

The Hammer candlestick pattern is a strong and visually intuitive signal for bullish reversals. By understanding its precise characteristics and, more importantly, its contextual significance within a downtrend, you can leverage it effectively in your trading. Implementing Hammer detection in Pinescript allows you to automate signal generation, combine it with other technical indicators for higher probability trades, and refine your price action analysis to make more informed trading decisions on TradingView.

Enhance Your Trading

Get a high-performance Pinescript analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pinescript Strategy