đŸȘ™
 Get student discount & enjoy best sellers ~$7/week

Remember: The content and code examples provided here are designed to help readers understand concepts and principles. These are learning resources and may not be suitable for direct implementation in live environments. For customized, production-ready scripts tailored to your specific strategy and risk parameters, Consult with our expert developers.

Harami Cross

1. Introduction & Hook

The Harami Cross is a powerful candlestick pattern that traders use to spot potential reversals in the market. In the world of algorithmic trading, mastering such patterns can be the difference between consistent profits and missed opportunities. This article will guide you through the Harami Cross strategy in Pine Script, exploring its logic, mathematical foundation, and practical implementation. Whether you are a beginner or a seasoned trader, you will gain deep insights into how to leverage this pattern for trading success.

2. What is Harami Cross?

The Harami Cross is a two-candle pattern found on price charts. It consists of a large-bodied candle (the "mother") followed by a doji candle (the "child") that is completely contained within the body of the first. The doji signals indecision, and when it appears after a strong trend, it can indicate a potential reversal. Traders look for this pattern to anticipate changes in market direction.

  • Bullish Harami Cross: Appears after a downtrend, suggesting a possible upward reversal.
  • Bearish Harami Cross: Appears after an uptrend, suggesting a possible downward reversal.

3. Market Logic Behind the Strategy

The Harami Cross reflects a shift in market sentiment. The first candle shows strong momentum in one direction. The doji that follows indicates indecision—buyers and sellers are in balance. This pause often precedes a reversal, as the prevailing trend loses strength and the opposite side gains confidence. By identifying this pattern, traders can position themselves ahead of potential market moves.

4. Mathematical Foundation & Formula

To detect a Harami Cross, we use the following logic:

  • The first candle (mother) must have a large body (difference between open and close).
  • The second candle (child) must be a doji (open ≈ close).
  • The entire doji must be within the body of the mother candle.

Mathematical conditions:

  • |open[1] - close[1]| > threshold (mother candle body size)
  • |open - close| <= doji_threshold (doji body size)
  • high <= max(open[1], close[1])
  • low >= min(open[1], close[1])

5. Step-by-Step Calculation Example

Suppose we have the following two candles:

  • Candle 1 (Mother): Open = 100, Close = 110, High = 112, Low = 98
  • Candle 2 (Child/Doji): Open = 106, Close = 106.2, High = 107, Low = 105
  1. Mother candle body = |100 - 110| = 10 (large body)
  2. Doji body = |106 - 106.2| = 0.2 (very small, qualifies as doji)
  3. Doji high (107) <= max(100, 110) = 110
  4. Doji low (105) >= min(100, 110) = 100

All conditions are met, so this is a valid Harami Cross.

6. Pine Script Implementation

Below is a Pine Script implementation that detects the Harami Cross pattern and plots signals on the chart.

//@version=6
strategy("Harami Cross Strategy", overlay=true)

// Parameters
mother_body_threshold = input.float(1.0, title="Mother Candle Min Body Size (%)")
doji_body_threshold = input.float(0.1, title="Doji Max Body Size (%)")

// Calculate body sizes
mother_body = math.abs(open[1] - close[1])
doji_body = math.abs(open - close)

// Calculate mother candle size as percent of price
mother_body_pct = mother_body / close[1] * 100
doji_body_pct = doji_body / close * 100

// Harami Cross logic
is_mother_large = mother_body_pct >= mother_body_threshold
is_doji = doji_body_pct <= doji_body_threshold
is_child_inside = high <= math.max(open[1], close[1]) and low >= math.min(open[1], close[1])

bullish_harami_cross = is_mother_large and is_doji and is_child_inside and close[1] < open[1]
bearish_harami_cross = is_mother_large and is_doji and is_child_inside and close[1] > open[1]

plotshape(bullish_harami_cross, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="Bullish Harami Cross")
plotshape(bearish_harami_cross, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="Bearish Harami Cross")

// Example strategy entry
if bullish_harami_cross
    strategy.entry("Long", strategy.long)
if bearish_harami_cross
    strategy.entry("Short", strategy.short)

7. Parameters & Customization in Pine Script

You can adjust the sensitivity of the Harami Cross detection by changing the mother_body_threshold and doji_body_threshold parameters. For volatile assets, you may want to increase the thresholds to reduce false signals. Pine Script allows you to expose these as inputs so you can optimize them during backtesting.

  • mother_body_threshold: Minimum body size for the mother candle (as a percentage of price).
  • doji_body_threshold: Maximum body size for the doji (as a percentage of price).

8. Python & FastAPI + NoSQL Implementation

For automated trading or research, you may want to detect Harami Cross patterns in Python and serve results via an API. Below is a Python example using FastAPI and a NoSql Database (e.g., MongoDB):

# Python FastAPI example for Harami Cross detection
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
from pymongo import MongoClient

app = FastAPI()
client = MongoClient("mongodb://localhost:27017/")
db = client["trading"]

