SineWave Indicator for ThinkOrSwim

Sesqui

New member
VIP
This indicator implements the SineWave Indicator from Dr Ehler's book, "Rocket Science for Traders" in thinkscript and is provided for educational purposes.

upper_sinewave.png



This indicator is similar to the Optimum Predictor Indicator in that it implements Dr Ehler's algorithm which adds phasors of the smoothed and detrended price data and applies the Homodyne Discriminator to the result, returning the price cycle period (eg time to complete a full cycle).

However it then computes the cycle phase angle per the algorithm in Dr Ehler's book. The lower indicator plots the SIN(phase_angle) line and uses a 2nd order accurate finite difference expression to compute its slope. When the SineWave's slope is > 0 it is colored green and red otherwise.

To block false signals, the slope of the price is used to color the zero line green in the lower indicator when the price slope > 0 and red when it is < 0. If the predictor line is sloping up when the price is sloping up (eg both lines are green) taking a long position is indicated. When both lines are red, the exiting a long position and entering a short position is indicated.

On the upper chart, an HMA of HL2 having period of 5 is colored green when both the price slope and SineWave slope > 0 and red when both are < 0.

The upper indicator script is given first, followed by the script for the lower indicator:

CSS:
# From Figure 9.3 of Rocket Science for Traders, by Dr Ehler
# Implements the SineWave Indicator
# Written by [email protected] DEC2024

declare upper;
def Price = close;

script GetPeriod {
    input Period_Prev_Bar = 6;
    def Price = HL2;
    def Smooth = (4 * Price + 3 * Price[1] + 2 * Price[2] + Price[3]) / 10;

    def Detrender = (0.0962 * Smooth + 0.5769 * Smooth[2] - 0.5769 * Smooth[4] - 0.0962 * Smooth[6]) * (0.075 * Period_Prev_Bar + 0.54);

    def Q1 = (0.0962 * Detrender + 0.5769 * Detrender[2] - 0.5769 * Detrender[4] - 0.0962 * Detrender[6]) * (0.075 * Period_Prev_Bar + 0.54);
    def I1 = Detrender[3];

    # Advance the phase of I1 and Q1 by 90 degrees
    def jI = (0.0962 * I1 + 0.5769 * I1[2] - 0.5769 * I1[4] - 0.0962 * I1[6]) * (0.075 * Period_Prev_Bar + 0.54);
    def jQ = (0.0962 * Q1 + 0.5769 * Q1[2] - 0.5769 * Q1[4] - 0.0962 * Q1[6]) * (0.075 * Period_Prev_Bar + 0.54);

    # Phasor addition for 3 bar averaging
    def I2 = I1 - jQ;
    def Q2 = Q1 + jI;

    # Smooth the I and Q components before applying the discriminator
    def I2smooth = 0.2 * I2 + 0.8 * I2[1];
    def Q2smooth = 0.2 * Q2 + 0.8 * Q2[1];

    # Homodyne Discriminator
    def Re = I2smooth * I2smooth[1] + Q2smooth * Q2smooth[1];
    def Im = I2smooth * Q2smooth[1] + Q2smooth * I2smooth[1];

    def Resmooth = 0.2 * Re + 0.8 * Re[1];
    def Imsmooth = 0.2 * Im + 0.8 * Im[1];

    def P = if Imsmooth <> 0 and Resmooth <> 0 and 360.0 / ATan(Imsmooth / Resmooth) < 1.5 * Period_Prev_Bar and 360.0 / ATan(Imsmooth / Resmooth) > 0.67 * Period_Prev_Bar then 360.0 / ATan(Imsmooth / Resmooth) else if 360.0 / ATan(Imsmooth / Resmooth) > 1.5 * Period_Prev_Bar then 1.5 * Period_Prev_Bar else if 360.0 / ATan(Imsmooth / Resmooth) < 0.67 * Period_Prev_Bar then 0.67 * Period_Prev_Bar else if 360.0 / ATan(Imsmooth / Resmooth) < 6 then 6 else if 360.0 / ATan(Imsmooth / Resmooth) > 50 then 50 else 6;

    def Psmooth = 0.2 * P + 0.8 * P[1];
    def Psmoothed_twice = 0.33 * Psmooth + 0.67 * Psmoothed_twice[1];

    plot Period_smoothed = Psmoothed_twice; #returns the newly computed smoothed period value 
    Period_smoothed.Hide();

}# end Script GetPeriod()

