🪙
 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.

Morning/Evening Star

1. Introduction & Hook

The Morning and Evening Star patterns are among the most powerful candlestick formations in technical analysis. Traders across the globe rely on these patterns to anticipate market reversals and optimize their trading strategies. In this comprehensive guide, we will explore the Morning/Evening Star strategy in Pine Script, dissect its market logic, mathematical foundation, and implementation across multiple programming languages. Whether you are a beginner or a seasoned trader, this article will equip you with the knowledge and tools to master this strategy and integrate it into your trading arsenal.

2. What is Morning/Evening Star?

The Morning Star is a bullish reversal pattern, typically appearing at the end of a downtrend. It consists of three candles: a large bearish candle, a small-bodied candle (which can be bullish or bearish), and a large bullish candle. The Evening Star is its bearish counterpart, signaling a potential reversal at the end of an uptrend. It also comprises three candles: a large bullish candle, a small-bodied candle, and a large bearish candle. Both patterns are widely used to identify potential turning points in the market.

3. Market Logic Behind the Strategy

The logic behind the Morning/Evening Star patterns is rooted in market psychology. The first candle represents the prevailing trend (bearish for Morning Star, bullish for Evening Star). The second candle indicates indecision or a pause in momentum, often forming a doji or spinning top. The third candle confirms the reversal, as it moves strongly in the opposite direction of the first candle. This sequence reflects a shift in control from sellers to buyers (Morning Star) or buyers to sellers (Evening Star).

4. Mathematical Foundation & Formula

To programmatically detect these patterns, we define specific criteria for each candle:

  • First Candle: Large body, direction matches the trend.
  • Second Candle: Small body, gaps away from the first candle's close.
  • Third Candle: Large body, opposite direction, closes well into the body of the first candle.

Mathematically, we can express the conditions as:

  • Body size = |close - open|
  • Gap = open of second candle > close of first (for Morning Star), or open of second candle < close of first (for Evening Star)
  • Confirmation = close of third candle > midpoint of first candle (Morning Star), or close of third candle < midpoint of first candle (Evening Star)

5. Step-by-Step Calculation Example

Let’s walk through a Morning Star example:

  • Candle 1: Open = 100, Close = 90 (bearish, large body)
  • Candle 2: Open = 89, Close = 91 (small body, slight gap down)
  • Candle 3: Open = 92, Close = 105 (bullish, large body, closes above midpoint of Candle 1)

Calculation:

  • Body1 = |90 - 100| = 10
  • Body2 = |91 - 89| = 2
  • Body3 = |105 - 92| = 13
  • Midpoint1 = (100 + 90) / 2 = 95
  • Gap: 89 < 90 (gap down)
  • Confirmation: 105 > 95 (close above midpoint)

All conditions are met, confirming a Morning Star pattern.

6. Pine Script Implementation

// Morning/Evening Star Strategy in Pine Script
// Detects both bullish (Morning Star) and bearish (Evening Star) patterns
// and plots buy/sell signals accordingly
//@version=6
strategy("Morning/Evening Star Strategy", overlay=true)

// Helper functions
body_size(open, close) => math.abs(close - open)
midpoint(open, close) => (open + close) / 2

// Morning Star Detection
ms_c1_bear = close[2] < open[2] // Candle 1 bearish
ms_c1_body = body_size(open[2], close[2])
ms_c2_body = body_size(open[1], close[1])
ms_c3_bull = close > open // Candle 3 bullish
ms_c3_body = body_size(open, close)
ms_gap = open[1] < close[2] // Gap down
ms_confirm = close > midpoint(open[2], close[2])

is_morning_star = ms_c1_bear and ms_c1_body > ms_c2_body and ms_c2_body < ms_c3_body and ms_gap and ms_c3_bull and ms_confirm

// Evening Star Detection
es_c1_bull = close[2] > open[2] // Candle 1 bullish
es_c1_body = body_size(open[2], close[2])
es_c2_body = body_size(open[1], close[1])
es_c3_bear = close < open // Candle 3 bearish
es_c3_body = body_size(open, close)
es_gap = open[1] > close[2] // Gap up
es_confirm = close < midpoint(open[2], close[2])

is_evening_star = es_c1_bull and es_c1_body > es_c2_body and es_c2_body < es_c3_body and es_gap and es_c3_bear and es_confirm

