Momentum Paint Candles

hockeycoachdoug

Active member
2019 Donor
VIP
----------------------------------------------------------------------------------------------------
mod note:
original can be found:
https://usethinkscript.com/threads/a-trend-momentum-and-cycle-trading-system-v3-0-csa.1596/

----------------------------------------------------------------------------------------------------
I watched a webinar awhile back that made the premise that combining a trend based indicator, a momentum based indicator and a cycle based indicator gives a good indication of directional bias. I would like to combine these 3 components into one paintbar type indicator and am hoping one of you coding pros might find value in this and be willing to code it here for the community.
For the trend indicator I want to use supertrend available here by Mobius. Here is the link SuperTrend by Mobius
For the momentum indicator I want to use True Momentum Oscillator (TMO). Here is the link TMO for TOS
For the cycle indicator I want to use TOP Cycle Trader. I am posting the code for this indicator here-

Code:
declare lower;
#plot Data = close;
input   FastCycleLength = 5;
input   SlowCycleLength = 8;
#def   CycleLineColor=DefineGlobalColor(Color.RED);
#input   CycleHistColor=Color.BLUE;
#input   ZeroLineColor1 = GetColor(1);
DefineGlobalColor("CycleLineColor", Color.RED);
DefineGlobalColor("CyclehistColor", Color.BLUE);
DefineGlobalColor("ZeroLineColor", Color.YELLOW);
def H = high;
def L = low;
#def FastVar(0),SlowVar(0),DiffVar(0);

def FastVar = ExpAverage((H + L) / 2, FastCycleLength);
def SlowVar = Average((H + L) / 2, SlowCycleLength);
def DiffVar = FastVar - SlowVar;

plot pDiffVar = DiffVar;
pDiffVar.SetDefaultColor(GlobalColor("CycleLineColor"));
plot pDiffVar2 = DiffVar;
pDiffVar2.SetDefaultColor(GlobalColor("CycleHistColor"));
plot pZeroLine = 0;
pZeroLine.SetDefaultColor(GlobalColor("ZeroLineColor"));
#Plot1(DiffVar,"Cycle",CycleLineColor);
#Plot2(DiffVar,"CycleHist",CycleHistColor);
#Plot3(0    ,"Zero",ZeroLineColor);

Here is how I envision the paintbar working-
When the supertrend indicator is long that would equal +1, when its short -1.
When the TMO is green that would equal +1. when its red its -1.
When the TOP Cycle Trader is above zero that would equal +1, when its below zero -1.
When all 3 indicators are equal to +1 making +3 total the price bars would paint green.
When all 3 indicators are equal to -1 making -3 total the price bars would paint red.
If the combination of all 3 indicators equals anything else, the price bars would paint gray meaning all 3 indicators were not in agreement.

I am open to any and all suggestions. I considered MACD for the momentum indicator but thought TMO was better. Considered Doncian channel for trend but thought supertrend was better. I am hoping one of you coders out there find this idea worthy of putting in the effort to code and share with us here.

