Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-gann-square-of-nine

$ Pine Script Gann Square of Nine

Master this advanced and unique technical analysis tool in TradingView's Pine Script that identifies key price levels based on W.D. Gann's geometric and numerical theories, revealing potential support, resistance, and turning points.

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

What is the Gann Square of Nine?

The Gann Square of Nine is a unique and complex analytical tool developed by legendary trader W.D. Gann. It's a spiral of numbers where numbers are arranged in a clockwise spiral, starting from a central number (often 1). The key insight of the Square of Nine is that specific numbers (prices) that fall on certain angles (e.g., 90, 180, 270, 360 degrees, or cardinal and ordinal crosses) from a central starting point tend to act as significant support and resistance levels, and even indicate potential price reversals.

Gann believed that markets move in predictable, geometric patterns, and that there's a harmonious relationship between price and time. The Square of Nine attempts to reveal these hidden relationships. For traders, the practical application often involves:

  • Identifying potential support and resistance levels: Prices falling on key angular lines from a significant high or low are considered strong levels.
  • Predicting turning points: When price approaches these angular levels, it's considered a potential area for reversal or acceleration.
  • Understanding market harmony: The belief that markets adhere to mathematical laws and cycles.
02

Components and Calculation (Gann Square of Nine Price Levels)

The core concept of the Gann Square of Nine for price levels is that square roots of prices, when plotted, form an arithmetic progression. Key levels are then derived from these square roots. A common way to calculate the significant angular price levels for a given `start_price` and a `box_size` (which represents the increment in the spiral) involves the following steps:

  1. Normalize the Starting Price: Divide the `start_price` by the `box_size`.
    Normalized_Price = start_price / box_size
  2. Find the Square Root: Take the square root of the `Normalized_Price`.
    Root_Price = math.sqrt(Normalized_Price)
  3. Identify the Integer Roots: Determine the integer part of the `Root_Price` and the next integer.
    N = math.floor(Root_Price)
    N_plus_1 = N + 1
  4. Calculate Levels for the Current Cycle/Ring: The levels are derived from `(N + X)^2 * box_size` or `(N_plus_1 + X)^2 * box_size`, where `X` represents fractional steps around the square (0.0 for 0 degrees, 0.125 for 45 degrees, 0.25 for 90 degrees, etc.).
03

Basic Gann Square of Nine Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My Gann Square of Nine Levels", overlay=true, max_bars_back=500)

// --- User Inputs ---
anchorPriceInput = input.float(close, title="Anchor Price (Start of Square)", tooltip="The central price from which Gann levels are calculated.")
boxSize = input.float(1.0, title="Box Size / Increment", minval=0.000001, tooltip="The increment used in the Gann Square spiral.")
lineTransparency = input.int(10, title="Line Transparency (0-100)", minval=0, maxval=100)
showLabels = input.bool(true, title="Show Level Labels")

// Function to calculate a Gann Square of Nine price level for a given degree
f_gann_level(currentPrice, boxSize, degree) =>
    float normalizedPrice = currentPrice / boxSize
    float sqrtNormalizedPrice = math.sqrt(normalizedPrice)
    float n_ = math.round(math.sqrt(currentPrice / boxSize))
    
    float calculated_level = na
    if (degree == 0)
        calculated_level = (n_ * n_) * boxSize
    else if (degree == 45)
        calculated_level = (n_ + 0.125) * (n_ + 0.125) * boxSize
    else if (degree == 90)
        calculated_level = (n_ + 0.25) * (n_ + 0.25) * boxSize
    else if (degree == 135)
        calculated_level = (n_ + 0.375) * (n_ + 0.375) * boxSize
    else if (degree == 180)
        calculated_level = (n_ + 0.5) * (n_ + 0.5) * boxSize
    else if (degree == 225)
        calculated_level = (n_ + 0.625) * (n_ + 0.625) * boxSize
    else if (degree == 270)
        calculated_level = (n_ + 0.75) * (n_ + 0.75) * boxSize
    else if (degree == 315)
        calculated_level = (n_ + 0.875) * (n_ + 0.875) * boxSize
    else if (degree == 360)
        calculated_level = (n_ + 1) * (n_ + 1) * boxSize
    else
        calculated_level = na
    
    calculated_level

