Indicator · Pine Script v6 · Own pane

Ehlers Phasor Analysis (HT_PHANA)

by mihakralj

This indicator calculates market cycle phase using John Ehlers' Phasor Analysis methodology.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code106
Settings2inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

106 lines of Pine Script v6 from lib/cycles/ht_phana/ht_phana.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

ht_phana.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Ehlers Phasor Analysis (HT_PHANA)", "HT_PHANA", overlay = false)

//@function Ehlers Phasor Analysis — extracts cycle phase via dual Pearson
//          correlation of price against cosine and negative-sine reference waves.
//          Pipeline: corr(price, cos) → Real; corr(price, -sin) → Imag;
//          Angle = 90° - atan(Imag/Real) with wraparound + monotonic constraint.
//          Outputs: Angle, DerivedPeriod, TrendState.
//@param source Series to analyze
//@param period Presumed dominant cycle wavelength in bars (>= 2)
//@returns Angle in degrees (primary), DerivedPeriod, TrendState
//@reference Ehlers, J.F. (2022). "Recurring Phase Of Cycle Analysis."
//           Technical Analysis of Stocks & Commodities, Nov 2022.
//@optimized O(period) per bar — trig lookup eliminates repeated transcendental calls
ht_phana(series float source, simple int period) =>
    if period < 2
        runtime.error("Period must be at least 2")

    var float prevAngle      = 0.0
    var float prevDeltaAngle = 0.0
    var float derivedPeriod  = 0.0

    // --- Correlate price with Cosine wave (Pearson → Real) ---
    float sx_r = 0.0, float sy_r = 0.0
    float sxx_r = 0.0, float sxy_r = 0.0, float syy_r = 0.0
    for k = 0 to period - 1
        float x = nz(source[k])
        float y = math.cos(2.0 * math.pi * k / period)
        sx_r  += x
        sy_r  += y
        sxx_r += x * x
        sxy_r += x * y
        syy_r += y * y

    float dp_r = (period * sxx_r - sx_r * sx_r) * (period * syy_r - sy_r * sy_r)
    float real = dp_r > 0 ? math.max(-1.0, math.min(1.0, (period * sxy_r - sx_r * sy_r) / math.sqrt(dp_r))) : 0.0

    // --- Correlate price with -Sine wave (Pearson → Imag) ---
    float sx_i = 0.0, float sy_i = 0.0
    float sxx_i = 0.0, float sxy_i = 0.0, float syy_i = 0.0
    for k = 0 to period - 1
        float x = nz(source[k])
        float y = -math.sin(2.0 * math.pi * k / period)
        sx_i  += x
        sy_i  += y
        sxx_i += x * x
        sxy_i += x * y
        syy_i += y * y

    float dp_i = (period * sxx_i - sx_i * sx_i) * (period * syy_i - sy_i * sy_i)
    float imag = dp_i > 0 ? math.max(-1.0, math.min(1.0, (period * sxy_i - sx_i * sy_i) / math.sqrt(dp_i))) : 0.0

    // --- Angle = 90 - atan(Imag/Real) with quadrant fix ---
    float angle = 0.0
    if real != 0
        angle := 90.0 - math.todegrees(math.atan(imag / real))
    if real < 0
        angle -= 180.0

    // --- Wraparound compensation ---
    if math.abs(angle) - math.abs(prevAngle - 360.0) < angle - prevAngle and prevAngle > 90.0 and angle < -90.0
        angle -= 360.0

    // --- Monotonic constraint (angle cannot go backwards) ---
    if angle < prevAngle and ((prevAngle > -135.0 and prevAngle < 135.0) or (angle < -90.0 and prevAngle < -90.0))
        angle := prevAngle

    // --- DerivedPeriod from angle rate-of-change ---
    float deltaAngle = angle - prevAngle
    if deltaAngle <= 0
        deltaAngle := prevDeltaAngle
    if deltaAngle > 0
        derivedPeriod := 360.0 / deltaAngle
        prevDeltaAngle := deltaAngle
    if derivedPeriod > 60
        derivedPeriod := 60.0

    // --- Trend state ---
    int trendState = 0
    float angleChange = angle - prevAngle
    if angleChange <= 6.0
        if angle >= 90.0 or angle <= -90.0
            trendState := 1    // trending long
        else if angle > -90.0 and angle < 90.0
            trendState := -1   // trending short

    prevAngle := angle

    [angle, derivedPeriod, trendState]

// ── Inputs ──
int   p_period = input.int(28, "Period", minval = 2)
float p_src    = input.source(close, "Source")

// ── Calculation ──
[angle, dp, ts] = ht_phana(p_src, p_period)

// ── Plot ──
plot(angle, "Angle", color.yellow, 2)
hline(0, "Zero", color.white)
hline(90, "+90", color.new(color.gray, 50))
hline(-90, "-90", color.new(color.gray, 50))
plot(dp, "DerivedPeriod", color.gray, 1, display = display.none)
plot(ts, "TrendState", color.red, 2, display = display.none)

Overview

Ehlers Phasor Analysis (HT_PHANA) correlates the price series against cosine and negative-sine reference waves via dual Pearson correlation to extract real and imaginary phasor components. From these, it computes cycle angle in degrees, derived cycle period, and trend state in a separate pane. The user can configure the presumed cycle period and input price source.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Trend, Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Periodint28p_period
Sourcesourceclosep_src
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Schaff Trend Cycle

by everget
948 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 10 days ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

[RS]Standardized Trend Map

by ricardosantos79
261 stars

Standardized Trend Map calculates series momentum relative to active price range across 40 distinct lookback periods ranging from 2 to 80 bars on an exponential moving average source. Each standardized calculation rounds to an integer values of -1, 0, or 1 to

Indicator v4 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of [RS]Standardized Trend Map

ADX Histogram

by harryguiacorn
219 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram
218 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers