CCI Trend Duration for ThinkorSwim

chewie76

Well-known member
VIP
VIP Enthusiast
This indicator displays the number of bars in your trend. The below code is for the CCI, but you could add any indicator into the code where price is above or below a certain level. For example, in the picture there is a Hull Moving Average and RSI as well as the CCI shown. When the trend is over 10 bars, the color changes indicating that the trend could be getting exhausted. Below is a 4 hour chart of NQ. When all three of these reset at the exact same bar, that indicates a strong new trend. The labels show you how many bars the trend is currently in. This could also help in analyzing the average size of past trend lengths.


1761853660651.png




Code:
#==============================
# CCI Trend Duration (Lower Study)
# Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# CCI
#-----------------------------------

input length = 14;
input price = close;
input cciMid = 0;

# --- CCI Levels ---

def mean = Average(price, length);
def dev = Average(AbsValue(price - mean), length);
def bandMid   = mean + cciMid   * 0.015 * dev;
def CCI  = bandMid;


#-----------------------------------------------
# Trend direction detection
#-----------------------------------------------

def rising = close > CCI;
def falling = close < CCI;

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "CCI_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);
 

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

This indicator displays the number of bars in your trend. The below code is for the CCI, but you could add any indicator into the code where price is above or below a certain level. For example, in the picture there is a Hull Moving Average and RSI as well as the CCI shown. When the trend is over 10 bars, the color changes indicating that the trend could be getting exhausted. Below is a 4 hour chart of NQ. When all three of these reset at the exact same bar, that indicates a strong new trend. The labels show you how many bars the trend is currently in. This could also help in analyzing the average size of past trend lengths.


View attachment 26141



Code:
#==============================
# CCI Trend Duration (Lower Study)
# Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# CCI
#-----------------------------------

input length = 14;
input price = close;
input cciMid = 0;

# --- CCI Levels ---

def mean = Average(price, length);
def dev = Average(AbsValue(price - mean), length);
def bandMid   = mean + cciMid   * 0.015 * dev;
def CCI  = bandMid;


#-----------------------------------------------
# Trend direction detection
#-----------------------------------------------

def rising = close > CCI;
def falling = close < CCI;

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "CCI_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);
Do you have the code for the HMA and RSI?
 
This indicator displays the number of bars in your trend. The below code is for the CCI, but you could add any indicator into the code where price is above or below a certain level. For example, in the picture there is a Hull Moving Average and RSI as well as the CCI shown. When the trend is over 10 bars, the color changes indicating that the trend could be getting exhausted. Below is a 4 hour chart of NQ. When all three of these reset at the exact same bar, that indicates a strong new trend. The labels show you how many bars the trend is currently in. This could also help in analyzing the average size of past trend lengths.


View attachment 26141



Code:
#==============================
# CCI Trend Duration (Lower Study)
# Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# CCI
#-----------------------------------

input length = 14;
input price = close;
input cciMid = 0;

# --- CCI Levels ---

def mean = Average(price, length);
def dev = Average(AbsValue(price - mean), length);
def bandMid   = mean + cciMid   * 0.015 * dev;
def CCI  = bandMid;


#-----------------------------------------------
# Trend direction detection
#-----------------------------------------------

def rising = close > CCI;
def falling = close < CCI;

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "CCI_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);
VERY COOL https://tos.mx/!M7L3x7qU perfect for PSAR it seems - will need to add a momentum code to signal a "slowing" down and label signal potential change near or something like that
Code:
#==============================
# PSAR Trend Duration + ROC Momentum (Lower Study)
#==============================

declare lower;

#-----------------------------------
# PSAR Inputs
#-----------------------------------
input acceleration = 0.02;
input accelerationLimit = 0.2;
input rocLength = 5;   # period for ROC of PSAR

def psar = ParabolicSAR(acceleration, accelerationLimit);

#-----------------------------------------------
# Trend direction detection (using PSAR)
#-----------------------------------------------
def rising = close > psar;
def falling = close < psar;

# Boolean trend signal (1 = up, 0 = down)
rec trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
rec trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.RED);
BearTrendLength.SetLineWeight(2);