var float gann_level_0 = na
var float gann_level_45 = na
var float gann_level_90 = na
var float gann_level_135 = na
var float gann_level_180 = na
var gann_level_225 = na
var gann_level_270 = na
var gann_level_315 = na
var gann_level_360 = na

if barstate.isfirst or ta.change(anchorPriceInput) or ta.change(boxSize)
    gann_level_0 = f_gann_level(anchorPriceInput, boxSize, 0)
    gann_level_45 = f_gann_level(anchorPriceInput, boxSize, 45)
    gann_level_90 = f_gann_level(anchorPriceInput, boxSize, 90)
    gann_level_135 = f_gann_level(anchorPriceInput, boxSize, 135)
    gann_level_180 = f_gann_level(anchorPriceInput, boxSize, 180)
    gann_level_225 = f_gann_level(anchorPriceInput, boxSize, 225)
    gann_level_270 = f_gann_level(anchorPriceInput, boxSize, 270)
    gann_level_315 = f_gann_level(anchorPriceInput, boxSize, 315)
    gann_level_360 = f_gann_level(anchorPriceInput, boxSize, 360)

plot(gann_level_0,   title="Gann 0/360 Deg", color=color.new(color.gray, lineTransparency),   linewidth=1, style=plot.style_stepline)
plot(gann_level_45,  title="Gann 45 Deg",  color=color.new(color.orange, lineTransparency), linewidth=1, style=plot.style_stepline)
plot(gann_level_90,  title="Gann 90 Deg",  color=color.new(color.red, lineTransparency),    linewidth=2, style=plot.style_stepline)
plot(gann_level_135, title="Gann 135 Deg", color=color.new(color.yellow, lineTransparency), linewidth=1, style=plot.style_stepline)
plot(gann_level_180, title="Gann 180 Deg", color=color.new(color.purple, lineTransparency), linewidth=2, style=plot.style_stepline)
plot(gann_level_225, title="Gann 225 Deg", color=color.new(color.aqua, lineTransparency),   linewidth=1, style=plot.style_stepline)
plot(gann_level_270, title="Gann 270 Deg", color=color.new(color.blue, lineTransparency),   linewidth=2, style=plot.style_stepline)
plot(gann_level_315, title="Gann 315 Deg", color=color.new(color.lime, lineTransparency),   linewidth=1, style=plot.style_stepline)
plot(gann_level_360, title="Gann 360 Deg", color=color.new(color.gray, lineTransparency),   linewidth=1, style=plot.style_stepline)
$ ✓ Compiled successfully
04

Geometric Harmony

Geometric Harmony

Gann's Square of Nine is rooted in the belief that markets move in predictable, geometric patterns and that specific price levels and timeframes are harmonically related. This indicator helps visualize those price harmonics.

05

Gann Square of Nine Trading Strategies

Conceptual Strategy: Bounces off Gann Levels

This simplified strategy demonstrates how you might react to Gann Square of Nine levels. It focuses on bounces off strong Gann angles (90°, 180°, 270°).

//@version=5
strategy("Gann Square of Nine Strategy", overlay=true)

var float strat_gann_level_90 = na
var float strat_gann_level_180 = na
var float strat_gann_level_270 = na
var float strat_gann_level_360 = na

if barstate.islast or ta.change(anchorPriceInput) or ta.change(boxSize)
    strat_gann_level_90 = f_gann_level(anchorPriceInput, boxSize, 90)
    strat_gann_level_180 = f_gann_level(anchorPriceInput, boxSize, 180)
    strat_gann_level_270 = f_gann_level(anchorPriceInput, boxSize, 270)
    strat_gann_level_360 = f_gann_level(anchorPriceInput, boxSize, 360)