def SmoothPeriod = CompoundValue(4,
                          if BarNumber() > 5 then GetPeriod(SmoothPeriod[1]) else SmoothPeriod[1], 6);

# Compute Dominant Cycle Phase
def SmoothPrice = (4 * Price + 3 * Price[1] + 2 * Price[2] + Price[3]) / 10.0;
def DCPeriod = if IsNaN(Floor(SmoothPeriod + 0.5)) then DCPeriod[1] else Floor(SmoothPeriod);

def RealPart = fold count = 0 to DCPeriod with p = 0 do p + Cos(360.0 * 0.0174533 * count / DCPeriod) * GetValue(SmoothPrice, count);

def ImagPart = fold index = 0 to DCPeriod with q = 0 do q + Sin(360.0 * 0.0174533 * index / DCPeriod) * GetValue(SmoothPrice, index);

# Compensating for one bar lag of Weighted Moving Average results in adding 360/SmoothPreriod in the next linear of code 
def DCPhase_calc = if AbsValue(RealPart) > 0.001 then ATan(ImagPart / RealPart) + 90 * 0.0174533 + 360 * 0.0174533 / SmoothPeriod else if AbsValue(RealPart) <= 0.001 then 90.0 * 0.0174533 * Sin(ImagPart) + 90 * 0.0174533 + 360 * 0.0174533 / SmoothPeriod else Double.NaN;

def DCPhase = if ImagPart < 0.0 then DCPhase_calc + 180.0 * 0.0174533 else if DCPhase_calc > 315.0 * 0.0174533 then DCPhase_calc - 360.0 * 0.0174533 else DCPhase_calc;

def Sine = Sin(DCPhase);
def SineSlope = 0.500 * (3.00 * Sine - 4.00 * Sine[1] + Sine[2]);

def priceSlope =  0.500 * (3.00 * Price - 4.00 * Price[1] + Price[2]);

input HMAlength = 5;
input displace = 0;

plot HMA = MovingAverage(AverageType.HULL,close, HMAlength)[-displace];
HMA.SetLineWeight(5);

def PLBuySignal = if SineSlope > 0 and priceSlope > 0 then 1 else 0;
def PLSellSignal =  if SineSlope < 0 and priceSlope < 0 then 1 else 0;

#######################################
##  Maintain the position of trades
#######################################

