1. Introduction & Hook
The world of trading is filled with patterns, signals, and strategies. Among these, candlestick patterns stand out for their simplicity and power. The Hanging Man is one such pattern that has captured the attention of traders for decades. But what makes it so special? Why do seasoned traders keep an eye out for this seemingly simple formation? In this comprehensive guide, we will dive deep into the Hanging Man strategy, exploring its origins, logic, mathematical underpinnings, and practical implementations across multiple programming languages. Whether you are a Pine Script enthusiast, a Python developer, or a Node.js coder, this article will equip you with the knowledge and tools to harness the Hanging Man for your trading edge.
2. What is Hanging Man?
The Hanging Man is a single-candle bearish reversal pattern that appears at the top of an uptrend. It is characterized by a small real body near the top of the trading range and a long lower shadow, with little or no upper shadow. The pattern visually resembles a man hanging from a gallows, hence the name. Its appearance signals that buyers are losing control and sellers may be ready to take over, potentially marking the end of an uptrend.
- Location: Appears after a price advance (uptrend).
- Shape: Small real body, long lower shadow (at least twice the body), little or no upper shadow.
- Implication: Bearish reversal signal.
3. Market Logic Behind the Strategy
The Hanging Man pattern tells a story about market psychology. During an uptrend, bulls are in control. When a Hanging Man forms, it means that sellers managed to push the price significantly lower during the session, but buyers managed to bring it back up near the open. However, the long lower shadow reveals that selling pressure is emerging. If the next candle confirms weakness (e.g., closes lower), it suggests that the uptrend may be exhausted and a reversal could be imminent.
- Bulls: Initially in control, but losing momentum.
- Bears: Starting to assert themselves, testing the resolve of buyers.
- Confirmation: Essential. A bearish candle after the Hanging Man increases reliability.
4. Mathematical Foundation & Formula
To programmatically detect a Hanging Man, we need to quantify its features:
- Body Size:
abs(close - open) - Lower Shadow:
min(open, close) - low - Upper Shadow:
high - max(open, close)
The classic criteria:
- Lower shadow >= 2 × body size
- Upper shadow is small or absent
- Small real body at the top of the range
Mathematically, in Pine Script terms:
// Hanging Man detection formula
body = abs(close - open)
lower_shadow = min(open, close) - low
upper_shadow = high - max(open, close)
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= (high - low) * 0.3
5. Step-by-Step Calculation Example
Let’s walk through a real-world example:
- Open: 105
- High: 106
- Low: 100
- Close: 104
Calculations:
- Body = |104 - 105| = 1
- Lower Shadow = min(104, 105) - 100 = 104 - 100 = 4
- Upper Shadow = 106 - max(104, 105) = 106 - 105 = 1
- Total Range = 106 - 100 = 6
Criteria:
- Lower shadow (4) >= 2 × body (2): Yes
- Upper shadow (1) <= 0.3 × body (0.3): No (so this is not a textbook Hanging Man, but close)
- Body (1) <= 0.3 × range (1.8): Yes
In practice, you may adjust thresholds for your market and timeframe.
6. Pine Script Implementation
Below is a robust Pine Script implementation for detecting the Hanging Man pattern. This script highlights the pattern on your chart and can be extended for alerts or automated trading.
//@version=6
strategy("Hanging Man Strategy", overlay=true)
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= range * 0.3 and close > open
bgcolor(is_hanging_man ? color.new(color.red, 80) : na)
// Optional: Enter short on confirmation
confirm = is_hanging_man and close[1] > close
if confirm
strategy.entry("Short", strategy.short)
Comments:
- Highlights Hanging Man candles with a red background.
- Enters a short trade on confirmation (next candle closes lower).
- Customizable thresholds for different assets/timeframes.
7. Parameters & Customization in Pine Script
To make your strategy flexible, expose parameters for body ratio, shadow ratio, and confirmation logic. Here’s how:
//@version=6
strategy("Custom Hanging Man", overlay=true)
body_ratio = input.float(0.3, "Max Body/Range Ratio")
shadow_ratio = input.float(2.0, "Min Lower Shadow/Body Ratio")
upper_shadow_ratio = input.float(0.3, "Max Upper Shadow/Body Ratio")
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
is_hanging_man = lower_shadow >= shadow_ratio * body and upper_shadow <= upper_shadow_ratio * body and body <= range * body_ratio
bgcolor(is_hanging_man ? color.new(color.red, 80) : na)
Now, you can fine-tune the detection logic for your market conditions.
8. Python & FastAPI + NoSQL Implementation
For algorithmic traders and data scientists, Python is a natural choice. Here’s how to detect the Hanging Man pattern in Python, and expose it via a FastAPI endpoint, storing results in a NoSql Database (e.g., MongoDB):
# hanging_man.py
from fastapi import FastAPI
from pydantic import BaseModel
from pymongo import MongoClient
app = FastAPI()
client = MongoClient("mongodb://localhost:27017/")
db = client["trading"]
collection = db["patterns"]
class Candle(BaseModel):
open: float
high: float
low: float
close: float
def is_hanging_man(candle: Candle, body_ratio=0.3, shadow_ratio=2.0, upper_shadow_ratio=0.3):
body = abs(candle.close - candle.open)
lower_shadow = min(candle.open, candle.close) - candle.low
upper_shadow = candle.high - max(candle.open, candle.close)
total_range = candle.high - candle.low
return (
lower_shadow >= shadow_ratio * body and
upper_shadow <= upper_shadow_ratio * body and
body <= total_range * body_ratio
)
@app.post("/detect_hanging_man/")
async def detect(candle: Candle):
result = is_hanging_man(candle)
collection.insert_one({"candle": candle.dict(), "is_hanging_man": result})
return {"is_hanging_man": result}
Comments:
- REST API for pattern detection
- Stores results in MongoDB for later analysis
- Easy to integrate with trading bots or dashboards
9. Node.js / JavaScript Implementation
JavaScript is popular for web-based trading dashboards and bots. Here’s a Node.js function to detect the Hanging Man pattern:
// hangingMan.js
function isHangingMan(candle, bodyRatio = 0.3, shadowRatio = 2.0, upperShadowRatio = 0.3) {
const body = Math.abs(candle.close - candle.open);
const lowerShadow = Math.min(candle.open, candle.close) - candle.low;
const upperShadow = candle.high - Math.max(candle.open, candle.close);
const range = candle.high - candle.low;
return (
lowerShadow >= shadowRatio * body &&
upperShadow <= upperShadowRatio * body &&
body <= range * bodyRatio
);
}
// Example usage
const candle = { open: 105, high: 106, low: 100, close: 104 };
console.log(isHangingMan(candle)); // true or false
Comments:
- Reusable function for any JavaScript/Node.js project
- Can be integrated into trading bots, web apps, or browser extensions
10. Backtesting & Performance Insights
Backtesting is essential to validate any trading strategy. In Pine Script, you can use the strategy functions to simulate trades based on Hanging Man signals. Key metrics to analyze include:
- Win Rate: Percentage of profitable trades
- Profit Factor: Gross profit divided by gross loss
- Drawdown: Maximum loss from peak to trough
- Sharpe Ratio: Risk-adjusted return
Example Pine Script for backtesting:
//@version=6
strategy("Hanging Man Backtest", overlay=true)
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= range * 0.3
if is_hanging_man and close[1] > close
strategy.entry("Short", strategy.short)
strategy.exit("TP/SL", from_entry="Short", profit=100, loss=50)
Analyze the results in TradingView’s Strategy Tester to optimize parameters and improve performance.
11. Risk Management Integration
Risk management is the backbone of sustainable trading. Integrate position sizing, stop-loss, and take-profit mechanisms into your strategy. Here’s how to do it in Pine Script:
//@version=6
strategy("Hanging Man with Risk Management", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=2)
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= range * 0.3
stop_loss = close * 1.01 // 1% above entry
profit_target = close * 0.97 // 3% below entry
if is_hanging_man and close[1] > close
strategy.entry("Short", strategy.short)
strategy.exit("Exit", from_entry="Short", stop=stop_loss, limit=profit_target)
Comments:
- Uses 2% of equity per trade
- Stop-loss and take-profit are set as percentages of entry price
- Prevents catastrophic losses and locks in profits
12. Combining with Other Indicators
The Hanging Man is more powerful when combined with other technical indicators. Common combinations include:
- Moving Averages: Confirm trend direction
- RSI: Identify overbought conditions
- MACD: Confirm momentum shifts
Example Pine Script combining Hanging Man with RSI:
//@version=6
strategy("Hanging Man + RSI", overlay=true)
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
rsi = ta.rsi(close, 14)
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= range * 0.3
if is_hanging_man and rsi > 70
strategy.entry("Short", strategy.short)
This approach filters out weak signals and increases the probability of success.
13. Multi-Timeframe & Multi-Asset Usage
The Hanging Man strategy is versatile. Here’s how to apply it across different timeframes and asset classes:
- Timeframes: Works on 1m, 15m, daily, weekly charts. Shorter timeframes yield more signals but may be noisier.
- Assets: Equities, forex, crypto, options. Adjust parameters for volatility and liquidity.
Example: Multi-timeframe confirmation in Pine Script:
//@version=6
strategy("Hanging Man Multi-Timeframe", overlay=true)
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= range * 0.3
// Check higher timeframe trend
htf_trend = request.security(syminfo.tickerid, "D", close) > request.security(syminfo.tickerid, "D", close[1])
if is_hanging_man and htf_trend == false
strategy.entry("Short", strategy.short)
This script only enters trades when the higher timeframe trend is not bullish, reducing false signals.
14. AI/ML Enhancements
Machine learning can enhance the Hanging Man strategy by optimizing parameters, filtering signals, and adapting to changing market conditions. Here’s how you can use reinforcement learning (RL) to optimize the strategy:
- Feature Engineering: Use Hanging Man occurrence, volume, volatility, and other indicators as features.
- RL Agent: Trains to maximize returns by adjusting thresholds and trade management rules.
# Example: RL agent optimizing Hanging Man parameters (pseudocode)
state = [body_ratio, shadow_ratio, upper_shadow_ratio, rsi, volume]
action = agent.select_action(state)
reward = backtest_strategy(action)
agent.learn(state, action, reward)
Integrate with Python libraries like Stable Baselines or TensorFlow for advanced experimentation.
15. Automation with Playwright/Jest
Automated testing ensures your strategy scripts work as intended. Use playwright for end-to-end browser testing or Jest for unit testing in JavaScript.
// Jest unit test for Hanging Man detection
const { isHangingMan } = require('./hangingMan');
test('Detects Hanging Man pattern', () => {
const candle = { open: 105, high: 106, low: 100, close: 104 };
expect(isHangingMan(candle)).toBe(true);
});
# Playwright e2e test (pseudocode)
import { test, expect } from '@playwright/test';
test('Hanging Man strategy highlights candle', async ({ page }) => {
await page.goto('http://localhost:3000/chart');
// Simulate candle data input
// Check for red highlight on Hanging Man candle
expect(await page.locator('.hanging-man-highlight').isVisible()).toBeTruthy();
});
These tests catch bugs early and ensure reliability in production environments.
16. Advanced Variations
Advanced traders may tweak the Hanging Man strategy for better results:
- Volume Filter: Only trade patterns with above-average volume.
- Pattern Clusters: Require multiple Hanging Man patterns in a row.
- Hybrid Patterns: Combine with engulfing or doji patterns for confirmation.
- Adaptive Thresholds: Adjust ratios based on volatility or ATR.
Example: Volume filter in Pine Script:
//@version=6
strategy("Hanging Man + Volume", overlay=true)
body = math.abs(close - open)
lower_shadow = math.min(open, close) - low
upper_shadow = high - math.max(open, close)
range = high - low
is_hanging_man = lower_shadow >= 2 * body and upper_shadow <= body * 0.3 and body <= range * 0.3
high_volume = volume > ta.sma(volume, 20)
if is_hanging_man and high_volume
strategy.entry("Short", strategy.short)
17. Common Pitfalls & Misconceptions
- Ignoring Confirmation: Acting on the Hanging Man without a bearish follow-up candle leads to false signals.
- Overfitting: Tweaking parameters too much for historical data may not generalize to future markets.
- Neglecting Market Context: The pattern is less reliable in sideways or choppy markets.
- Risk Mismanagement: Failing to use stop-losses can result in large losses.
- Assuming 100% Accuracy: No pattern is infallible. Use as part of a broader trading plan.
18. Conclusion & Key Takeaways
The Hanging Man is a powerful yet simple candlestick pattern that signals potential bearish reversals at the top of uptrends. By understanding its logic, mathematical foundation, and practical implementation, traders can integrate it into robust, automated strategies. Always combine with confirmation signals, sound risk management, and, where possible, machine learning enhancements. Backtest thoroughly and adapt parameters to your market and timeframe. The Hanging Man is not a magic bullet, but in the hands of a disciplined trader, it can be a valuable tool for capturing trend reversals and managing risk.
Glossary of Key Terms
- Body: The difference between open and close prices of a candle.
- Shadow (Wick): The line above or below the body, showing price extremes.
- Confirmation: Additional signal (e.g., bearish candle) validating the pattern.
- Backtesting: Simulating a strategy on historical data to assess performance.
- Risk Management: Techniques to limit losses and protect capital.
- Multi-Timeframe Analysis: Using signals from different chart periods for confirmation.
- Reinforcement Learning: AI technique for optimizing strategies via trial and error.
Comparison Table
| Pattern | Trend Location | Signal | Reliability | Confirmation Needed? |
|---|---|---|---|---|
| Hanging Man | Uptrend Top | Bearish Reversal | Medium | Yes |
| Shooting Star | Uptrend Top | Bearish Reversal | Medium | Yes |
| Hammer | Downtrend Bottom | Bullish Reversal | Medium | Yes |
| Doji | Any | Indecision | Low | Yes |
| Engulfing | Top/Bottom | Reversal | High | No |
TheWallStreetBulls