# Highlight long-running trends
BullTrendLength.AssignValueColor(if BullTrendLength >= 10 then Color.CYAN else Color.CURRENT);
BearTrendLength.AssignValueColor(if BearTrendLength >= 10 then Color.MAGENTA else Color.CURRENT);

plot signal = 10;
signal.SetDefaultColor(Color.CYAN);

#-----------------------------------
# ROC (Rate of Change) of PSAR for momentum insight
#-----------------------------------
def psarPrev = psar[rocLength];
def rocPSAR = if psarPrev != 0 then ((psar - psarPrev) / psarPrev) * 100 else 0;

# Momentum direction
def rocUp = rocPSAR > 0;
def rocDown = rocPSAR < 0;
def rocNeutral = rocPSAR == 0;

# Momentum strength classification
def strongMomentum = AbsValue(rocPSAR) >= 1;  # tweak threshold as needed

#-----------------------------------
# Heads-up logic
#-----------------------------------
def newUpTrend = trendChange and trendUp;
def newDownTrend = trendChange and !trendUp;
def longBullTrend = trendUp and BullTrendLength >= 10;
def longBearTrend = !trendUp and BearTrendLength >= 10;

#-----------------------------------
# Labels for Quick Interpretation
#-----------------------------------

# Trend phase label
AddLabel(yes,
    if newUpTrend then "NEW UPTREND STARTED"
    else if newDownTrend then "NEW DOWNTREND STARTED"
    else if longBullTrend then "Extended Uptrend (" + trendCount + " bars)"
    else if longBearTrend then "Extended Downtrend (" + trendCount + " bars)"
    else if trendUp then "Uptrend Active (" + trendCount + " bars)"
    else "Downtrend Active (" + trendCount + " bars)",
    if newUpTrend then Color.CYAN
    else if newDownTrend then Color.MAGENTA
    else if trendUp then Color.GREEN
    else Color.RED
);

# ROC Momentum label
AddLabel(yes,
    "PSAR ROC: " + AsText(Round(rocPSAR, 2)) + "%  → " +
    (if rocUp then "Increasing PSAR (Momentum Rising)"
     else if rocDown then "Decreasing PSAR (Momentum Falling)"
     else "Flat Momentum"),
    if rocUp and strongMomentum then Color.GREEN
    else if rocDown and strongMomentum then Color.RED
    else Color.YELLOW
);

# Summary label
AddLabel(yes,
    "Trend: " + (if trendUp then "UP" else "DOWN") +
    " | Bars: " + trendCount +
    " | PSAR: " + AsText(Round(psar, 2)),
    if trendUp then Color.GREEN else Color.RED
);

#-----------------------------------
# Alerts (optional)
#-----------------------------------
Alert(newUpTrend, "PSAR Flip: New UPTREND detected", Alert.BAR, Sound.Ring);
Alert(newDownTrend, "PSAR Flip: New DOWNTREND detected", Alert.BAR, Sound.Bell);
 
Do you have the code for the HMA and RSI?
Here is the Hull Moving Avg.

Code:
#==============================
# HMA Trend Duration (Lower Study)
# # Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# Hull Moving Average
#-----------------------------------

input price = hl2;
input HMA_Length = 28;

def HMA = HullMovingAvg(price = price, length = HMA_Length);

# Trend direction detection
def rising = close > hma; #hma > hma[trendLength];
def falling = close < hma; #hma < hma[trendLength];

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "HMA_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);
 
Do you have the code for the HMA and RSI?
Here is the RSI version.

Code:
#==============================
# RSI Trend Duration (Lower Study)
# Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# RSI
#-----------------------------------

input length = 5;
input price = close;
input smoothingType = {default Wilders, EMA};
input rsiValue2 = 50.0;
input smoothingType2 = {default Wilders, EMA};

def coeff2 = rsiValue2 / (100 - rsiValue2);
def chg2 = price - price[1];
def diff2;
switch (smoothingType2) {
case Wilders:
    diff2 =  (length - 1) * (WildersAverage(Max(-chg2, 0), length) * coeff2 - WildersAverage(Max(chg2, 0), length));
case EMA:
    diff2 =  (length - 1) * (ExpAverage(Max(-chg2, 0), length) * coeff2 - ExpAverage(Max(chg2, 0), length)) / 2;
}

