How to Analyze Candle Wicks Using Pine Script in TradingView?

Price charts in financial markets are a canvas of information, and Japanese candlesticks provide a rich way to visualize this data. Each candlestick tells a story about price movement within a specific timeframe, and wicks – also known as shadows – are crucial elements of that narrative. Understanding how to interpret and programmatically analyze these wicks using Pine Script in TradingView can significantly enhance your trading insights.

Understanding Candle Wicks: Highs, Lows, and Price Action

A candlestick’s body represents the range between the open and close prices. The wicks extend above and below the body, indicating the highest (upper wick) and lowest (lower wick) prices reached during that period. A long wick suggests significant price rejection or volatility in that direction before settling near the body’s range. For instance, a long upper wick implies buyers pushed the price up, but sellers ultimately drove it back down.

Pine Script Basics: Accessing OHLC Data

Pine Script provides straightforward access to the fundamental components of each candlestick bar. The built-in variables open, high, low, and close allow you to retrieve the opening, highest, lowest, and closing prices for the current bar being processed. time and volume are also readily available. These variables are the building blocks for any wick analysis.

Why Analyze Wicks? Identifying Potential Reversals

Wicks are powerful indicators of sentiment and potential turning points. Long wicks, especially at market extremes or near significant support/resistance levels, can signal potential price reversals. A long lower wick on a down-trending bar might suggest selling pressure was met with strong buying interest, potentially indicating a bottom. Conversely, a long upper wick on an up-trending bar could signal buying exhaustion and impending selling pressure. Analyzing wick length relative to the candle body and the overall bar range adds another layer of insight into the strength or weakness of price moves.

Detecting Wick Length and Position with Pine Script

Analyzing wicks programmatically involves calculating their length and position relative to the candle body. This allows us to quantify these visual cues and build objective trading rules.

Calculating Wick Length: Upper and Lower Wicks

The length of the upper wick is the difference between the highest price (high) and the higher of the open and close prices (math.max(open, close)). Similarly, the lower wick length is the difference between the lower of the open and close prices (math.min(open, close)) and the lowest price (low).

We can define functions for these calculations:

// Function to calculate upper wick length
float upperWickLength = high - math.max(open, close)

// Function to calculate lower wick length
float lowerWickLength = math.min(open, close) - low

// Note: body length is math.abs(close - open)

These simple calculations form the basis for identifying candles with unusually long wicks.

Relative Wick Position: Body vs. Wick Ratio

The significance of a wick is often judged relative to the size of the candle body or the total bar range (high - low). A candle with a small body and a very long wick in one direction (e.g., a Doji with a long shadow) is far more indicative of price rejection than a large body with a small wick.

Calculating ratios helps quantify this:

  • Upper Wick to Body Ratio: upperWickLength / math.abs(close - open)
  • Lower Wick to Body Ratio: lowerWickLength / math.abs(close - open)
  • Upper Wick to Total Range Ratio: upperWickLength / (high - low)
  • Lower Wick to Total Range Ratio: lowerWickLength / (high - low)

Care must be taken when the body size is zero (Doji); handling division by zero is essential, perhaps by checking math.abs(close - open) > 0.

Pine Script Functions for Wick Analysis

Beyond basic arithmetic, Pine Script’s built-in functions and variables are key. high, low, open, close are the primitives. math.max(), math.min(), and math.abs() are vital for calculating wick and body lengths. Comparison operators (>, <, >=, <=, ==, !=) are used to check conditions like a wick being longer than the body or exceeding a certain threshold. Custom functions can encapsulate complex wick pattern logic, making your code modular and readable.

Advanced Wick Analysis Techniques in Pine Script

Moving beyond simple wick length, we can identify specific candlestick patterns defined by their wick and body relationships. This requires combining the basic calculations with conditional logic.

Identifying Doji Patterns and Long-Legged Dojis

A Doji is a candlestick where the open and close prices are very close or equal, resulting in a tiny or non-existent body. Its wicks can vary in length. A Long-Legged Doji has significantly long upper and lower wicks, indicating strong indecision and volatility within the bar. Detecting a Doji can be done by checking if math.abs(close - open) is less than a small threshold (e.g., a fraction of the average true range).

// Define a threshold based on ATR for flexibility
float atrValue = ta.atr(14)
float dojiThreshold = atrValue * 0.1 // Example: body less than 10% of ATR

// Check if current bar is a Doji
bool isDoji = math.abs(close - open) < dojiThreshold

// Check for Long-Legged Doji (example criteria)
bool isLongLeggedDoji = isDoji and upperWickLength > atrValue * 0.5 and lowerWickLength > atrValue * 0.5