longCondition = close > strat_gann_level_270 and close[1] <= strat_gann_level_270[1]
shortCondition = close < strat_gann_level_90 and close[1] >= strat_gann_level_90[1]

if (longCondition and not na(strat_gann_level_270))
    strategy.entry("Long Gann 270", strategy.long)

if (shortCondition and not na(strat_gann_level_90))
    strategy.entry("Short Gann 90", strategy.short)

profitTargetPoints = input.float(2.0, title="Profit Target (Points)", minval=0.1)
stopLossPoints = input.float(1.0, title="Stop Loss (Points)", minval=0.1)

strategy.exit("Long Gann 270 Exit", from_entry="Long Gann 270", profit=strategy.position_avg_price + profitTargetPoints, stop=strategy.position_avg_price - stopLossPoints)
strategy.exit("Short Gann 90 Exit", from_entry="Short Gann 90", profit=strategy.position_avg_price - profitTargetPoints, stop=strategy.position_avg_price + stopLossPoints)
06

Optimizing Gann Square of Nine Performance

To get the most from Gann Square of Nine levels in Pine Script:

  • Anchor Price Selection: The choice of the `anchorPriceInput` is paramount. It should typically be a significant swing high or low from which a new move is expected.
  • Box Size (Increment) Tuning: The `boxSize` is crucial for the indicator's relevance. Experiment to find a `boxSize` that makes the lines visually meaningful for your asset.
  • Confluence is Key: Gann Square of Nine levels become much more powerful when they align with traditional Pivot Points, Fibonacci Retracements, significant historical highs/lows, Moving Averages, or Trendlines.
  • Price Action Confirmation: Always confirm price reactions at Gann levels with strong candlestick patterns and volume.
  • Understanding Angle Interpretations: 90°, 180°, 270°, and 360° are generally considered the strongest cardinal levels, while 45°, 135°, 225°, and 315° are ordinal levels.
  • Time Cycles (Advanced): True Gann analysis often integrates time cycles, which requires advanced Pine Script coding beyond simple horizontal lines.
07

Important Note

Important Note

Gann's methods are highly subjective and complex. The 'correct' anchorPriceInput and boxSize can be difficult to determine, and different interpretations exist.

08

Common Gann Square of Nine Pitfalls

  • Subjectivity and Complexity: Gann's methods are highly subjective and complex. Different interpretations exist, leading to varying results.
  • Not a Guaranteed System: Gann's tools are not infallible. Price can move through Gann levels without reaction, especially during high volatility.
  • Over-Reliance: Using Gann Square of Nine as the sole decision-making tool without additional confirmation can lead to poor trading decisions.
  • Lack of Standardization: There isn't one single, universally accepted formula for the Gann Square of Nine. Implementations can vary.
  • Lagging Element (for Anchor): If the anchorPriceInput is based on historical data, the levels derived from it are somewhat static and historical.
  • Visual Clutter: Plotting too many levels or using incorrect parameters can clutter the chart.
09

Conclusion

Conclusion

The Gann Square of Nine, as implemented in Pine Script, offers a fascinating and advanced approach to identifying potential support and resistance levels based on W.D. Gann's profound theories. By calculating specific price points corresponding to geometric angles around a chosen anchor, this indicator provides a unique framework for understanding market structure and anticipating turning points. While demanding careful selection of the `anchorPriceInput` and `boxSize`, and requiring diligent confirmation from other technical analysis tools and price action, mastering the Gann Square of Nine can significantly enhance your pine script strategies. By integrating these harmonically derived levels into your trading plan, you can gain a deeper and more nuanced understanding of market dynamics and improve your timing for entries and exits.

Enhance Your Trading

Get a high-performance Pine Script 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 Pine Script Strategy