// Plot signals
plotshape(is_morning_star, title="Morning Star", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(is_evening_star, title="Evening Star", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

// Strategy entries
if is_morning_star
    strategy.entry("Long", strategy.long)
if is_evening_star
    strategy.entry("Short", strategy.short)

7. Parameters & Customization in Pine Script

To adapt the strategy to different markets or timeframes, you can expose parameters for body size thresholds, gap size, and confirmation levels. Example:

// Customizable parameters
body_threshold = input.int(5, "Min Body Size")
gap_threshold = input.float(0.1, "Min Gap (%)")
confirm_ratio = input.float(0.5, "Confirmation Ratio")

// Use these parameters in your detection logic

This allows traders to fine-tune the sensitivity of pattern detection based on volatility and asset class.

8. Python & FastAPI + NoSQL Implementation

For algorithmic trading platforms, you may want to detect these patterns in Python and serve results via FastAPI, storing signals in a NoSql Database like MongoDB.

# Python implementation for Morning/Evening Star 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

def detect_morning_star(candles: List[Candle]):
    if len(candles) < 3:
        return False
    c1, c2, c3 = candles[-3], candles[-2], candles[-1]
    body1 = abs(c1.close - c1.open)
    body2 = abs(c2.close - c2.open)
    body3 = abs(c3.close - c3.open)
    midpoint1 = (c1.open + c1.close) / 2
    gap = c2.open < c1.close
    confirm = c3.close > midpoint1
    return c1.close < c1.open and body1 > body2 and body2 < body3 and gap and c3.close > c3.open and confirm

@app.post("/detect_morning_star/")
def api_detect_morning_star(candles: List[Candle]):
    result = detect_morning_star(candles)
    db.signals.insert_one({"pattern": "morning_star", "detected": result})
    return {"morning_star": result}

9. Node.js / JavaScript Implementation

JavaScript is popular for browser-based charting and serverless trading bots. Here’s a Node.js function to detect the Morning Star pattern:

// Node.js Morning Star detection
function detectMorningStar(candles) {
    if (candles.length < 3) return false;
    const [c1, c2, c3] = candles.slice(-3);
    const body1 = Math.abs(c1.close - c1.open);
    const body2 = Math.abs(c2.close - c2.open);
    const body3 = Math.abs(c3.close - c3.open);
    const midpoint1 = (c1.open + c1.close) / 2;
    const gap = c2.open < c1.close;
    const confirm = c3.close > midpoint1;
    return c1.close < c1.open && body1 > body2 && body2 < body3 && gap && c3.close > c3.open && confirm;
}

10. Backtesting & Performance Insights

Backtesting is crucial to validate the effectiveness of the Morning/Evening Star strategy. In Pine Script, you can use the strategy functions to simulate trades and analyze metrics such as win rate, profit factor, and drawdown. For Python, libraries like Backtrader or Zipline can be used. Always test across multiple assets and timeframes to ensure robustness.

11. Risk Management Integration

Effective risk management is essential. Integrate position sizing, stop-loss, and take-profit rules into your strategy. Example in Pine Script:

// Risk management example
risk_pct = input.float(1, "Risk % per Trade")
stop_loss = input.float(1.5, "Stop Loss (%)")
take_profit = input.float(3, "Take Profit (%)")

if is_morning_star
    strategy.entry("Long", strategy.long, qty_percent=risk_pct)
    strategy.exit("TP/SL", from_entry="Long", stop=close * (1 - stop_loss/100), limit=close * (1 + take_profit/100))
if is_evening_star
    strategy.entry("Short", strategy.short, qty_percent=risk_pct)
    strategy.exit("TP/SL", from_entry="Short", stop=close * (1 + stop_loss/100), limit=close * (1 - take_profit/100))

12. Combining with Other Indicators

Enhance the reliability of the Morning/Evening Star strategy by combining it with indicators like RSI, MACD, or moving averages. For example, only take trades when the RSI confirms an oversold (Morning Star) or overbought (Evening Star) condition.

// Combine with RSI filter
rsi = ta.rsi(close, 14)
if is_morning_star and rsi < 30
    strategy.entry("Long", strategy.long)
if is_evening_star and rsi > 70
    strategy.entry("Short", strategy.short)

13. Multi-Timeframe & Multi-Asset Usage

Apply the strategy across different timeframes and asset classes. In Pine Script, use the request.security() function to fetch higher timeframe data. For example:

// Multi-timeframe example
htf_close = request.security(syminfo.tickerid, "D", close)
// Use htf_close in your logic

This approach allows you to confirm signals on the daily chart while trading on the 15-minute chart. The strategy is applicable to equities, forex, crypto, and even options, with parameter adjustments for each market’s volatility and structure.

14. AI/ML Enhancements

Machine learning can optimize pattern detection and parameter selection. Feature engineering may include candle ratios, gaps, and confirmation strength. Example: using reinforcement learning (RL) to tune parameters for maximum profit.

# Pseudocode for RL agent optimizing parameters
for episode in range(num_episodes):
    params = agent.select_parameters()
    profit = backtest_strategy(params)
    agent.update(params, profit)

15. Automation with Playwright/Jest

Automate testing of your strategy scripts using playwright for end-to-end checks or Jest for unit tests. Example Jest test for the Node.js implementation:

// Jest unit test for Morning Star detection
const { detectMorningStar } = require('./morningStar');
test('detects Morning Star pattern', () => {
    const candles = [
        { open: 100, close: 90 },
        { open: 89, close: 91 },
        { open: 92, close: 105 }
    ];
    expect(detectMorningStar(candles)).toBe(true);
});

16. Advanced Variations

Advanced traders may look for variations such as:

  • Double Morning/Evening Star (two consecutive patterns)
  • Volume confirmation (higher volume on the third candle)
  • Pattern within a support/resistance zone
  • Integration with volatility filters (ATR, Bollinger Bands)

17. Common Pitfalls & Misconceptions

  • Assuming every pattern leads to a reversal—false signals are common, especially in choppy markets.
  • Ignoring market context—patterns are more reliable at key support/resistance levels.
  • Overfitting parameters—avoid excessive optimization on historical data.
  • Neglecting risk management—always use stop-loss and position sizing.

18. Conclusion & Key Takeaways

The Morning/Evening Star strategy is a robust tool for identifying market reversals. By understanding its logic, mathematical foundation, and implementation across platforms, traders can harness its power for consistent profits. Always combine with sound risk management and consider enhancing with additional indicators or AI-driven optimization.

Glossary of Key Terms

  • Bullish/Bearish: Market direction; bullish means rising, bearish means falling.
  • Body: The difference between open and close prices of a candle.
  • Gap: Price difference between the close of one candle and the open of the next.
  • Confirmation: The third candle’s close relative to the first candle’s midpoint.
  • Risk Management: Techniques to control losses, such as stop-loss and position sizing.
  • Backtesting: Testing a strategy on historical data to evaluate performance.
  • Multi-Timeframe: Using signals from different chart intervals.
  • AI/ML: Artificial Intelligence and Machine Learning for strategy optimization.

Comparison Table

StrategyPattern TypeSignal StrengthBest MarketFalse Signal Rate
Morning/Evening StarReversalHigh (with confirmation)All (Equities, Forex, Crypto)Medium
EngulfingReversalMediumAllMedium
DojiIndecisionLowAllHigh
Hammer/Shooting StarReversalMediumAllMedium

Frequently Asked Questions about Morning/Evening Star

What is a Morning Star in Pine Script?

A Morning Star pattern is a bullish reversal chart pattern that consists of three candlesticks: a small bearish candle followed by two white candles. The second candlestick should be longer than the first and have a higher high, indicating a potential reversal.

How to identify the Evening Star in Pine Script?

An Evening Star pattern is a bearish reversal chart pattern that consists of three candlesticks: a small bullish candle followed by two black candles. The second candlestick should be longer than the first and have a lower low, indicating a potential reversal.

  • Identify the small bullish candle as the 'first' candle.
  • The next candle should be bearish and close below the previous day's open.
  • The third candle should be bearish again, with a lower high than the first two candles.

What is the Pine Script Morning Star strategy?

The Morning Star strategy involves identifying a Morning Star pattern and then entering a long position when the pattern is formed. The strategy can be used in conjunction with other indicators or alone, depending on the trader's preferences.

  • Wait for the formation of a Morning Star pattern.
  • Enter a long position when the pattern is complete.
  • Set a stop-loss below the lowest point of the pattern and take-profit above the highest point of the pattern.

How to use Pine Script Evening Star strategy?

The Evening Star strategy involves identifying an Evening Star pattern and then entering a short position when the pattern is formed. The strategy can be used in conjunction with other indicators or alone, depending on the trader's preferences.

  • Wait for the formation of an Evening Star pattern.
  • Enter a short position when the pattern is complete.
  • Set a stop-loss above the highest point of the pattern and take-profit below the lowest point of the pattern.

What are the benefits of using Pine Script Morning Star strategy?

The Morning Star strategy offers several benefits, including:

  • Low risk: The strategy involves waiting for a reversal pattern to form, which reduces the risk of entering a trade.
  • High reward potential: A successful trade can result in significant profits if the price moves in the expected direction.
  • Simple to implement: The strategy is relatively easy to understand and implement, even for beginner traders.



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