I also want to create a scan/ watchlist using this where I can add a number of stock symbols to a watchlist and have the following columns showing symbol, color of bar on a daily basis (or long term) (red, green, or gray), color of bar on a 15 or 30 minute basis (short term)(red, green, or gray, and a column showing average volatility for some period of bars to use as a sort column to find the symbols that are moving.

I want to use this in 3 ways. First as a way to confirm directional bias of trade I am in ( I should be long if bars are green). second with the scanner portion, when both a long term (daily) and a short term (15 or 30 min) are both same color then enter a trade in that colors direction. Lastly as a portfolio management feature. Take a portion of money and break into 5-10 slots each represented by a sector ETF such as 50K broken into 5 trading slots of 10K committed to each ETF. When daily bars are green for a specific ETF, that slot is long all 10K, when its red that slot is in cash.
Thank you in advance.
 
Last edited by a moderator:
@diazlaz Just some quick feedback on version 2.0 - although this is a much slimmer study, the following component has issues passing through the scanner. This is similar to my comments at post # 90 earlier. Hence unless you exclude this the mix, scanning will be an issue.

# CCI + TTM squeeze + TTM trend
 

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

@diazlaz Just some quick feedback on version 2.0 - although this is a much slimmer study, the following component has issues passing through the scanner. This is similar to my comments at post # 90 earlier. Hence unless you exclude this the mix, scanning will be an issue.

# CCI + TTM squeeze + TTM trend
You can remove that and make the threshold 3 for a slightly less accurate version. Make sure you include the MACD fill, it will get you signals a few crucial bars earlier oftentimes.
 
@diazlaz Just some quick feedback on version 2.0 - although this is a much slimmer study, the following component has issues passing through the scanner. This is similar to my comments at post # 90 earlier. Hence unless you exclude this the mix, scanning will be an issue.

# CCI + TTM squeeze + TTM trend


@diazlaz Ah! I found the real culprit that's causing problems in the scan engine, In the CCI + TTM squeeze + TTM trend segment, you have the following code:

Code:
# CCI + TTM squeeze + TTM trend
def CCIBuy = CCI(length = 14).CCI > 0 and CCI(length = 50).CCI > 0;
def CCISell = CCI(length = 14).CCI < 0 and CCI(length = 50).CCI < 0;
def sTrendUp = TTM_Trend().TrendUp;
def sTrendDn = TTM_Trend().TrendDown;
def SqueezeUp = TTM_Squeeze().Histogram >= 0;
def SqueezeDn = TTM_Squeeze().Histogram <= 0;

Now, if you remove the two statements relating to TTM_Trend() from consideration, this passes the scanner beautifully. I was real curious so I looked hard. Unfortunately there's no source code available for TTM_Trend so I guess we won't know the underlying reason. My guess is that it might be using future bars
 
@diazlaz Ah! I found the real culprit that's causing problems in the scan engine, In the CCI + TTM squeeze + TTM trend segment, you have the following code:

Code:
# CCI + TTM squeeze + TTM trend
def CCIBuy = CCI(length = 14).CCI > 0 and CCI(length = 50).CCI > 0;
def CCISell = CCI(length = 14).CCI < 0 and CCI(length = 50).CCI < 0;
def sTrendUp = TTM_Trend().TrendUp;
def sTrendDn = TTM_Trend().TrendDown;
def SqueezeUp = TTM_Squeeze().Histogram >= 0;
def SqueezeDn = TTM_Squeeze().Histogram <= 0;

Now, if you remove the two statements relating to TTM_Trend() from consideration, this passes the scanner beautifully. I was real curious so I looked hard. Unfortunately there's no source code available for TTM_Trend so I guess we won't know the underlying reason. My guess is that it might be using future bars
Thanks Tom. I have a few replacements for TTM trend, if we all think it's necessary we can try 2 alternatives I have that produce similar results to the TTM trend.

We can produce a scan version without the TTM trend in the meantime.
 
I've been testing this on futures tick charts using v1.9. Amazing work on the addition of macd paint.
My simple strategy is this: if green candle crosses up MA, I would long. Red candle candle crosses DowMA, I short. Simple and easy.
The most tricky part, is the exit, since it will take some time for candles to reverse colors. For now I just trail my stops.

Great work Diazlaz. Is this version still not sufficient to trade on?
 
@Playstation This version is sufficient to trade on...but wait for the next version when the two additional Heikin Ashi trends are implemented it should be even more accurate when it comes to confirmations of trend. For exits you may want to use a HULL MA or standard Heikin Ashi. Check out the MTF Heikin Ashi Dots I merged based on @Townsend Heikin Ashi MTF candles and @diazlaz point study...On a 5 min chart I have the Heikin Ashi set at 10 min and I follow it with the 1.9V Trend Momentum Cycle...its pretty accurate. BTW: uncheck the "DATA" plot from the user interface...I don't know how to get rid of it as I am not a coder...

Code:
## Heiken Aski Multi-Time Frame
## 2019 Paul Townsend v3
declare lower;

input UsePeriod = AggregationPeriod.TEN_MIN;

def aOpen = open(period = UsePeriod);
def aClose = close(period = UsePeriod);
def aHigh = high(period = UsePeriod);
def aLow = low(period = UsePeriod);

def haClose = (aOpen + aClose + aHigh + aLow) / 4;
def haOpen = (haOpen[1] + haClose[1]) / 2;

#AssignPriceColor(if haOpen < haClose then Color.GRAY else
#if haOpen > haClose then Color.DOWNTICK else Color.WHITE);

#AddLabel(yes, "[" + UsePeriod / 60000 + "]", Color.WHITE);

 # STATE
    def sState1 = if HAclose > HAopen then 100 else -100;
  
    plot data = sState1;#} #end of HeikinAshiCandles
#</SCRIPT>

# STATE

#def sState = HeikinAshiCandles();

# LOWER PLOT

plot pDB1 = 0;
pDB1.AssignValueColor(
if IsNaN(sState1) then Color.DARK_GRAY else
if sState1 == 100 then Color.GREEN else
Color.RED);
pDB1.SetPaintingStrategy (PaintingStrategy.POINTS);
pDB1.SetLineWeight(5);
pDB1.HideTitle();
pDB1.HideBubble();

# END OF EXAMPLE PLOT
 
@Playstation This is the indicator I tagged you in...I decided to post this here as well as I am not sure how such a volatile indicator would do as part of this CSA study... @diazlaz have you seen this indicator before? Do you think that having it as part of this study here would help to speed up and entry or exit? Your thoughts...

IMO when you use it by its self...its good for a quick scalp IF you're doing a bunch of shares and want to be in and out...It is not an indicator you would use to hold...like lets say TMO or Schaff Trend...,however, will all the other indicators I am not sure how it would react for an early entry exit. This indicator IMO is on par with indicators such as Stochastic Momentum Index...even Fisher Transform. I would love to see some sort of an exit indicator before the candle changes colors in this CSA study as well...I just don't think its possible to have...Meaning having indicators that are meant for long term and indicators that are meant for quick exits...


Code:
# filename: _Universal_Oscillator_LB_
# source: https://www.tradingview.com/script/ieFYbVdC-Ehlers-Universal-Oscillator-LazyBear/

# Original idea and execution:
# Ehlers Universal Oscillator
# Code by LazyBear

# initial port by netarchitech
# 2019.11.05

declare lower;

input bandedge = 20;
input showHistogram = yes;
input showMA = no;
input lengthMA = 9;
input PaintBars = yes;
input price = close;

def whitenoise = (close - close[2])/2;
def a1 = expaverage(-1.414 * 3.14159 / bandedge);
def b1 = 2.0 * a1 * cos(1.414 * 180 /bandedge);
def c2 = b1;
def c3 = -a1 * a1;
def c1 = 1 - c2 - c3;

def filt = c1 * (whitenoise + (whitenoise[1]))/2 + c2 * (filt[1]) + c3 * (filt[2]);

def filt1 = if totalsum(1) == 0 then 0 else if totalsum(1) == 2 then c2 * filt1[1] else if totalsum(1) == 3 then c2 * filt1[1] + c3 * (filt1[2]) else filt;

def pk = if totalsum(1) == 2 then .0000001 else if absvalue(filt1) > pk[1] then absvalue(filt1) else 0.991 * pk[1];

def denom = if pk==0 then -1 else pk;

def euo = if denom == -1 then euo[1] else filt1/pk;

def euoMA = expaverage(euo, lengthMA);

plot zeroLine = 0;

plot diff = if showHistogram then euo else double.nan;
     diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
     diff.SetLineWeight(5);
     diff.DefineColor("Positive and Up", Color.UPTICK);
     diff.DefineColor("Positive and Down", Color.UPTICK);
     diff.DefineColor("Negative and Down", Color.DOWNTICK);
     diff.DefineColor("Negative and Up", Color.DOWNTICK);
     diff.AssignValueColor(if diff >= 0 then if diff > diff[1] then diff.color("Positive and Up") else diff.color("Positive and Down") else if diff < diff[1] then diff.color("Negative and Down") else diff.color("Negative and Up"));

plot ehlers_universal_oscillator = euo;
ehlers_universal_oscillator.hide();

plot showMovAvg = if showMA then euoMA else double.nan;

AssignPriceColor(if PaintBars then (if euo >= 0 then Color.UPTICK else Color.DOWNTICK) else Color.CURRENT);
 
@diazlaz for your next version can you please incorporate the following Heikin Ashi:

Townsend MTF Heikin Ashi so that users can change what timeframe they want. I found that on a 5 min chart a 10 min Heikin Ashi works great with less fake outs...but that could also be attributed to the equities I trade.

Code:
## Heiken Aski Multi-Time Frame
## 2019 Paul Townsend v3

input UsePeriod = aggregationperiod.ten_MIN;

def aOpen = open(period = usePeriod);
def aClose = close(period = usePeriod);
def aHigh = high(period = usePeriod);
def aLow = low(period = usePeriod);

def haClose = (aOpen + aClose + aHigh + aLow)/4;
def haOpen = (haOpen[1] + haClose[1]) /2;

assignpriceColor(if haOpen < haClose then color.green else
if haOpen > haClose then color.red else color.white);

addlabel(yes,"[" + useperiod/60000 + "]",color.white);

Mobius Heikin Ashi SuperTrend:

Code:
# Mobius
# SuperTrend HeikenAshi
# Chat Room Request
# V03.10.2015
# Up = (HIGH + LOW) / 2 + Multiplier * ATR
# Down = (HIGH + LOW) / 2 – Multiplier * ATR
# When the change of trend occurs, the indicator flips

# For RP: Add AR trend, Aberrant Vol, R State, PTR

input AtrMult = .70;
input nATR = 4;
input AvgType = AverageType.HULL;
input PaintBars = yes;
input BubbleOn = no;
input ShowLabel = no;
input AlertOn = no;
input PlotLine = no;

def HAopen;
def HAhigh;
def HAlow;
def HAclose;
HAopen = CompoundValue(1, (haopen[1] + haclose[1]) / 2, (open[1] + close) / 2);
HAhigh = Max(high, close[1]);
HAlow = Min(low, close[1]);
haclose = (HAopen + HAclose[1] + HAlow + close) / 4;
def v = volume;
def bar = barNumber();
def EOD = if SecondsTillTime(1545) == 0 and
             SecondsFromTime(1545) == 0
          then 1
          else 0;
def NotActive = if SecondsFromTime(1545) > 0
                then 1
                else 0;
def ATR = MovingAverage(AvgType, TrueRange(HAhigh, HAclose, HAlow), nATR);
def UP = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1]
         then Round(UP / tickSize(), 0) * tickSize()
         else Round(DN / tickSize(), 0) * tickSize();
plot SuperTrend = ST;
SuperTrend.SetHiding(!PlotLine);
SuperTrend.AssignValueColor(if close < ST then Color.RED else Color.GREEN);
SuperTrend.SetPaintingStrategy(PaintingStrategy.Line);
AssignPriceColor(if PaintBars and close < ST
                 then Color.RED
                 else if PaintBars and close > ST
                      then Color.GREEN
                      else Color.CURRENT);
plot ST_point = if isNaN(close[-1])
                then ST
                else double.nan;
ST_point.SetStyle(Curve.Points);
ST_point.SetLineWeight(3);
ST_point.SetDefaultColor(Color.Yellow);
# End Code SuperTrend HeikenAshi

Schaff Trend Cycle:

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2015-2019
#

declare lower;

input fastLength = 23;
input slowLength = 50;
input KPeriod = 10;
input DPeriod = 3;
input over_bought = 75;
input over_sold = 25;
input averageType = AverageType.EXPONENTIAL;

def macd = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def fastK1 = FastKCustom(macd, KPeriod);
def fastD1 = MovingAverage(averageType, fastK1, DPeriod);
def fastK2 = FastKCustom(fastD1, KPeriod);
plot STC = MovingAverage(averageType, fastK2, DPeriod);
plot OverBought = over_bought;
plot OverSold = over_sold;

STC.SetDefaultColor(GetColor(8));
OverBought.SetDefaultColor(GetColor(7));
OverSold.SetDefaultColor(GetColor(7));
 
Here is Release 2.0. In this release prepares the script to support MTF and Integrates Heikin Ashi Candles and MTF Heikin Ashi Candles.

Set aggregationPeriod of MTF aggregation (default 5 mins) by changing the "aggregationPeriod" input. threshold remain the same adjust as necessary. Please note. you will always need a higher aggregationPeriod in your input from the default period/chart you're on for the study to work properly.


