Williams Alligator

Haiyue
15min

Williams Alligator

Indicator Overview
  • Category: Trend — Overlay Indicator
  • Default Parameters: jawPeriod=13, teethPeriod=8, lipsPeriod=5; jawShift=8, teethShift=5, lipsShift=3
  • Output: Three smoothed moving average lines (Jaw, Teeth, Lips)
  • Applicable Markets: Stocks, Futures, Forex, Cryptocurrencies

I. What is the Williams Alligator

The Williams Alligator was created by renowned American trader and technical analyst Bill Williams, first published in his classic 1995 book Trading Chaos.

Bill Williams compared the market to an alligator, using three Smoothed Moving Averages (SMMA) with different periods and displacements to simulate the alligator’s “Jaw,” “Teeth,” and “Lips.” The relative positions and intertwining states of these three lines reflect different phases of the market.

Three-Line Definitions

LineColorCalculationMeaning
JawBlueSMMA(median, 13), shifted forward 8 periodsLong-term trend, the alligator’s “jawbone”
TeethRedSMMA(median, 8), shifted forward 5 periodsMedium-term trend, the alligator’s “teeth”
LipsGreenSMMA(median, 5), shifted forward 3 periodsShort-term trend, the alligator’s “lips”

Where median=(High+Low)/2median = (High + Low) / 2 (median price).

Four States of the Alligator

Bill Williams used alligator behavior to describe market states:

  1. Sleeping: Three lines are intertwined, the alligator’s mouth is closed —> Market is in consolidation / trendless state
  2. Awakening: Three lines begin to separate, the alligator opens its mouth —> A new trend is about to start
  3. Eating: Three lines are clearly separated in proper order —> Market is in a strong trend
  4. Sated: Three lines begin to converge, the alligator closes its mouth —> The trend is about to end
Bill Williams’ Trading Philosophy

Bill Williams’ core belief was “applying chaos theory to trading.” He argued that markets are inherently chaotic, and traders should not attempt to predict the market but rather identify and follow its natural state. The Alligator indicator embodies this philosophy — it does not predict direction, it only tells you what “phase” the market is currently in.

II. Mathematical Principles and Calculation

Prerequisite: SMMA (Smoothed Moving Average)

SMMA (Smoothed Moving Average), also called RMA (Running Moving Average) or Wilder Smoothing, has the recursive formula:

SMMAt=SMMAt1×(n1)+PricetnSMMA_t = \frac{SMMA_{t-1} \times (n - 1) + Price_t}{n}

The initial value is the simple average of the first nn periods:

SMMAn=1ni=1nPriceiSMMA_n = \frac{1}{n}\sum_{i=1}^{n} Price_i

SMMA is equivalent to exponential smoothing with a decay factor of α=1/n\alpha = 1/n, which is smoother and more lagging than the standard EMA (α=2/(n+1)\alpha = 2/(n+1)).

Median Price

Mediant=Hight+Lowt2Median_t = \frac{High_t + Low_t}{2}

Calculation of the Three Lines

Jaw (Blue Line):

Jawt=SMMA(Median,13)t8Jaw_t = SMMA(Median, 13)_{t-8}

First compute the 13-period SMMA of Median, then shift the result right by 8 periods.

Teeth (Red Line):

Teetht=SMMA(Median,8)t5Teeth_t = SMMA(Median, 8)_{t-5}

8-period SMMA, shifted right by 5 periods.

Lips (Green Line):

Lipst=SMMA(Median,5)t3Lips_t = SMMA(Median, 5)_{t-3}

5-period SMMA, shifted right by 3 periods.

Purpose of the Shift

The forward displacement shifts the curves to the right on the time axis, adding extra lag. This is an intentional design choice by Bill Williams:

  • Different shift amounts cause the three lines to produce staggered crossovers near trend turning points
  • The line with the largest shift (Jaw) changes most slowly, representing the longest-term trend
  • The line with the smallest shift (Lips) reacts fastest, responding first to price changes

Trend State Determination

Uptrend (Bullish Eating):

Lips>Teeth>Jaw(green line on top, blue line on bottom)Lips > Teeth > Jaw \quad \text{(green line on top, blue line on bottom)}

Downtrend (Bearish Eating):

Lips<Teeth<Jaw(green line on bottom, blue line on top)Lips < Teeth < Jaw \quad \text{(green line on bottom, blue line on top)}

Consolidation (Sleeping): Three lines are intertwined with no clear ordering.

III. Python Implementation

import numpy as np
import pandas as pd