class Candle(BaseModel):
    open: float
    close: float
    high: float
    low: float

@app.post("/detect_harami_cross/")
def detect_harami_cross(candles: List[Candle]):
    results = []
    for i in range(1, len(candles)):
        mother = candles[i-1]
        child = candles[i]
        mother_body = abs(mother.open - mother.close)
        doji_body = abs(child.open - child.close)
        mother_body_pct = mother_body / mother.close * 100
        doji_body_pct = doji_body / child.close * 100
        is_mother_large = mother_body_pct >= 1.0
        is_doji = doji_body_pct <= 0.1
        is_child_inside = child.high <= max(mother.open, mother.close) and child.low >= min(mother.open, mother.close)
        if is_mother_large and is_doji and is_child_inside:
            results.append({"index": i, "type": "Harami Cross"})
    db.signals.insert_many(results)
    return results

9. Node.js / JavaScript Implementation

Here is a Node.js function to detect Harami Cross patterns in an array of candle objects:

// Node.js Harami Cross detection
function detectHaramiCross(candles) {
  const signals = [];
  for (let i = 1; i < candles.length; i++) {
    const mother = candles[i - 1];
    const child = candles[i];
    const motherBody = Math.abs(mother.open - mother.close);
    const dojiBody = Math.abs(child.open - child.close);
    const motherBodyPct = motherBody / mother.close * 100;
    const dojiBodyPct = dojiBody / child.close * 100;
    const isMotherLarge = motherBodyPct >= 1.0;
    const isDoji = dojiBodyPct <= 0.1;
    const isChildInside = child.high <= Math.max(mother.open, mother.close) && child.low >= Math.min(mother.open, mother.close);
    if (isMotherLarge && isDoji && isChildInside) {
      signals.push({ index: i, type: 'Harami Cross' });
    }
  }
  return signals;
}

10. Backtesting & Performance Insights

Backtesting is essential to validate the effectiveness of the Harami Cross strategy. In Pine Script, you can use the strategy functions to simulate trades and analyze performance metrics such as win rate, profit factor, and drawdown. Adjust your thresholds and observe how the strategy performs across different assets and timeframes. Look for periods of overfitting and ensure your results are robust.

11. Risk Management Integration

Risk management is crucial for any trading strategy. Integrate position sizing, stop-loss, and take-profit logic to protect your capital. Here is an example in Pine Script:

// Risk management example in Pine Script
risk_pct = input.float(1.0, title="Risk per Trade (%)")
stop_loss_pct = input.float(2.0, title="Stop Loss (%)")
take_profit_pct = input.float(4.0, title="Take Profit (%)")

if bullish_harami_cross
    strategy.entry("Long", strategy.long, qty_percent=risk_pct)
    strategy.exit("TP/SL", from_entry="Long", stop=close * (1 - stop_loss_pct / 100), limit=close * (1 + take_profit_pct / 100))
if bearish_harami_cross
    strategy.entry("Short", strategy.short, qty_percent=risk_pct)
    strategy.exit("TP/SL", from_entry="Short", stop=close * (1 + stop_loss_pct / 100), limit=close * (1 - take_profit_pct / 100))

12. Combining with Other Indicators

The Harami Cross is more powerful when combined with other technical indicators. For example, you can filter signals using moving averages, RSI, or Bollinger Bands. Only take trades when the Harami Cross aligns with the broader trend or when momentum indicators confirm the reversal.

// Example: Combine with 50-period SMA
sma50 = ta.sma(close, 50)
long_condition = bullish_harami_cross and close > sma50
short_condition = bearish_harami_cross and close < sma50
if long_condition
    strategy.entry("Long", strategy.long)
if short_condition
    strategy.entry("Short", strategy.short)

13. Multi-Timeframe & Multi-Asset Usage

Applying the Harami Cross across multiple timeframes and assets increases its versatility. In Pine Script, use the request.security() function to access higher or lower timeframe data. This allows you to confirm signals on the daily chart while trading on the 15-minute chart, for example. The pattern works on equities, forex, crypto, and even options charts.

// Multi-timeframe confirmation
higher_tf = input.timeframe("D", title="Higher Timeframe")
higher_tf_bullish = request.security(syminfo.tickerid, higher_tf, bullish_harami_cross)
higher_tf_bearish = request.security(syminfo.tickerid, higher_tf, bearish_harami_cross)
if bullish_harami_cross and higher_tf_bullish
    strategy.entry("Long", strategy.long)
if bearish_harami_cross and higher_tf_bearish
    strategy.entry("Short", strategy.short)

14. AI/ML Enhancements

Machine learning can enhance the Harami Cross strategy by optimizing parameters and filtering false signals. Feature engineering may include the size of the mother candle, volatility, and volume. You can use reinforcement learning (RL) agents to dynamically adjust thresholds for different market conditions.

