Williams Alligator
Williams Alligator
- 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
| Line | Color | Calculation | Meaning |
|---|---|---|---|
| Jaw | Blue | SMMA(median, 13), shifted forward 8 periods | Long-term trend, the alligator’s “jawbone” |
| Teeth | Red | SMMA(median, 8), shifted forward 5 periods | Medium-term trend, the alligator’s “teeth” |
| Lips | Green | SMMA(median, 5), shifted forward 3 periods | Short-term trend, the alligator’s “lips” |
Where (median price).
Four States of the Alligator
Bill Williams used alligator behavior to describe market states:
- Sleeping: Three lines are intertwined, the alligator’s mouth is closed —> Market is in consolidation / trendless state
- Awakening: Three lines begin to separate, the alligator opens its mouth —> A new trend is about to start
- Eating: Three lines are clearly separated in proper order —> Market is in a strong trend
- Sated: Three lines begin to converge, the alligator closes its mouth —> The trend is about to end
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:
The initial value is the simple average of the first periods:
SMMA is equivalent to exponential smoothing with a decay factor of , which is smoother and more lagging than the standard EMA ().
Median Price
Calculation of the Three Lines
Jaw (Blue Line):
First compute the 13-period SMMA of Median, then shift the result right by 8 periods.
Teeth (Red Line):
8-period SMMA, shifted right by 5 periods.
Lips (Green Line):
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):
Downtrend (Bearish Eating):
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())
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 State | Market Meaning | Trading Recommendation |
|---|---|---|
| Sleeping | No trend, consolidation | Do not trade, or use mean-reversion strategies |
| Awakening | Trend about to start | Prepare for entry, wait for confirmation |
| Eating | Strong trend in progress | Add to position in trend direction or hold |
| Sated | Trend about to end | Gradually 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 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
- Clear market phase classification: Four states correspond closely to real market behavior
- Highly intuitive: The alligator metaphor makes concepts easy to understand and remember
- Filters sideways noise: Explicitly tells traders “do not trade” during consolidation
- Multi-timeframe consistency: Performs consistently across daily, 4H, 1H, and other timeframes
- Complements the Williams system: Works exceptionally well with Fractals and AO/AC indicators
Disadvantages
- Significant lag: SMMA itself has lag, and the added shift makes the three lines even slower to react
- Delayed signals at trend onset: A new trend may have already progressed considerably before the alligator “awakens”
- Subjectivity in state classification: The criteria for intertwined vs. separated are difficult to quantify precisely
- Repeated intertwining in choppy markets: Unable to provide effective signals
- Fixed parameters: Bill Williams insisted on using fixed parameters, but different markets/timeframes may require adjustments
Use Cases
| Scenario | Suitability | Notes |
|---|---|---|
| Daily trend trading | High | The classic application for the Alligator |
| 4H chart swing trading | High | Performs well on medium timeframes |
| Forex major pairs | High | Effective in markets with clear trends |
| 1-minute scalping | Low | Too much lag, delayed signals |
| Very low volatility instruments | Low | Three lines stay intertwined for extended periods |
Comparison with Similar Indicators
| Dimension | Williams Alligator | Triple MA System | Ichimoku Cloud | MACD |
|---|---|---|---|---|
| Number of Lines | 3 | 3 | 5 + Cloud | 2 + Histogram |
| Information Dimensions | Trend phase + Direction | Trend direction | Trend + S/R | Trend + Momentum |
| Market Phase Identification | Strong | Weak | Medium | Medium |
| Degree of Lag | Medium-High | Depends on MA type | Medium-High | Medium |
| Learning Curve | Medium | Simple | Steep | Simple |
| Original Theoretical Basis | Chaos Theory | Traditional TA | Ichimoku Sanjin Theory | Gerald Appel |
Common Parameter Variants
| Scenario | Jaw | Teeth | Lips | Notes |
|---|---|---|---|---|
| Standard | 13/8 | 8/5 | 5/3 | Bill Williams’ original settings |
| Short-term | 8/5 | 5/3 | 3/2 | Shortened periods and shifts, faster response |
| Long-term | 21/13 | 13/8 | 8/5 | Extended periods, suited for weekly or low-frequency trading |
- 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