def smma(series: np.ndarray, period: int) -> np.ndarray:
    """
    Calculate Smoothed Moving Average (SMMA / RMA / Wilder Smooth).

    Parameters
    ----------
    series : Price series (numpy array)
    period : Smoothing period

    Returns
    ----------
    numpy array, same length as input, first period-1 values are NaN
    """
    n = len(series)
    result = np.full(n, np.nan)

    # Initial value: simple average of the first 'period' data points
    result[period - 1] = np.mean(series[:period])

    # Recursive calculation
    for i in range(period, n):
        result[i] = (result[i - 1] * (period - 1) + series[i]) / period

    return result


def williams_alligator(df: pd.DataFrame,
                       jaw_period: int = 13,
                       teeth_period: int = 8,
                       lips_period: int = 5,
                       jaw_shift: int = 8,
                       teeth_shift: int = 5,
                       lips_shift: int = 3) -> pd.DataFrame:
    """
    Calculate the Williams Alligator indicator.

    Parameters
    ----------
    df : DataFrame, must contain 'high', 'low' columns
    jaw_period : Jaw period, default 13
    teeth_period : Teeth period, default 8
    lips_period : Lips period, default 5
    jaw_shift : Jaw forward shift, default 8
    teeth_shift : Teeth forward shift, default 5
    lips_shift : Lips forward shift, default 3

    Returns
    ----------
    DataFrame with 'jaw', 'teeth', 'lips', 'state' columns
    """
    # Median price
    median = ((df['high'] + df['low']) / 2).values

    # Calculate SMMA
    jaw_raw = smma(median, jaw_period)
    teeth_raw = smma(median, teeth_period)
    lips_raw = smma(median, lips_period)

    # Apply displacement (shift right = positive shift in pandas)
    jaw_series = pd.Series(jaw_raw, index=df.index).shift(jaw_shift)
    teeth_series = pd.Series(teeth_raw, index=df.index).shift(teeth_shift)
    lips_series = pd.Series(lips_raw, index=df.index).shift(lips_shift)

    result = pd.DataFrame({
        'jaw': jaw_series,
        'teeth': teeth_series,
        'lips': lips_series
    }, index=df.index)

    # Classify alligator state
    def classify_state(row):
        if pd.isna(row['jaw']) or pd.isna(row['teeth']) or pd.isna(row['lips']):
            return 'unknown'
        j, t, l = row['jaw'], row['teeth'], row['lips']
        if l > t > j:
            return 'eating_bull'    # Bullish eating
        elif l < t < j:
            return 'eating_bear'    # Bearish eating
        else:
            # Check spread between lines to distinguish sleeping vs transitioning
            spread = max(j, t, l) - min(j, t, l)
            avg = (j + t + l) / 3
            if avg > 0 and spread / avg < 0.005:
                return 'sleeping'   # Sleeping (spread less than 0.5%)
            else:
                return 'transitioning'  # Transitioning (awakening/sated)

    result['state'] = result.apply(classify_state, axis=1)

    return result


# ========== Usage Example ==========
if __name__ == "__main__":
    np.random.seed(42)
    n = 150
    dates = pd.date_range('2024-01-01', periods=n, freq='B')

    # Simulate price data with trending and consolidation phases
    phase1 = np.linspace(0, 10, 50)          # Uptrend
    phase2 = np.zeros(30) + 10               # Consolidation
    phase3 = np.linspace(10, 0, 40)          # Downtrend
    phase4 = np.zeros(30)                    # Consolidation
    trend = np.concatenate([phase1, phase2, phase3, phase4])

    noise = np.cumsum(np.random.randn(n) * 0.3)
    price = 100 + trend + noise

    df = pd.DataFrame({
        'open':  price + np.random.uniform(-0.5, 0.5, n),
        'high':  price + np.abs(np.random.randn(n)) * 1.0,
        'low':   price - np.abs(np.random.randn(n)) * 1.0,
        'close': price + np.random.uniform(-0.3, 0.3, n),
        'volume': np.random.randint(1000, 5000, n)
    }, index=dates)

    alligator = williams_alligator(df)
    merged = df[['close']].join(alligator)

    print("Alligator indicator data for the last 20 periods:")
    print(merged[['close', 'jaw', 'teeth', 'lips', 'state']].tail(20).to_string())

    # State distribution statistics
    print("\nAlligator state distribution:")
    print(merged['state'].value_counts())

    # Find state transition points
    state_changes = merged['state'] != merged['state'].shift(1)
    transitions = merged.loc[state_changes & (merged['state'] != 'unknown'),
                             ['close', 'state']]
    print("\nState transition log (last 10 events):")
    print(transitions.tail(10).to_string())