Ruby:
#trend, a momentum and a cycle based indicator for ThinkorSwim V2.0
#@hockeycoachdoug Community Request
#
#VERSION
# 2020.01.17 V2.0 @diazlaz - Integrated HeikinAshiCandles and MTF HeikinAshiCandles
#                          - set aggregationPeriod to MTF aggregation(default 5 mins)
# 2020.01.09 V1.9 @diazlaz - Integrated PaintBars MACD Neutral Condition trigger
#                          - set enableNeutralMACDPainter to yes (default is no) and
#                          - neutral gray will be evaluated by MACD (Dark Red/Green)
# 2020.01.09 V1.8 @diazlaz - Integrated Super Trend w/CCI and ATR
#                          - Integrated CCI + TTM squeeze + TTM trend Combo
#                          - Set treshold defaults to 7 (7 out of 10), removed scanmode.
# 2020.01.04 V1.7 @diazlaz - Integrated Slim Ribbon.
# 2020.01.02 V1.6 @diazlaz - Integrated DMI and BOP, restructured INPUTS to each module.
#                            threshold increased to 4 by default.
# 2020.01.01 V1.5 @diazlaz - Integrated ADX Trending States and BAR Line
# 2020.01.01 V1.4 @diazlaz - Integrated TTM Trends, modules selection
#                            and added threshold for signals
# 2019.12.31 V1.2 @diazlaz - Integrated FREMA
# 2019.12.30 V1.1 @diazlaz - Labels, Additional Dashboard, Lower Study
# 2019.12.30 V1.0 @diazlaz - Community Ask/Release
#
#LINK
#https://usethinkscript.com/threads/i-request-help-combining-3-indicators-into-1-paintbar-study.1390/
#
#INSTRUCTION
#Here is how I envision the paintbar working:
#When the supertrend indicator is long that would equal +1, when its short -1.
#When the TMO is green that would equal +1. when its red its -1.
#When the TOP Cycle Trader is above zero that would equal +1, when its below zero -1.
#When all 3 indicators are equal to +1 making +3 total the price bars would paint #green.
#When all 3 indicators are equal to -1 making -3 total the price bars would paint red.
#If the combination of all 3 indicators equals anything else, the price bars would #paint gray meaning all 3 indicators were not in agreement.
#
#Now includes: TTM Trend, Super Trend, Frema, TMO, TOP, DMI , BOP, Slim Ribbon and
#ADX as Trending/Non-Trending, Super Trend w/CCI and ATR combo and
#a CCI + TTM squeeze + TTM trend Combo with LONG/SHORT/HOLD signal selection
#based on threshold specified and indicators enabled.
#

declare upper;

#INPUTS
input showLabels = yes;
input PaintBars = yes;
input enableNeutralMACDPainter = no;
input aggregationPeriod = AggregationPeriod.FIVE_MIN;
input threshold = 7;

input enableHA = yes;
input enableHAMTF = yes;
input enableTTM = yes;
input enableSuperTrend = yes;
input enableFrema = yes;
input enableTMO = yes;
input enableSlim = yes;
input enableTOP = yes;
input enableDMI = yes;
input enableBOP = yes;
input enableSuperTrendCCIATR = yes;
input enableCCITTM = yes;

input displace = 0;

#CORE
DefineGlobalColor("CycleLineColor", Color.RED);
DefineGlobalColor("CyclehistColor", Color.BLUE);
DefineGlobalColor("ZeroLineColor", Color.YELLOW);
DefineGlobalColor("Bullish", Color.GREEN);
DefineGlobalColor("Bearish", Color.RED);
DefineGlobalColor("Neutral", Color.MAGENTA); #Color.YELLOW
DefineGlobalColor("Off", Color.DARK_GRAY);
DefineGlobalColor("On", Color.GREEN);
DefineGlobalColor("Sync1", Color.YELLOW);
DefineGlobalColor("Sync2", Color.CYAN);
DefineGlobalColor("Up", Color.GREEN);
DefineGlobalColor("Down", Color.RED);
DefineGlobalColor("NUp", Color.DARK_GREEN);
DefineGlobalColor("NDown", Color.DARK_RED);
DefineGlobalColor("Neutral", Color.BLUE);
DefineGlobalColor("Neutral2", Color.PLUM);

def h = high;
def l = low;
def o = open;
def c = close;

def h1 = high(period = aggregationPeriod);
def l1 = low(period = aggregationPeriod);
def o1 = open(period = aggregationPeriod);
def c1 = close(period = aggregationPeriod);

def na = Double.NaN;


AddLabel(showLabels, "A trend, momentum and cycle Trading System v2.0", Color.CYAN);