# Example: RL agent optimizing Harami Cross parameters (pseudocode)
for episode in range(num_episodes):
    state = get_market_state()
    action = agent.select_action(state)  # Adjust thresholds
    reward = backtest_strategy(action)
    agent.learn(state, action, reward)

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. Here is a Jest example for the Node.js Harami Cross function:

// Jest unit test for Harami Cross detection
const { detectHaramiCross } = require('./haramiCross');
test('detects Harami Cross pattern', () => {
  const candles = [
    { open: 100, close: 110, high: 112, low: 98 },
    { open: 106, close: 106.2, high: 107, low: 105 }
  ];
  const signals = detectHaramiCross(candles);
  expect(signals.length).toBe(1);
  expect(signals[0].type).toBe('Harami Cross');
});

16. Advanced Variations

Advanced traders may look for Harami Cross patterns with additional filters, such as volume spikes, confirmation from other candlestick patterns, or specific volatility regimes. You can also experiment with adaptive thresholds based on recent market conditions or use ensemble methods to combine multiple pattern detections.

17. Common Pitfalls & Misconceptions

  • Assuming every Harami Cross leads to a reversal—many are false signals.
  • Ignoring market context—patterns are more reliable at key support/resistance levels.
  • Overfitting parameters during backtesting—ensure your strategy generalizes well.
  • Neglecting risk management—always use stops and position sizing.

18. Conclusion & Key Takeaways

The Harami Cross is a valuable tool in a trader’s arsenal. When implemented correctly in Pine Script and combined with robust risk management, it can help you anticipate market reversals and improve your trading results. Remember to validate your strategy with backtesting, optimize parameters, and consider integrating AI for further enhancements. Stay disciplined, and always trade with a plan.

Glossary of Key Terms

  • Harami Cross: A two-candle reversal pattern with a large mother candle and a doji child candle inside its body.
  • Doji: A candlestick with a very small body, indicating indecision.
  • Backtesting: Simulating a strategy on historical data to evaluate performance.
  • Risk Management: Techniques to control losses and protect capital.
  • Reinforcement Learning: A type of machine learning where agents learn by trial and error.

Comparison Table

StrategyPattern TypeStrengthBest MarketFalse Signal Rate
Harami CrossReversalMedium-HighAll (esp. trending)Medium
EngulfingReversalHighAllLow-Medium
DojiIndecisionMediumAllHigh
HammerReversalMediumDowntrendsMedium
Shooting StarReversalMediumUptrendsMedium

Frequently Asked Questions about Harami Cross

What is a Harami Cross in Pine Script?

A Harami Cross is a candlestick pattern recognized by some technical analysts as a potential reversal signal.

It consists of two candles: the first candle (the 'mother' candle) and the second candle (the 'child' candle).

  • The child candle must be completely inside the mother candle, touching or crossing its body.
  • The child candle's wick should not extend beyond the mother candle's wick.

How do I identify a Harami Cross in Pine Script?

To identify a Harami Cross, look for two candles: one with a long body (the mother candle) and another with a shorter body (the child candle).

The child candle should be entirely within the mother candle's body, touching or crossing its wick.

  • Check if the child candle is completely inside the mother candle's body.
  • Verify that the child candle's wick does not extend beyond the mother candle's wick.

What are the possible outcomes of a Harami Cross?

A Harami Cross can be either bullish or bearish, depending on the direction of the next candle.

Bullish Harami Cross: If the next candle closes above the middle of the child candle's body, it may signal a continuation of an uptrend.

Bearish Harami Cross: If the next candle closes below the middle of the child candle's body, it may signal a continuation of a downtrend.

Can I use Harami Cross as a standalone trading strategy?

The Harami Cross is often used in combination with other technical indicators and chart patterns to form a more robust trading strategy.

  • Combine the Harami Cross with other reversal signals, such as the Double Hollow Top or Hanging Man.
  • Use it in conjunction with trend-following strategies, like moving averages or Bollinger Bands.

Is the Harami Cross a reliable indicator?

The reliability of the Harami Cross depends on various factors, including market conditions and the quality of the chart setup.

It's essential to use the Harami Cross in conjunction with other forms of validation, such as chart patterns, trend analysis, or fundamental analysis.

  • Be cautious when using the Harami Cross in highly volatile markets.
  • Consider the chart quality and ensure there are no issues with data feed or chart settings.



How to post a request?

Posting a request is easy. Get Matched with experts within 5 minutes

  • 1:1 Live Session: $60/hour
  • MVP Development / Code Reviews: $200 budget
  • Bot Development: $400 per bot
  • Portfolio Optimization: $300 per portfolio
  • Custom Trading Strategy: $99 per strategy
  • Custom AI Agents: Starting at $100 per agent
Professional Services: Trading Debugging $60/hr, MVP Development $200, AI Trading Bot $400, Portfolio Optimization $300, Trading Strategy $99, Custom AI Agent $100. Contact for expert help.
⭐⭐⭐ 500+ Clients Helped | 💯 100% Satisfaction Rate


Was this content helpful?

Help us improve this article