def CurrentPosition;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 {            # FLAT
        if (PLBuySignal) {
            CurrentPosition = 1;
        } else if (PLSellSignal) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 {      # LONG
        if (PLSellSignal) {
            CurrentPosition = -1;
        } else if ((PLSellSignal)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 {     # SHORT
        if (PLBuySignal) {
            CurrentPosition = 1;
        } else if ((PLBuySignal)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}

def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat  = if CurrentPosition == 0 then 1 else 0;

HMA.AssignValueColor(if isLong then Color.DARK_GREEN else if isShort then Color.DARK_RED else Color.CURRENT);
HMA.SetLineWeight(5);

#END UPPER INDICATOR
CSS:
# From Figure 9.3 of Rocket Science for Traders, by Dr Ehler
# Implements the SineWave Indicator
# Written by [email protected] DEC2024

#=======================================================================================
#START LOWER INDICATOR
declare lower;
def Price = HL2;
def bar_number = BarNumber();

script GetPeriod {
    input Period_Prev_Bar = 6;
    def Price = HL2;
    def Smooth = (4 * Price + 3 * Price[1] + 2 * Price[2] + Price[3]) / 10;

    def Detrender = (0.0962 * Smooth + 0.5769 * Smooth[2] - 0.5769 * Smooth[4] - 0.0962 * Smooth[6]) * (0.075 * Period_Prev_Bar + 0.54);

    def Q1 = (0.0962 * Detrender + 0.5769 * Detrender[2] - 0.5769 * Detrender[4] - 0.0962 * Detrender[6]) * (0.075 * Period_Prev_Bar + 0.54);
    def I1 = Detrender[3];

    # Advance the phase of I1 and Q1 by 90 degrees
    def jI = (0.0962 * I1 + 0.5769 * I1[2] - 0.5769 * I1[4] - 0.0962 * I1[6]) * (0.075 * Period_Prev_Bar + 0.54);
    def jQ = (0.0962 * Q1 + 0.5769 * Q1[2] - 0.5769 * Q1[4] - 0.0962 * Q1[6]) * (0.075 * Period_Prev_Bar + 0.54);

    # Phasor addition for 3 bar averaging
    def I2 = I1 - jQ;
    def Q2 = Q1 + jI;

    # Smooth the I and Q components before applying the discriminator
    def I2smooth = 0.2 * I2 + 0.8 * I2[1];
    def Q2smooth = 0.2 * Q2 + 0.8 * Q2[1];

    # Homodyne Discriminator
    def Re = I2smooth * I2smooth[1] + Q2smooth * Q2smooth[1];
    def Im = I2smooth * Q2smooth[1] + Q2smooth * I2smooth[1];

    def Resmooth = 0.2 * Re + 0.8 * Re[1];
    def Imsmooth = 0.2 * Im + 0.8 * Im[1];

    def P = if Imsmooth <> 0 and Resmooth <> 0 and 360.0 / ATan(Imsmooth / Resmooth) < 1.5 * Period_Prev_Bar and 360.0 / ATan(Imsmooth / Resmooth) > 0.67 * Period_Prev_Bar then 360.0 / ATan(Imsmooth / Resmooth) else if 360.0 / ATan(Imsmooth / Resmooth) > 1.5 * Period_Prev_Bar then 1.5 * Period_Prev_Bar else if 360.0 / ATan(Imsmooth / Resmooth) < 0.67 * Period_Prev_Bar then 0.67 * Period_Prev_Bar else if 360.0 / ATan(Imsmooth / Resmooth) < 6 then 6 else if 360.0 / ATan(Imsmooth / Resmooth) > 50 then 50 else 6;


    def Psmooth = 0.2 * P + 0.8 * P[1];
    def Psmoothed_twice = 0.33 * Psmooth + 0.67 * Psmoothed_twice[1];

    plot Period_smoothed = Psmoothed_twice; #returns the newly computed smoothed period value
    Period_smoothed.Hide();

}# end Script GetPeriod()


def SmoothPeriod = CompoundValue(4,
                          if BarNumber() > 5 then GetPeriod(SmoothPeriod[1]) else SmoothPeriod[1], 6);

# Compute Phase
def SmoothPrice = (4 * Price + 3 * Price[1] + 2 * Price[2] + Price[3]) / 10.0;
def DCPeriod = if IsNaN(Floor(SmoothPeriod + 0.5)) then DCPeriod[1] else Floor(SmoothPeriod);

def RealPart = fold count = 0 to DCPeriod with p = 0 do p + Cos(360.0 * 0.0174533 * count / DCPeriod) * GetValue(SmoothPrice, count);

def ImagPart = fold index = 0 to DCPeriod with q = 0 do q + Sin(360.0*0.0174533*index / DCPeriod) * GetValue(SmoothPrice, index);

# Compensating for one bar lag of Weighted Moving Average results in adding 360/SmoothPreriod in the next linear of code
def DCPhase_calc = if AbsValue(RealPart) > 0.001 then ATan(ImagPart/RealPart)+90*0.0174533 + 360*0.0174533/SmoothPeriod else if AbsValue(RealPart) <= 0.001 then 90.0*0.0174533*Sin(ImagPart)+90*0.0174533 + 360*0.0174533/SmoothPeriod else Double.NaN;

def DCPhase = if ImagPart < 0.0 then DCPhase_calc + 180.0*0.0174533 else if DCPhase_calc > 315.0*0.0174533 then DCPhase_calc - 360.0*0.0174533 else DCPhase_calc;

#The Sin(DCPhase) is the SineWave, and
plot Sine = Sin(DCPhase);

def SineSlope = 0.500 * (3.00 * Sine - 4.00 * Sine[1] + Sine[2]);
Sine.AssignValueColor(if SineSlope > 0 then COlor.Green else Color.Red);
Sine.SetLineWeight(3);

def priceSlope =  0.500 * (3.00 * price - 4.00 * price[1] + price[2]);
plot PriceConfluence = 0;
PriceConfluence.SetLineWeight(5);
PriceConfluence.AssignValueColor(if priceSlope > 0 then Color.Green else Color.Red);

#END
 
Last edited:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
245 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top