#HeikinAshiCandles
def HA1open;
def HA1high;
def HA1low;
def HA1close;
HA1open = CompoundValue(1, (HA1open[1] + HA1close[1]) / 2, (o[1] + c[1]) / 2);
HA1high = Max(Max(h, HA1open), HA1close[1]);
HA1low = Min(Min(l, HA1open), HA1close[1]);
HA1close = (o + h + l + c) / 4;
def sHA1 = if HA1close > HA1open then 100 else -100;
def sBullish_HA1 = if(enableHA and sHA1 == 100,1,0);
def sBearish_HA1 = enableHA and sHA1 == -100;
AddLabel(showlabels and enableHA, "HA", if IsNan(sHA1) then COLOR.DARK_GRAY else
if sHA1[-displace] > 0 then COLOR.GREEN else
if sHA1[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#HeikinAshiCandles MTF
def HA2open;
def HA2high;
def HA2low;
def HA2close;
HA2open = CompoundValue(1, (HA2open[1] + HA2close[1]) / 2, (o1[1] + c1[1]) / 2);
HA2high = Max(Max(h1, HA2open), HA2close[1]);
HA2low = Min(Min(l1, HA2open), HA2close[1]);
HA2close = (o1 + h1 + l1 + c1) / 4;
def sHA2 = if HA2close > HA2open then 100 else -100;
def sBullish_HA2 = if(enableHAMTF and sHA2 == 100,1,0);
def sBearish_HA2 = enableHAMTF and sHA2 == -100;
AddLabel(showlabels and enableHAMTF, "HAMTF", if IsNan(sHA2) then COLOR.DARK_GRAY else
if sHA2[-displace] > 0 then COLOR.GREEN else
if sHA2[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

   
#TTM Trend
def TrendUp = if TTM_Trend().TrendUp == 1 then 1 else 0;
def TrendDown = if TTM_Trend().TrendDown == 1 then 1 else 0;
def sTTM = if TrendUp then 100 else if TrendDown then -100 else 0;
def sBullish_TTM = if(enableTTM and sTTM == 100,1,0);
def sBearish_TTM = enableTTM and sTTM == -100;
AddLabel(showlabels and enableTTM, "TTM", if IsNan(sTTM) then COLOR.DARK_GRAY else
if sTTM[-displace] > 0 then COLOR.GREEN else
if sTTM[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#SuperTrend (Mobius)
input AtrMult = 1.0; #SuperTrend
input nATR = 4; #SuperTrend
input AvgType = AverageType.HULL; #SuperTrend

def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR);
def UP = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP else DN;
def sSuperTrend = if close < ST then -100 else 100;
def sBullish_SuperTrend = enableSuperTrend and sSuperTrend == 100;
def sBearish_SuperTrend = enableSuperTrend and sSuperTrend == -100;
AddLabel(showlabels and enableSuperTrend, "SuperTrend", if IsNan(sSuperTrend) then COLOR.DARK_GRAY else
if sSuperTrend[-displace] > 0 then COLOR.GREEN else
if sSuperTrend[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#FREMA
input AA = .1; #FREMA

def CC;
def zeroLine = 0;
def RE1;
def RE2;
def RE3;
def RE4;
def RE5;
def RE6;
def RE7;
def RE8;
def EMA;
CC = if CC[1] == 0 then .9 else 1 – AA;
EMA = AA * close + CC * EMA[1];
RE1 = CC * EMA + EMA[1];
RE2 = Power(CC, 2) * RE1 + RE1[1];
RE3 = Power(CC, 4) * RE2 + RE2[1];
RE4 = Power(CC, 8) * RE3 + RE3[1];
RE5 = Power(CC, 16) * RE4 + RE4[1];
RE6 = Power(CC, 32) * RE5 + RE5[1];
RE7 = Power(CC, 64) * RE6 + RE6[1];
RE8 = Power(CC, 128) * RE7 + RE7[1];
def EMA_Signal = EMA – AA * RE8;
def sFrema = if (EMA_Signal > zeroLine) then 100 else -100;
def sBullish_Frema = enableFrema and sFrema == 100;
def sBearish_Frema = enableFrema and sFrema == -100;
AddLabel(showlabels and enableFrema, "Frema", if IsNan(sFrema) then COLOR.DARK_GRAY else
if sFrema[-displace] > 0 then COLOR.GREEN else
if sFrema[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#TMO
input length = 14; #TMO
input calcLength = 5; #TMO
input smoothLength = 3; #TMO

def data = fold i = 0 to length
           with s
           do s + (if c > getValue(o, i)
                   then 1
                   else if c < getValue(o, i)
                        then - 1
                        else 0);
def EMA5 = ExpAverage(data, calcLength);
def Main = ExpAverage(EMA5, smoothLength);
def Signal = ExpAverage(Main, smoothLength);
def sMain = if Main > Signal then 100 else -100;
def sSignal = if Main > Signal then 100 else - 100;
def ob = if isNaN(c) then double.nan else round(length * .7);
def os = if isNaN(c) then double.nan else -round(length * .7);
def sTMO = if Main > Signal then 100 else -100;
def sBullish_TMO = enableTMO and sTMO == 100;
def sBearish_TMO = enableTMO and sTMO == -100;
AddLabel(showlabels and enableTMO, "TMO", if IsNan(sTMO) then COLOR.DARK_GRAY else
if sTMO[-displace] > 0 then COLOR.GREEN else
if sTMO[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#SLIM
input sSuperFast = 8;
input sFast = 13;
input sSlow = 21;

def SuperFastM1 = ExpAverage(close[-displace], sSuperFast);
def FastM1 = ExpAverage(close[-displace], sFast);
def SlowM1 = ExpAverage(close[-displace], sSlow);
def buyM1 = SuperFastM1 > FastM1 and FastM1 > SlowM1 and low > SuperFastM1;
def stopbuyM1 = SuperFastM1 <= FastM1;
def buynowM1 = !buyM1[1] and buyM1;
def buysignalM1 = CompoundValue(1, if buynowM1 and !stopbuyM1 then 1
else if buysignalM1[1] == 1 and stopbuyM1 then 0 else buysignalM1[1], 0);
def Buy_SignalM1 = buysignalM1[1] == 0 and buysignalM1 == 1;
def Momentum_DownM1 = buysignalM1[1] == 1 and buysignalM1 == 0;
def sellM1 = SuperFastM1 < FastM1 and FastM1 < SlowM1 and high < SuperFastM1;
def stopsellM1 = SuperFastM1 >= FastM1;
def sellnowM1 = !sellM1[1] and sellM1;
def sellsignalM1 = CompoundValue(1, if sellnowM1 and !stopsellM1 then 1
else if sellsignalM1[1] == 1 and stopsellM1 then 0 else sellsignalM1[1], 0);
def Sell_SignalM1 = sellsignalM1[1] == 0 and sellsignalM1;
def Momentum_UpM1 = sellsignalM1[1] == 1 and sellsignalM1 == 0;
def sStateM1 = if Buy_SignalM1 then 100 else if Momentum_UpM1 then 10 else if Sell_SignalM1 then -100 else if Momentum_DownM1 then -10 else sStateM1[1];
def sBullish_SLIM = enableSLIM and sStateM1 == 100;
def sBearish_SLIM = enableSLIM and sStateM1 == -100;
AddLabel(showlabels and enableSLIM, "SLIM", if IsNan(sStateM1) then COLOR.DARK_GRAY else
if sStateM1[-displace] >= 100 then COLOR.GREEN else
if sStateM1[-displace] <= -100 then COLOR.RED
else COLOR.YELLOW);

#TOP Cycle Trader
input FastCycleLength = 5; #TOP
input SlowCycleLength = 8; #TOP

def FastVar = ExpAverage((H + L) / 2, FastCycleLength);
def SlowVar = Average((H + L) / 2, SlowCycleLength);
def DiffVar = FastVar - SlowVar;
def pDiffVar = DiffVar;
def pDiffVar2 = DiffVar;
def sTOP = if DiffVar > 0 then 100 else -100;
def sBullish_TOP = enableTOP and sTOP == 100;
def sBearish_TOP = enableTOP and sTOP == -100;
AddLabel(showlabels and enableTOP, "TOP", if IsNan(sTOP) then COLOR.DARK_GRAY else
if sTOP[-displace] > 0 then COLOR.GREEN else
if sTOP[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#DMITrend
input DMIlength = 13;

def hiDiff = high - high[1];
def loDiff = low[1] - low;
def plusDM = if hiDiff > loDiff and hiDiff > 0 then hiDiff else 0;
def minusDM =  if loDiff > hiDiff and loDiff > 0 then loDiff else 0;
def ATRDMI = WildersAverage(TrueRange(high, close, low), DMIlength);
Def DIPlus = 100 * WildersAverage(plusDM, DMIlength) / ATRDMI;
Def DIMinus = 100 * WildersAverage(minusDM, DMIlength) / ATRDMI;
def sDMI = if DIPlus > DIMinus then 100 else if DIMinus > DIPlus then -100 else 0;
def sBullish_DMI = enableDMI and sDMI == 100;
def sBearish_DMI = enableDMI and sDMI == -100;
AddLabel(showlabels and enableDMI, "DMI", if IsNan(sDMI) then COLOR.DARK_GRAY else
if sDMI[-displace] > 0 then COLOR.GREEN else
if sDMI[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#BOP indicator
input averageType = {Simple, Exponential, default Weighted, Wilders, Hull,  Disabled};
input BoPlength = 16;

def rawBMP = if high != low then (close - open) / (high - low) else 1;
def BMP;
switch (averageType) {
case Simple:
    BMP = Average(rawBMP, BoPlength);
case Exponential:
    BMP = ExpAverage(rawBMP, BoPlength);
case Weighted:
    BMP = wma(rawBMP, BoPlength);
case Wilders:
    BMP = WildersAverage(rawBMP, BoPlength);
case Hull:
    BMP = HullMovingAvg(rawBMP, BoPlength);
case Disabled:
    BMP = rawBMP;
}
def sBOP = if BMP > 0 then 100 else -100;
def sBullish_BOP = enableBOP and sBOP == 100;
def sBearish_BOP = enableBOP and sBOP == -100;
AddLabel(showlabels and enableBOP, "BOP", if IsNan(sBOP) then COLOR.DARK_GRAY else
if sBOP[-displace] > 0 then COLOR.GREEN else
if sBOP[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));


# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED
input lengthCCI = 50;
input lengthATR = 21;
input AtrFactor = 1.0;
def pricedata = hl2;
def ATRcci = Average(TrueRange(h, c, l), lengthATR) * AtrFactor;
def price = c + l + h;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
          then 0
          else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
          then Max(MT1[1], pricedata - ATRcci)
          else Min(MT1[1], pricedata + ATRcci);
def sSuperTrendCCIATR = if c < MT1 and c < ST then -100 else if C > MT1 and c >ST then 100 else 0;
def sBullish_SuperTrendCCIATR = enableSuperTrendCCIATR and sSuperTrendCCIATR == 100;
def sBearish_SuperTrendCCIATR = enableSuperTrendCCIATR and sSuperTrendCCIATR == -100;
AddLabel(showlabels and enableSuperTrendCCIATR, "SuperTrendCCI", if IsNan(sSuperTrendCCIATR) then COLOR.DARK_GRAY else
if sSuperTrendCCIATR[-displace] > 0 then COLOR.GREEN else
if sSuperTrendCCIATR[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));


# CCI + TTM squeeze + TTM trend
def CCIBuy = CCI(length = 14).CCI > 0 and CCI(length = 50).CCI > 0;
def CCISell = CCI(length = 14).CCI < 0 and CCI(length = 50).CCI < 0;
def sTrendUp = TTM_Trend().TrendUp;
def sTrendDn = TTM_Trend().TrendDown;
def SqueezeUp = TTM_Squeeze().Histogram >= 0;
def SqueezeDn = TTM_Squeeze().Histogram <= 0;
def Buy = CCIBuy and sTrendUp and SqueezeUp;
def Sell = CCISell and sTrendDn and SqueezeDn;
def sCCITTM = if buy then 100 else if sell then -100 else 0;
def sBullish_CCITTM = enableCCITTM and sCCITTM == 100;
def sBearish_CCITTM = enableCCITTM and sCCITTM == -100;
AddLabel(showlabels and enableCCITTM, "TTM CCI", if IsNan(sCCITTM) then COLOR.DARK_GRAY else
if sCCITTM[-displace] > 0 then COLOR.GREEN else
if sCCITTM[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#ADX TRENDING
input ADXlength = 8; #ADX
input ADXTrending = 25; #ADX
input showADXBar = yes;

def ADX = DMI(ADXlength).ADX;
plot ADXCross = LowestAll(low);
ADXCross.SetPaintingStrategy(PaintingStrategy.LINE);
ADXCross.AssignValueColor(
    if ADX > ADXTrending then Color.LIME
    else Color.DARK_GRAY);
ADXCross.SetLineWeight(5);
ADXCross.SetHiding(!showADXBar);

#MACD Neutal Eval
input fastLength_1 = 12;
input slowLength_1 = 26;
input MACDLength_1 = 9;
input AverageType_1 = {SMA, default EMA};
def macd_Val_1 = MACD(fastLength_1, slowLength_1, MACDLength_1, AverageType_1).Value;
def macd_Avg1 = MACD(fastLength_1, slowLength_1, MACDLength_1, AverageType_1).Avg;
def MACD_trig = if MACD().value > MACD().avg then 1 else 0;

AddLabel(showlabels,
if ADX > ADXTrending then "Trending" else
"Non Trending",
if IsNan(c) then COLOR.DARK_GRAY else
if ADX > ADXTrending then COLOR.GREEN else
COLOR.DARK_GRAY);

AddLabel(showlabels,
"MACD",
if IsNan(c) then COLOR.DARK_GRAY else
if macd_Val_1 > macd_Avg1 then COLOR.DARK_GREEN else
COLOR.DARK_RED);

#STATE
def sResults = sHA1 + sHA2 + sSuperTrend + sTMO + sTOP + sFrema + sTTM + sDMI + sBOP + sStateM1;
def sBullish = sBullish_HA1 + sBullish_HA2 + sBullish_TTM + sBullish_SuperTrend + sBullish_Frema + sBullish_TMO + sBullish_TOP + sBullish_DMI + sBullish_BOP + sBullish_SLIM + sBullish_SuperTrendCCIATR + sBullish_CCITTM;
def sBearish = sBearish_HA1 + sBearish_HA2 + sBearish_TTM + sBearish_SuperTrend + sBearish_Frema + sBearish_TMO + sBearish_TOP + sBearish_DMI + sBearish_BOP + sBearish_SLIM + sBearish_SuperTrendCCIATR + sBearish_CCITTM;
def bullish = if(sBullish >= threshold,1,0);
def bearish = if(sBearish >= threshold,1,0);
def sState = if bullish then 100 else if bearish then -100 else 0;
def sState2 = if sState != 0 then sState else sState2[1];

#COLORBARS
AssignPriceColor(
if PaintBars then
    if bullish then COLOR.GREEN else if bearish then COLOR.RED
     else
     if enableNeutralMACDPainter then
      if macd_Val_1 > macd_Avg1 then COLOR.DARK_GREEN else COLOR.DARK_RED
     else
    COLOR.GRAY
else COLOR.CURRENT);

AddLabel(showlabels,
if bullish[-displace] then "LONG" else
if bearish[-displace] then "SHORT"
else "HOLD",
if IsNan(c) then COLOR.DARK_GRAY else
if bullish[-displace] then COLOR.GREEN else
if bearish[-displace] then COLOR.RED
else COLOR.GRAY);

#END OF trend, a momentum and a cycle based indicator for ThinkorSwim V2.0
 
@diazlaz is the 2.0 version also include the Mobius version of Heikin Ashi SuperTrend from post #114? or just regular Heikin Ashi with MTF? TOS down on my end today so I can't test but it looks like its a regular version from the script.
 
Last edited:
Here is release 2.1 - integrates Supertrend with HA Candles

Ruby:
#trend, a momentum and a cycle based indicator for ThinkorSwim V2.1
#@hockeycoachdoug Community Request
#
#VERSION
# 2020.01.18 V2.1 @diazlaz - Integrated SuperTrend with HeikinAshiCandles
# 2020.01.17 V2.0 @diazlaz - Integrated HeikinAshiCandles and HeikinAshiCandles MTF
#                          - set aggregationPeriod to MTF aggregation (default 5 mins)
# 2020.01.09 V1.9 @diazlaz - Integrated PaintBars MACD Neutral Condition trigger
#                          - set enableNeutralMACDPainter to yes (default is no) and
#                          - neutral gray will be evaluated by MACD (Dark Red/Green)
# 2020.01.09 V1.8 @diazlaz - Integrated Super Trend w/CCI and ATR
#                          - Integrated CCI + TTM squeeze + TTM trend Combo
#                          - Set treshold defaults to 7 (7 out of 10), removed scanmode.
# 2020.01.04 V1.7 @diazlaz - Integrated Slim Ribbon.
# 2020.01.02 V1.6 @diazlaz - Integrated DMI and BOP, restructured INPUTS to each module.
#                            threshold increased to 4 by default.
# 2020.01.01 V1.5 @diazlaz - Integrated ADX Trending States and BAR Line
# 2020.01.01 V1.4 @diazlaz - Integrated TTM Trends, modules selection
#                            and added threshold for signals
# 2019.12.31 V1.2 @diazlaz - Integrated FREMA
# 2019.12.30 V1.1 @diazlaz - Labels, Additional Dashboard, Lower Study
# 2019.12.30 V1.0 @diazlaz - Community Ask/Release
#
#LINK
#https://usethinkscript.com/threads/i-request-help-combining-3-indicators-into-1-paintbar-study.1390/
#
#INSTRUCTION
#Here is how I envision the paintbar working:
#When the supertrend indicator is long that would equal +1, when its short -1.
#When the TMO is green that would equal +1. when its red its -1.
#When the TOP Cycle Trader is above zero that would equal +1, when its below zero -1.
#When all 3 indicators are equal to +1 making +3 total the price bars would paint #green.
#When all 3 indicators are equal to -1 making -3 total the price bars would paint red.
#If the combination of all 3 indicators equals anything else, the price bars would #paint gray meaning all 3 indicators were not in agreement.
#
#Now includes: TTM Trend, Super Trend, Frema, TMO, TOP, DMI , BOP, Slim Ribbon and
#ADX as Trending/Non-Trending, Super Trend w/CCI and ATR combo and
#a CCI + TTM squeeze + TTM trend Combo with LONG/SHORT/HOLD signal selection
#based on threshold specified and indicators enabled.
#

declare upper;

#INPUTS
input showLabels = yes;
input PaintBars = yes;
input enableNeutralMACDPainter = no;
input aggregationPeriod = AggregationPeriod.FIVE_MIN;
input threshold = 7;

input enableHA = yes;
input enableHAMTF = yes;
input enableTTM = yes;
input enableSuperTrend = yes;
input enableSuperTrendHA = yes;
input enableFrema = yes;
input enableTMO = yes;
input enableSlim = yes;
input enableTOP = yes;
input enableDMI = yes;
input enableBOP = yes;
input enableSuperTrendCCIATR = yes;
input enableCCITTM = yes;

input displace = 0;

#CORE
DefineGlobalColor("CycleLineColor", Color.RED);
DefineGlobalColor("CyclehistColor", Color.BLUE);
DefineGlobalColor("ZeroLineColor", Color.YELLOW);
DefineGlobalColor("Bullish", Color.GREEN);
DefineGlobalColor("Bearish", Color.RED);
DefineGlobalColor("Neutral", Color.MAGENTA); #Color.YELLOW
DefineGlobalColor("Off", Color.DARK_GRAY);
DefineGlobalColor("On", Color.GREEN);
DefineGlobalColor("Sync1", Color.YELLOW);
DefineGlobalColor("Sync2", Color.CYAN);
DefineGlobalColor("Up", Color.GREEN);
DefineGlobalColor("Down", Color.RED);
DefineGlobalColor("NUp", Color.DARK_GREEN);
DefineGlobalColor("NDown", Color.DARK_RED);
DefineGlobalColor("Neutral", Color.BLUE);
DefineGlobalColor("Neutral2", Color.PLUM);

def h = high;
def l = low;
def o = open;
def c = close;

def h1 = high(period = aggregationPeriod);
def l1 = low(period = aggregationPeriod);
def o1 = open(period = aggregationPeriod);
def c1 = close(period = aggregationPeriod);

def na = Double.NaN;

AddLabel(showLabels, "A trend, momentum and cycle Trading System v2.1", Color.CYAN);

#HeikinAshiCandles
def HA1open;
def HA1high;
def HA1low;
def HA1close;
HA1open = CompoundValue(1, (HA1open[1] + HA1close[1]) / 2, (o[1] + c[1]) / 2);
HA1high = Max(Max(h, HA1open), HA1close[1]);
HA1low = Min(Min(l, HA1open), HA1close[1]);
HA1close = (o + h + l + c) / 4;
def sHA1 = if HA1close > HA1open then 100 else -100;
def sBullish_HA1 = if(enableHA and sHA1 == 100,1,0);
def sBearish_HA1 = enableHA and sHA1 == -100;
AddLabel(showlabels and enableHA, "HA", if IsNan(sHA1) then COLOR.DARK_GRAY else
if sHA1[-displace] > 0 then COLOR.GREEN else
if sHA1[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#HeikinAshiCandles MTF
def HA2open;
def HA2high;
def HA2low;
def HA2close;
HA2open = CompoundValue(1, (HA2open[1] + HA2close[1]) / 2, (o1[1] + c1[1]) / 2);
HA2high = Max(Max(h1, HA2open), HA2close[1]);
HA2low = Min(Min(l1, HA2open), HA2close[1]);
HA2close = (o1 + h1 + l1 + c1) / 4;
def sHA2 = if HA2close > HA2open then 100 else -100;
def sBullish_HA2 = if(enableHAMTF and sHA2 == 100,1,0);
def sBearish_HA2 = enableHAMTF and sHA2 == -100;
AddLabel(showlabels and enableHAMTF, "HAMTF", if IsNan(sHA2) then COLOR.DARK_GRAY else
if sHA2[-displace] > 0 then COLOR.GREEN else
if sHA2[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));
    
#TTM Trend
def TrendUp = if TTM_Trend().TrendUp == 1 then 1 else 0;
def TrendDown = if TTM_Trend().TrendDown == 1 then 1 else 0;
def sTTM = if TrendUp then 100 else if TrendDown then -100 else 0;
def sBullish_TTM = if(enableTTM and sTTM == 100,1,0);
def sBearish_TTM = enableTTM and sTTM == -100;
AddLabel(showlabels and enableTTM, "TTM", if IsNan(sTTM) then COLOR.DARK_GRAY else
if sTTM[-displace] > 0 then COLOR.GREEN else
if sTTM[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#SuperTrend (Mobius)
input AtrMult = 1.0; #SuperTrend
input nATR = 4; #SuperTrend
input AvgType = AverageType.HULL; #SuperTrend

def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR);
def UP = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP else DN;
def sSuperTrend = if close < ST then -100 else 100;
def sBullish_SuperTrend = enableSuperTrend and sSuperTrend == 100;
def sBearish_SuperTrend = enableSuperTrend and sSuperTrend == -100;
AddLabel(showlabels and enableSuperTrend, "SuperTrend", if IsNan(sSuperTrend) then COLOR.DARK_GRAY else
if sSuperTrend[-displace] > 0 then COLOR.GREEN else
if sSuperTrend[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#SuperTrend with HeikinAshiCandles (Mobius)
def ATR2 = MovingAverage(AvgType, TrueRange(ha1high, HA1close, HA1low), nATR);
def UP2 = HL2 + (AtrMult * ATR2);
def DN2 = HL2 + (-AtrMult * ATR2);
def ST2 = if HA1close < ST2[1] then UP2 else DN2;
def sSuperTrend2 = if HA1close < ST2 then -100 else 100;
def sBullish_SuperTrend2 = enableSuperTrendHA and sSuperTrend2 == 100;
def sBearish_SuperTrend2 = enableSuperTrendHA and sSuperTrend2 == -100;
AddLabel(showlabels and enableSuperTrendHA, "SuperTrendHA", if IsNan(sSuperTrend2) then COLOR.DARK_GRAY else
if sSuperTrend2[-displace] > 0 then COLOR.GREEN else
if sSuperTrend2[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#FREMA
input AA = .1; #FREMA

def CC;
def zeroLine = 0;
def RE1;
def RE2;
def RE3;
def RE4;
def RE5;
def RE6;
def RE7;
def RE8;
def EMA;
CC = if CC[1] == 0 then .9 else 1 – AA;
EMA = AA * close + CC * EMA[1];
RE1 = CC * EMA + EMA[1];
RE2 = Power(CC, 2) * RE1 + RE1[1];
RE3 = Power(CC, 4) * RE2 + RE2[1];
RE4 = Power(CC, 8) * RE3 + RE3[1];
RE5 = Power(CC, 16) * RE4 + RE4[1];
RE6 = Power(CC, 32) * RE5 + RE5[1];
RE7 = Power(CC, 64) * RE6 + RE6[1];
RE8 = Power(CC, 128) * RE7 + RE7[1];
def EMA_Signal = EMA – AA * RE8;
def sFrema = if (EMA_Signal > zeroLine) then 100 else -100;
def sBullish_Frema = enableFrema and sFrema == 100;
def sBearish_Frema = enableFrema and sFrema == -100;
AddLabel(showlabels and enableFrema, "Frema", if IsNan(sFrema) then COLOR.DARK_GRAY else
if sFrema[-displace] > 0 then COLOR.GREEN else
if sFrema[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#TMO
input length = 14; #TMO
input calcLength = 5; #TMO
input smoothLength = 3; #TMO

def data = fold i = 0 to length
           with s
           do s + (if c > getValue(o, i)
                   then 1
                   else if c < getValue(o, i)
                        then - 1
                        else 0);
def EMA5 = ExpAverage(data, calcLength);
def Main = ExpAverage(EMA5, smoothLength);
def Signal = ExpAverage(Main, smoothLength);
def sMain = if Main > Signal then 100 else -100;
def sSignal = if Main > Signal then 100 else - 100;
def ob = if isNaN(c) then double.nan else round(length * .7);
def os = if isNaN(c) then double.nan else -round(length * .7);
def sTMO = if Main > Signal then 100 else -100;
def sBullish_TMO = enableTMO and sTMO == 100;
def sBearish_TMO = enableTMO and sTMO == -100;
AddLabel(showlabels and enableTMO, "TMO", if IsNan(sTMO) then COLOR.DARK_GRAY else
if sTMO[-displace] > 0 then COLOR.GREEN else
if sTMO[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#SLIM
input sSuperFast = 8;
input sFast = 13;
input sSlow = 21;

def SuperFastM1 = ExpAverage(close[-displace], sSuperFast);
def FastM1 = ExpAverage(close[-displace], sFast);
def SlowM1 = ExpAverage(close[-displace], sSlow);
def buyM1 = SuperFastM1 > FastM1 and FastM1 > SlowM1 and low > SuperFastM1;
def stopbuyM1 = SuperFastM1 <= FastM1;
def buynowM1 = !buyM1[1] and buyM1;
def buysignalM1 = CompoundValue(1, if buynowM1 and !stopbuyM1 then 1
else if buysignalM1[1] == 1 and stopbuyM1 then 0 else buysignalM1[1], 0);
def Buy_SignalM1 = buysignalM1[1] == 0 and buysignalM1 == 1;
def Momentum_DownM1 = buysignalM1[1] == 1 and buysignalM1 == 0;
def sellM1 = SuperFastM1 < FastM1 and FastM1 < SlowM1 and high < SuperFastM1;
def stopsellM1 = SuperFastM1 >= FastM1;
def sellnowM1 = !sellM1[1] and sellM1;
def sellsignalM1 = CompoundValue(1, if sellnowM1 and !stopsellM1 then 1
else if sellsignalM1[1] == 1 and stopsellM1 then 0 else sellsignalM1[1], 0);
def Sell_SignalM1 = sellsignalM1[1] == 0 and sellsignalM1;
def Momentum_UpM1 = sellsignalM1[1] == 1 and sellsignalM1 == 0;
def sStateM1 = if Buy_SignalM1 then 100 else if Momentum_UpM1 then 10 else if Sell_SignalM1 then -100 else if Momentum_DownM1 then -10 else sStateM1[1];
def sBullish_SLIM = enableSLIM and sStateM1 == 100;
def sBearish_SLIM = enableSLIM and sStateM1 == -100;
AddLabel(showlabels and enableSLIM, "SLIM", if IsNan(sStateM1) then COLOR.DARK_GRAY else
if sStateM1[-displace] >= 100 then COLOR.GREEN else
if sStateM1[-displace] <= -100 then COLOR.RED
else COLOR.YELLOW);

#TOP Cycle Trader
input FastCycleLength = 5; #TOP
input SlowCycleLength = 8; #TOP

def FastVar = ExpAverage((H + L) / 2, FastCycleLength);
def SlowVar = Average((H + L) / 2, SlowCycleLength);
def DiffVar = FastVar - SlowVar;
def pDiffVar = DiffVar;
def pDiffVar2 = DiffVar;
def sTOP = if DiffVar > 0 then 100 else -100;
def sBullish_TOP = enableTOP and sTOP == 100;
def sBearish_TOP = enableTOP and sTOP == -100;
AddLabel(showlabels and enableTOP, "TOP", if IsNan(sTOP) then COLOR.DARK_GRAY else
if sTOP[-displace] > 0 then COLOR.GREEN else
if sTOP[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#DMITrend
input DMIlength = 13;

def hiDiff = high - high[1];
def loDiff = low[1] - low;
def plusDM = if hiDiff > loDiff and hiDiff > 0 then hiDiff else 0;
def minusDM =  if loDiff > hiDiff and loDiff > 0 then loDiff else 0;
def ATRDMI = WildersAverage(TrueRange(high, close, low), DMIlength);
Def DIPlus = 100 * WildersAverage(plusDM, DMIlength) / ATRDMI;
Def DIMinus = 100 * WildersAverage(minusDM, DMIlength) / ATRDMI;
def sDMI = if DIPlus > DIMinus then 100 else if DIMinus > DIPlus then -100 else 0;
def sBullish_DMI = enableDMI and sDMI == 100;
def sBearish_DMI = enableDMI and sDMI == -100;
AddLabel(showlabels and enableDMI, "DMI", if IsNan(sDMI) then COLOR.DARK_GRAY else
if sDMI[-displace] > 0 then COLOR.GREEN else
if sDMI[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#BOP indicator
input averageType = {Simple, Exponential, default Weighted, Wilders, Hull,  Disabled};
input BoPlength = 16;

def rawBMP = if high != low then (close - open) / (high - low) else 1;
def BMP;
switch (averageType) {
case Simple:
    BMP = Average(rawBMP, BoPlength);
case Exponential:
    BMP = ExpAverage(rawBMP, BoPlength);
case Weighted:
    BMP = wma(rawBMP, BoPlength);
case Wilders:
    BMP = WildersAverage(rawBMP, BoPlength);
case Hull:
    BMP = HullMovingAvg(rawBMP, BoPlength);
case Disabled:
    BMP = rawBMP;
}
def sBOP = if BMP > 0 then 100 else -100;
def sBullish_BOP = enableBOP and sBOP == 100;
def sBearish_BOP = enableBOP and sBOP == -100;
AddLabel(showlabels and enableBOP, "BOP", if IsNan(sBOP) then COLOR.DARK_GRAY else
if sBOP[-displace] > 0 then COLOR.GREEN else
if sBOP[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));


# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED
input lengthCCI = 50;
input lengthATR = 21;
input AtrFactor = 1.0;
def pricedata = hl2;
def ATRcci = Average(TrueRange(h, c, l), lengthATR) * AtrFactor;
def price = c + l + h;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
          then 0
          else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
          then Max(MT1[1], pricedata - ATRcci)
          else Min(MT1[1], pricedata + ATRcci);
def sSuperTrendCCIATR = if c < MT1 and c < ST then -100 else if C > MT1 and c >ST then 100 else 0;
def sBullish_SuperTrendCCIATR = enableSuperTrendCCIATR and sSuperTrendCCIATR == 100;
def sBearish_SuperTrendCCIATR = enableSuperTrendCCIATR and sSuperTrendCCIATR == -100;
AddLabel(showlabels and enableSuperTrendCCIATR, "SuperTrendCCI", if IsNan(sSuperTrendCCIATR) then COLOR.DARK_GRAY else
if sSuperTrendCCIATR[-displace] > 0 then COLOR.GREEN else
if sSuperTrendCCIATR[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));


# CCI + TTM squeeze + TTM trend
def CCIBuy = CCI(length = 14).CCI > 0 and CCI(length = 50).CCI > 0;
def CCISell = CCI(length = 14).CCI < 0 and CCI(length = 50).CCI < 0;
def sTrendUp = TTM_Trend().TrendUp;
def sTrendDn = TTM_Trend().TrendDown;
def SqueezeUp = TTM_Squeeze().Histogram >= 0;
def SqueezeDn = TTM_Squeeze().Histogram <= 0;
def Buy = CCIBuy and sTrendUp and SqueezeUp;
def Sell = CCISell and sTrendDn and SqueezeDn;
def sCCITTM = if buy then 100 else if sell then -100 else 0;
def sBullish_CCITTM = enableCCITTM and sCCITTM == 100;
def sBearish_CCITTM = enableCCITTM and sCCITTM == -100;
AddLabel(showlabels and enableCCITTM, "TTM CCI", if IsNan(sCCITTM) then COLOR.DARK_GRAY else
if sCCITTM[-displace] > 0 then COLOR.GREEN else
if sCCITTM[-displace] < 0 then COLOR.RED
else GlobalColor("Off"));

#ADX TRENDING
input ADXlength = 8; #ADX
input ADXTrending = 25; #ADX
input showADXBar = yes;

def ADX = DMI(ADXlength).ADX;
plot ADXCross = LowestAll(low);
ADXCross.SetPaintingStrategy(PaintingStrategy.LINE);
ADXCross.AssignValueColor(
    if ADX > ADXTrending then Color.LIME
    else Color.DARK_GRAY);
ADXCross.SetLineWeight(5);
ADXCross.SetHiding(!showADXBar);

#MACD Neutal Eval
input fastLength_1 = 12;
input slowLength_1 = 26;
input MACDLength_1 = 9;
input AverageType_1 = {SMA, default EMA};
def macd_Val_1 = MACD(fastLength_1, slowLength_1, MACDLength_1, AverageType_1).Value;
def macd_Avg1 = MACD(fastLength_1, slowLength_1, MACDLength_1, AverageType_1).Avg;
def MACD_trig = if MACD().value > MACD().avg then 1 else 0;

AddLabel(showlabels,
if ADX > ADXTrending then "Trending" else
"Non Trending",
if IsNan(c) then COLOR.DARK_GRAY else
if ADX > ADXTrending then COLOR.GREEN else
COLOR.DARK_GRAY);

AddLabel(showlabels,
"MACD",
if IsNan(c) then COLOR.DARK_GRAY else
if macd_Val_1 > macd_Avg1 then COLOR.DARK_GREEN else
COLOR.DARK_RED);

#STATE
def sResults = sHA1 + sHA2 + sSuperTrend + sTMO + sTOP + sFrema + sTTM + sDMI + sBOP + sStateM1 + sSuperTrend2;

def sBullish = sBullish_HA1 + sBullish_HA2 + sBullish_TTM + sBullish_SuperTrend + sBullish_Frema + sBullish_TMO + sBullish_TOP + sBullish_DMI + sBullish_BOP + sBullish_SLIM + sBullish_SuperTrendCCIATR + sBullish_CCITTM +
sBullish_SuperTrend2;

def sBearish = sBearish_HA1 + sBearish_HA2 + sBearish_TTM + sBearish_SuperTrend + sBearish_Frema + sBearish_TMO + sBearish_TOP + sBearish_DMI + sBearish_BOP + sBearish_SLIM + sBearish_SuperTrendCCIATR + sBearish_CCITTM +
sBearish_SuperTrend2;

def bullish = if(sBullish >= threshold,1,0);
def bearish = if(sBearish >= threshold,1,0);
def sState = if bullish then 100 else if bearish then -100 else 0;
def sState2 = if sState != 0 then sState else sState2[1];

#COLORBARS
AssignPriceColor(
if PaintBars then
    if bullish then COLOR.GREEN else if bearish then COLOR.RED
     else
     if enableNeutralMACDPainter then
      if macd_Val_1 > macd_Avg1 then COLOR.DARK_GREEN else COLOR.DARK_RED
     else
    COLOR.GRAY
else COLOR.CURRENT);

AddLabel(showlabels,
if bullish[-displace] then "LONG" else
if bearish[-displace] then "SHORT"
else "HOLD",
if IsNan(c) then COLOR.DARK_GRAY else
if bullish[-displace] then COLOR.GREEN else
if bearish[-displace] then COLOR.RED
else COLOR.GRAY);

#END OF trend, a momentum and a cycle based indicator for ThinkorSwim V2.1
 
Here is the strategy portion, copy the latest version and append the following code to make it into a strategy. please remember threshold, the indicators that are enabled and the MACD neutral evaluation and timeframes all will effect the strategy in the back test.

The strategy will go long and short on the positions leveraging the auto buy and sell auto order. please share your results and findings. Have fun this long holiday weekend testing various combinations.

oHQZdij.png


Ruby:
#STRATEGY
def SS = if bullish then 100 else if bearish then -100 else if enableNeutralMACDPainter
then if macd_Val_1 > macd_Avg1 then 10 else -10 else 0;

def sBuy = SS crosses above 0;
def sSell = SS crosses below 0;

AddOrder(OrderType.BUY_AUTO, condition = Sbuy
, price =  open[-1], 1000, tickcolor = Color.GREEN, arrowcolor = Color.GREEN, name = "BE");

AddOrder(OrderType.SELL_AUTO, condition = sSell
, price = open[-1], 1000, tickcolor = Color.RED, arrowcolor = Color.RED, name = "SE");
 
@diazlaz for your next version can you please incorporate the following Heikin Ashi:

Townsend MTF Heikin Ashi so that users can change what timeframe they want. I found that on a 5 min chart a 10 min Heikin Ashi works great with less fake outs...but that could also be attributed to the equities I trade.

Code:
## Heiken Aski Multi-Time Frame
## 2019 Paul Townsend v3

input UsePeriod = aggregationperiod.ten_MIN;

def aOpen = open(period = usePeriod);
def aClose = close(period = usePeriod);
def aHigh = high(period = usePeriod);
def aLow = low(period = usePeriod);

def haClose = (aOpen + aClose + aHigh + aLow)/4;
def haOpen = (haOpen[1] + haClose[1]) /2;

assignpriceColor(if haOpen < haClose then color.green else
if haOpen > haClose then color.red else color.white);

addlabel(yes,"[" + useperiod/60000 + "]",color.white);

Mobius Heikin Ashi SuperTrend:

Code:
# Mobius
# SuperTrend HeikenAshi
# Chat Room Request
# V03.10.2015
# Up = (HIGH + LOW) / 2 + Multiplier * ATR
# Down = (HIGH + LOW) / 2 – Multiplier * ATR
# When the change of trend occurs, the indicator flips

# For RP: Add AR trend, Aberrant Vol, R State, PTR

input AtrMult = .70;
input nATR = 4;
input AvgType = AverageType.HULL;
input PaintBars = yes;
input BubbleOn = no;
input ShowLabel = no;
input AlertOn = no;
input PlotLine = no;

def HAopen;
def HAhigh;
def HAlow;
def HAclose;
HAopen = CompoundValue(1, (haopen[1] + haclose[1]) / 2, (open[1] + close) / 2);
HAhigh = Max(high, close[1]);
HAlow = Min(low, close[1]);
haclose = (HAopen + HAclose[1] + HAlow + close) / 4;
def v = volume;
def bar = barNumber();
def EOD = if SecondsTillTime(1545) == 0 and
             SecondsFromTime(1545) == 0
          then 1
          else 0;
def NotActive = if SecondsFromTime(1545) > 0
                then 1
                else 0;
def ATR = MovingAverage(AvgType, TrueRange(HAhigh, HAclose, HAlow), nATR);
def UP = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1]
         then Round(UP / tickSize(), 0) * tickSize()
         else Round(DN / tickSize(), 0) * tickSize();
plot SuperTrend = ST;
SuperTrend.SetHiding(!PlotLine);
SuperTrend.AssignValueColor(if close < ST then Color.RED else Color.GREEN);
SuperTrend.SetPaintingStrategy(PaintingStrategy.Line);
AssignPriceColor(if PaintBars and close < ST
                 then Color.RED
                 else if PaintBars and close > ST
                      then Color.GREEN
                      else Color.CURRENT);
plot ST_point = if isNaN(close[-1])
                then ST
                else double.nan;
ST_point.SetStyle(Curve.Points);
ST_point.SetLineWeight(3);
ST_point.SetDefaultColor(Color.Yellow);
# End Code SuperTrend HeikenAshi

Schaff Trend Cycle:

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2015-2019
#

declare lower;

input fastLength = 23;
input slowLength = 50;
input KPeriod = 10;
input DPeriod = 3;
input over_bought = 75;
input over_sold = 25;
input averageType = AverageType.EXPONENTIAL;

def macd = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def fastK1 = FastKCustom(macd, KPeriod);
def fastD1 = MovingAverage(averageType, fastK1, DPeriod);
def fastK2 = FastKCustom(fastD1, KPeriod);
plot STC = MovingAverage(averageType, fastK2, DPeriod);
plot OverBought = over_bought;
plot OverSold = over_sold;

STC.SetDefaultColor(GetColor(8));
OverBought.SetDefaultColor(GetColor(7));
OverSold.SetDefaultColor(GetColor(7));

@HighBredCloud, on the Schaff Trend Cycle: what is the logic you suggest for bullish or bearish behavior? over, crossing over bought or over sold?
 
@diazlaz I have a script for the Schaff Trend and Schaff wave trend...for the logic that you asked to incorporate I suggest the Schaff STC Wave and AvgExpWave ONLY from the script below...IF you can make the logic work based on the Schaff Wave crossing over the AvgExpWave that would trigger bullish or bearish condition that would be great...Not sure if anything else is useful. Up to you. Once again thank you for your hard work on this study.

For the rest of you interested in this indicator...it works very well and keeps you in trend.

Code:
#STSW = Schaff Trend Line and Schaff Wave Line
#Schaff Trend Line = Used for quick up/down trend declaration
#Schaff Wave Line = Trade Wave in the direction of trend as
#declared by Trend Line.
#Schaff Wave Line can be used alone to enter trend
#declared by the MACD.
#Schaff Wave can be used with the EMA for signals

declare lower;

input fastLengthTrend = 48;
input slowLengthTrend = 104;
input KPeriodTrend = 36;
input DPeriodTrend = 8;
input averageTypeTrend = AverageType.EXPONENTIAL;
input fastLengthWave = 12;
input slowLengthWave = 26;
input KPeriodWave = 9;
input DPeriodWave = 2;
input over_bought = 75;
input over_sold = 25;
input averageTypeWave = AverageType.EXPONENTIAL;

def macdTrend = MovingAverage(averageTypeTrend, close, fastLengthTrend) - MovingAverage(averageTypeTrend, close, slowLengthTrend);
def macdWave = MovingAverage(averageTypeWave, close, fastLengthWave) - MovingAverage(averageTypeWave, close, slowLengthWave);
def fastK1Trend = FastKCustom(macdTrend, KPeriodTrend);
def fastK1Wave = FastKCustom(macdWave, KPeriodWave);
def fastD1Trend = MovingAverage(averageTypeTrend, fastK1Trend, DPeriodTrend);
def fastD1Wave = MovingAverage(averageTypeWave, fastK1Wave, DPeriodWave);
def fastK2Trend = FastKCustom(fastD1Trend, KPeriodTrend);
def fastK2Wave = FastKCustom(fastD1Wave, KPeriodWave);
plot STCTrend = MovingAverage(averageTypeTrend, fastK2Trend, DPeriodTrend);
plot STCWave = MovingAverage(averageTypeWave, fastK2Wave, DPeriodWave);
plot OverBought = over_bought;
plot OverSold = over_sold;

STCTrend.SetDefaultColor(GetColor(8));
STCWave.SetDefaultColor(GetColor(8));
OverBought.SetDefaultColor(GetColor(7));
OverSold.SetDefaultColor(GetColor(7));

plot Fifty_Line = 50;
fifty_line.SetDefaultColor(GetColor(8));
fifty_line.HideTitle();
fifty_line.SetStyle(Curve.SHORT_DASH);

STCTrend.DefineColor("Up", GetColor(1));
STCTrend.DefineColor("Down", GetColor(0));
STCTrend.AssignValueColor(if STCTrend > STCTrend[1] then STCTrend.Color("Up") else STCTrend.Color("Down"));
STCWave.DefineColor("Up", GetColor(1));
STCWave.DefineColor("Down", GetColor(0));
STCWave.AssignValueColor(if STCWave > STCWave[1] then STCWave.Color("Up") else STCWave.Color("Down"));

input lengthWave = 10;
plot AvgExpWave = ExpAverage(STCWave, lengthWave);
AvgExpWave.SetDefaultColor(GetColor(1));
#
# Polarity

# v0.01

# 6.2.19

# Nube 

#hint: This study calculates a CCI from an average of high and low pivot prices then uses that CCI and a user defined number of deviations to determine polarity. A cross above +deviations or cross below -devations signals a polarity change

 

# subscript for calculating the mean of pivot prices

script pivotMean{ 

input pivotN = 4;

input stochasticN = 21;

def h = high; 

def l = low;

def norm = (close - Lowest(l, pivotN)) /

(Highest(h, pivotN) - Lowest(l, pivotN));

 

## Pivot High

def hh = if norm crosses above .5

then h

else if h > hh[1]

then h

else hh[1];

def hpBar = if h == hh

then BarNumber() 

else Double.NaN;

def hpPrice = if !IsNaN(hpBar) 

then h 

else hpPrice[1]; 

 

## Pivot Low

def ll = if norm crosses below .5

then l

else if l < ll[1]

then l

else ll[1];

def lpBar = if l == ll 

then BarNumber()

else Double.NaN;

def lpPrice = if !IsNaN(lpBar) 

then l 

else lpPrice[1];

 

plot 

pivotMean = Average((hpPrice + lpPrice) / 2, stochasticN);

}

 

# Inputs

input pivotLength = 4; #hint pivotLength: Number of bars for stochastic pivot calcuation

input meanLength = 21; #hint meanLength: Number of bars to calculate mean

input deviations = 1.0;#hint deviations: Number of deviations from mean to signal a polarity change

 

# Variables

def mean   = pivotMean(pivotLength, meanLength);

def linDev = lindev(close, meanLength);

def cci    = (close - mean) / linDev;

 

def polarity_;

if cci crosses above deviations{

polarity_ = 1;

}else

if cci crosses below -deviations{

polarity_ = -1; 

}else{

polarity_ = polarity_[1];

}

 

# Plots

plot 

Polarity = polarity_;

Polarity.AssignValueColor(if polarity_ > 0 then Color.Green else Color.Red);

 

#declare lower;

 

# f/ Polarity
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
524 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