SMMA Implementation Differences

Different platforms may implement SMMA slightly differently (primarily in how the initial value is handled). MetaTrader uses the SMA of the first N data points as the initial value, while TradingView may use an equivalent EMA formula. This causes minor differences in indicator values during the initial period, but they converge over time.

IV. Problems the Indicator Solves

1. Market Phase Identification

The most valuable function of the Alligator indicator is helping traders identify the current market phase:

Alligator StateMarket MeaningTrading Recommendation
SleepingNo trend, consolidationDo not trade, or use mean-reversion strategies
AwakeningTrend about to startPrepare for entry, wait for confirmation
EatingStrong trend in progressAdd to position in trend direction or hold
SatedTrend about to endGradually take profits or tighten stops

2. Trend Direction Confirmation

  • Bullish alignment (Lips > Teeth > Jaw) —> Go long
  • Bearish alignment (Lips < Teeth < Jaw) —> Go short

3. Entry Timing

Bill Williams recommended entering when the alligator “awakens,” specifically when:

  • The three lines begin to separate from an intertwined state
  • Price breaks through the Lips line
  • The direction aligns with the separation direction

4. Exit Timing

  • Three lines begin to converge (alligator becomes “sated”)
  • Lips crosses back through Teeth
  • Price falls below Teeth (for longs) or rises above Teeth (for shorts)

5. Signal Filtering

When the alligator is sleeping, signals from other indicators have reduced reliability. Use the alligator state as a pre-filter: only execute signals from other systems during the eating phase.

Bill Williams’ Trading Rules

Bill Williams did not use the Alligator indicator in isolation. In his trading system, he combined it with Fractals and momentum oscillators (Awesome Oscillator / Accelerator Oscillator) to form the complete “Trading Chaos” methodology.

V. Advantages, Disadvantages, and Use Cases

Advantages

  1. Clear market phase classification: Four states correspond closely to real market behavior
  2. Highly intuitive: The alligator metaphor makes concepts easy to understand and remember
  3. Filters sideways noise: Explicitly tells traders “do not trade” during consolidation
  4. Multi-timeframe consistency: Performs consistently across daily, 4H, 1H, and other timeframes
  5. Complements the Williams system: Works exceptionally well with Fractals and AO/AC indicators

Disadvantages

  1. Significant lag: SMMA itself has lag, and the added shift makes the three lines even slower to react
  2. Delayed signals at trend onset: A new trend may have already progressed considerably before the alligator “awakens”
  3. Subjectivity in state classification: The criteria for intertwined vs. separated are difficult to quantify precisely
  4. Repeated intertwining in choppy markets: Unable to provide effective signals
  5. Fixed parameters: Bill Williams insisted on using fixed parameters, but different markets/timeframes may require adjustments

Use Cases

ScenarioSuitabilityNotes
Daily trend tradingHighThe classic application for the Alligator
4H chart swing tradingHighPerforms well on medium timeframes
Forex major pairsHighEffective in markets with clear trends
1-minute scalpingLowToo much lag, delayed signals
Very low volatility instrumentsLowThree lines stay intertwined for extended periods

Comparison with Similar Indicators

DimensionWilliams AlligatorTriple MA SystemIchimoku CloudMACD
Number of Lines335 + Cloud2 + Histogram
Information DimensionsTrend phase + DirectionTrend directionTrend + S/RTrend + Momentum
Market Phase IdentificationStrongWeakMediumMedium
Degree of LagMedium-HighDepends on MA typeMedium-HighMedium
Learning CurveMediumSimpleSteepSimple
Original Theoretical BasisChaos TheoryTraditional TAIchimoku Sanjin TheoryGerald Appel

Common Parameter Variants

ScenarioJawTeethLipsNotes
Standard13/88/55/3Bill Williams’ original settings
Short-term8/55/33/2Shortened periods and shifts, faster response
Long-term21/1313/88/5Extended periods, suited for weekly or low-frequency trading
Best Practices
  • Strictly follow the “no trading while sleeping” rule: When the alligator is intertwined, the market has no trend, and forcing trades only leads to losses
  • Combine with fractal breakouts for entry: In the direction of alligator awakening, wait for an upper fractal (long) or lower fractal (short) to be broken
  • Use the Teeth line as a trailing stop: Close the position when the closing price breaks below the Teeth line
  • Multi-timeframe coordination: Confirm trend direction with the alligator on higher timeframes, then find entries on lower timeframes when the alligator awakens
  • The longer the alligator “eats,” the larger the pullback tends to be after it becomes “sated” — take profits in a timely manner