Using a dynamic threshold like a percentage of ATR makes the detection more robust across different instruments and timeframes.

Hammer and Shooting Star Detection Using Wick Analysis

Hammer (bullish reversal) and Shooting Star (bearish reversal) are classic patterns heavily reliant on wick analysis. Both have a small body (ideally at one end of the bar) and a very long wick on the opposite side, with a minimal or absent wick on the body’s side.

  • Hammer: Small body near the high, long lower wick (typically 2x or more the body length), little to no upper wick. Usually occurs after a downtrend.
  • Shooting Star: Small body near the low, long upper wick (typically 2x or more the body length), little to no lower wick. Usually occurs after an uptrend.

Detecting these requires combining checks for body size, relative wick lengths, and relative wick positions.

// Example logic for detecting a potential Hammer
float bodySize = math.abs(close - open)
float totalRange = high - low

bool isSmallBody = bodySize < totalRange * 0.3 // Body is less than 30% of range
bool isLongLowerWick = lowerWickLength > bodySize * 2 // Lower wick is at least 2x body
bool isSmallUpperWick = upperWickLength < bodySize * 0.5 // Upper wick is less than half body
bool isHammer = isSmallBody and isLongLowerWick and isSmallUpperWick and close > open // Bullish body, lower wick is longer

// Example logic for detecting a potential Shooting Star
bool isShootingStar = isSmallBody and upperWickLength > bodySize * 2 and lowerWickLength < bodySize * 0.5 and close < open // Bearish body, upper wick is longer

Refining these criteria is crucial for practical application.

Combining Wick Analysis with Volume Data

The significance of a wick pattern is often amplified when accompanied by high volume. High volume during the formation of a long wick suggests strong participation in the price rejection. For example, a Hammer on high volume after a downtrend is generally considered more bullish than one on low volume.

Integrating volume into your wick analysis involves accessing the volume built-in variable and adding checks like volume > ta.sma(volume, 20) (current volume is above its 20-period simple moving average) to your pattern detection logic.

Creating Trading Strategies Based on Wick Analysis

Objective wick analysis paves the way for developing systematic trading strategies. While wick patterns are often used as components of larger strategies, they can also form the core logic.

Entry and Exit Rules Based on Wick Patterns

Entry rules could be triggered by the confirmation of a wick pattern. For a Hammer, an entry might be placed above the high of the Hammer candle on the next bar, confirming that price is moving in the expected direction. For a Shooting Star, an entry might be placed below the low of the Shooting Star candle.

Exit rules could involve taking profit at predefined levels or using subsequent wick analysis. For instance, after entering on a Hammer, a long upper wick appearing might be a signal to exit or tighten a stop-loss.

Stop-Loss and Take-Profit Placement Using Wick Information

Wicks provide natural levels for risk management. For a long entry based on a Hammer, a logical stop-loss could be placed below the low of the Hammer candle’s long lower wick. This level represents the extreme low reached during the rejection; a move below it invalidates the pattern’s premise. For a short entry based on a Shooting Star, the stop-loss could be placed above the high of the Shooting Star’s long upper wick.

Take-profit levels can be set using fixed risk-to-reward ratios relative to the stop distance, or by targeting previous support/resistance levels or measured moves derived from the wick pattern itself.

Backtesting Wick-Based Strategies in TradingView

Pine Script’s strategy functions (e.g., strategy.entry, strategy.exit, strategy.close) are essential for backtesting. You define your entry and exit conditions based on your wick analysis logic, and the TradingView strategy tester simulates these trades on historical data, providing performance metrics like net profit, drawdown, and win rate.

Rigorous backtesting, including forward testing on new data, is critical. Be mindful of lookahead bias (using data from future bars) and over-optimization (fitting the strategy too closely to historical data).

Practical Examples and Pine Script Code Snippets

Let’s translate some of these concepts into actionable Pine Script code.

Example 1: Highlighting Candles with Long Upper Wicks

This script highlights candles where the upper wick is significantly longer than the lower wick and the body combined, potentially indicating strong selling pressure from the high.

//@version=5
indicator("Long Upper Wick Highlighter", shorttitle="LgUpperWick", overlay=true)

// --- Inputs --- 
float wickRatioThreshold = input.float(2.0, "Upper Wick / (Body + Lower Wick) Ratio Threshold")
int minBodySize = input.int(10, "Minimum Body Size (Ticks)") // Prevent division by tiny/zero body

// --- Calculations ---
float bodySize = math.abs(close - open)
float upperWick = high - math.max(open, close)
float lowerWick = math.min(open, close) - low