def value2 = price + if diff2 >= 0 then diff2 else diff2 / coeff2;
DEF RSI = compoundValue(1, value2[1], Double.NaN);

# Trend direction detection
def rising = close > RSI;
def falling = close < RSI;

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "RSI_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);
 
Here is the RSI version.

Code:
#==============================
# RSI Trend Duration (Lower Study)
# Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# RSI
#-----------------------------------

input length = 5;
input price = close;
input smoothingType = {default Wilders, EMA};
input rsiValue2 = 50.0;
input smoothingType2 = {default Wilders, EMA};

def coeff2 = rsiValue2 / (100 - rsiValue2);
def chg2 = price - price[1];
def diff2;
switch (smoothingType2) {
case Wilders:
    diff2 =  (length - 1) * (WildersAverage(Max(-chg2, 0), length) * coeff2 - WildersAverage(Max(chg2, 0), length));
case EMA:
    diff2 =  (length - 1) * (ExpAverage(Max(-chg2, 0), length) * coeff2 - ExpAverage(Max(chg2, 0), length)) / 2;
}

def value2 = price + if diff2 >= 0 then diff2 else diff2 / coeff2;
DEF RSI = compoundValue(1, value2[1], Double.NaN);

# Trend direction detection
def rising = close > RSI;
def falling = close < RSI;

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "RSI_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);

Thanks!!
 
why signal is set at 10?
Here is the RSI version.

Code:
#==============================
# RSI Trend Duration (Lower Study)
# Assembled by Chewie
#==============================

declare lower;

#-----------------------------------
# RSI
#-----------------------------------

input length = 5;
input price = close;
input smoothingType = {default Wilders, EMA};
input rsiValue2 = 50.0;
input smoothingType2 = {default Wilders, EMA};

def coeff2 = rsiValue2 / (100 - rsiValue2);
def chg2 = price - price[1];
def diff2;
switch (smoothingType2) {
case Wilders:
    diff2 =  (length - 1) * (WildersAverage(Max(-chg2, 0), length) * coeff2 - WildersAverage(Max(chg2, 0), length));
case EMA:
    diff2 =  (length - 1) * (ExpAverage(Max(-chg2, 0), length) * coeff2 - ExpAverage(Max(chg2, 0), length)) / 2;
}

def value2 = price + if diff2 >= 0 then diff2 else diff2 / coeff2;
DEF RSI = compoundValue(1, value2[1], Double.NaN);

# Trend direction detection
def rising = close > RSI;
def falling = close < RSI;

# Boolean trend signal (1 = up, 0 = down)
def trendUp = if rising then 1 else if falling then 0 else trendUp[1];

# Detect when trend changes
def trendChange = trendUp[1] != trendUp;

#-----------------------------------
# Trend duration counting
#-----------------------------------
def trendCount = if trendChange then 1 else trendCount[1] + 1;

#-----------------------------------
# Plot Trend Durations
#-----------------------------------
plot BullTrendLength = if trendUp then trendCount else Double.NaN;
BullTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullTrendLength.SetDefaultColor(Color.GREEN);
BullTrendLength.SetLineWeight(2);

plot BearTrendLength = if !trendUp then trendCount else Double.NaN;
BearTrendLength.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearTrendLength.SetDefaultColor(Color.red);
BearTrendLength.SetLineWeight(2);

Bulltrendlength.AssignValueColor(if bulltrendlength >= 10 then Color.cyan else color.current);
Beartrendlength.AssignValueColor(if beartrendlength >= 10 then Color.magenta else color.current);

plot signal = 10;
signal.setdefaultColor(color.cyan);

#-----------------------------------
# Labels for quick reference
#-----------------------------------
AddLabel(yes, "RSI_Uptrend(bars): " + AsText(BullTrendLength), Color.GREEN);
AddLabel(yes, "Downtrend(bars): " + AsText(BearTrendLength), Color.red);
why is signal set at 10?
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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