// --- Logic ---
bool isLongUpperWickCandidate = bodySize * syminfo.mintick >= minBodySize // Ensure minimum body size
bool meetsRatioCriteria = isLongUpperWickCandidate and (bodySize + lowerWick > 0) and (upperWick / (bodySize + lowerWick)) >= wickRatioThreshold

// --- Plotting ---
barcolor(meetsRatioCriteria ? color.yellow : na, title="Highlight")

This indicator calculates the upper and lower wick lengths and body size. It then checks if the upper wick is, for example, two times (based on wickRatioThreshold) longer than the combined length of the body and the lower wick, only for candles with a minimum body size to avoid noise from extreme Dojis or tiny bars.

Example 2: Alerting on Potential Hammer Formations

This script provides an alert condition for potential Hammer patterns based on defined criteria.

//@version=5
indicator("Hammer Alert", shorttitle="HammerAlert", overlay=true)

// --- Inputs ---
float bodyRatioThreshold = input.float(0.3, "Max Body Size (% of Range)")
float wickRatioThreshold = input.float(2.0, "Min Lower Wick / Body Ratio")
float upperWickRatioThreshold = input.float(0.5, "Max Upper Wick / Body Ratio")

// --- Calculations ---
float bodySize = math.abs(close - open)
float totalRange = high - low
float upperWick = high - math.max(open, close)
float lowerWick = math.min(open, close) - low

// --- Logic ---
bool isSmallBody = totalRange > 0 and bodySize / totalRange < bodyRatioThreshold
bool isLongLowerWick = bodySize > 0 and lowerWick / bodySize >= wickRatioThreshold
bool isSmallUpperWick = bodySize > 0 and upperWick / bodySize < upperWickRatioThreshold

bool isHammer = isSmallBody and isLongLowerWick and isSmallUpperWick and close > open // Added check for close > open for bullish body

// --- Plotting & Alerts ---
plotshape(isHammer, style=shape.triangleup, color=color.green, size=size.small, title="Hammer")

alertcondition(isHammer, "Potential Hammer Pattern", alert.freq_once_per_bar)

This indicator calculates ratios based on user inputs and identifies a Hammer pattern when all conditions are met. It plots an up triangle and triggers an alert, which you can configure in TradingView’s alert settings.

Example 3: Creating a Wick-Based Trend Filter

This example demonstrates a simple concept: a potential trend filter based on the dominance of upper or lower wicks over a period. If lower wicks are predominantly longer, it might indicate underlying buying pressure.

//@version=5
indicator("Wick Dominance Filter", shorttitle="WickFilter")

// --- Inputs ---
int lookbackPeriod = input.int(20, "Lookback Period")
float dominanceThreshold = input.float(0.5, "Dominance Threshold (0.5 = balanced)")

// --- Calculations ---
float totalUpperWick = 0.0
float totalLowerWick = 0.0

for i = 0 to lookbackPeriod - 1
    currentOpen = open[i]
    currentClose = close[i]
    currentHigh = high[i]
    currentLow = low[i]

    currentUpperWick = currentHigh - math.max(currentOpen, currentClose)
    currentLowerWick = math.min(currentOpen, currentClose) - currentLow

    totalUpperWick := totalUpperWick + currentUpperWick
    totalLowerWick := totalLowerWick + currentLowerWick

// --- Logic ---
float wickDominanceRatio = totalUpperWick + totalLowerWick > 0 ? totalLowerWick / (totalUpperWick + totalLowerWick) : 0.5

// --- Plotting ---
plot(wickDominanceRatio, "Wick Dominance Ratio", color=color.blue)

// Highlight when lower wicks dominate significantly
bool isLowerWickDominant = wickDominanceRatio > dominanceThreshold
barcolor(isLowerWickDominant ? color.green : na, title="Lower Wick Dominance")

This script calculates the sum of upper and lower wick lengths over a lookback period. It then plots a ratio showing the proportion of total wick length contributed by lower wicks. When this ratio exceeds a threshold (e.g., 0.6, meaning lower wicks make up over 60% of total wick length), it suggests potential underlying strength.

Conclusion: Improving Trading with Pine Script Wick Analysis

Wick analysis provides valuable insights into price rejection and potential shifts in market sentiment. By leveraging Pine Script, you can move beyond subjective visual interpretation and build objective, quantifiable methods for detecting specific wick patterns, analyzing their significance, and integrating them into your trading systems. From simple bar highlighting to complex strategy entries and exits, understanding and programming wick analysis is a powerful addition to any Pine Script developer’s toolkit. Remember to combine wick analysis with other tools like volume, support/resistance, and trend indicators for more robust trading decisions, and always backtest thoroughly.


Leave a Reply