RedK Chop & Breakout Scout V2.0 for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
BKDJZNq.png

I added alert to be shows on the indicator.

Message from the author:
The RedK Chop & Breakout Scout (C&BS or just CBS) is a centered oscillator that helps traders identify when the price is in a chop zone, where it's recommended to avoid trading or exit existing trades - and helps identify (good & tradeable) price breakouts.

This concept is similar to a Stochastic Oscillator - with the main difference being that we're utilizing units of ATR (instead of a channel width) to calculate the main indicator line - which will then lead to a non-restricted oscillator (rather than a +/- 100%) - given that ATR changes with the underlying and the timeframe, among other variables.

https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/

CODE BELOW

CSS:
#// © RedKTrader
#// plots a centered oscillator based on how many ATR units the source price is from a price baseline (could be a Donchian midline or another slow MA)
#// the Chop Zone is detected when the price is within a customizable ATR-based distance above or below the baseline
#// a filter is then applied (using EMA - but can be other types of long-term MA) to indicate the preferred trade direction (long vs. short)
#// when the CBS line is inside the chop zone, trading is not recommended for the conservative trader
#// Breakouts are found when the CBS line exits the Chop zone (in agreement with the filter direction)
#// An aggressive swing trader can consider positions when the CBS line crosses the 0 line in the filter direction
#indicator('RedK Chop & Breakout Scout ', shorttitle='C&B_Scout v2.0'
#https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/
# Converted and mod by Sam4Cok@Samer800 - 08/2022

#//                                  ATR Calclatioin Function
#// ==============================================================================================
script nz {
    input data = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
# RMA(src, length)=>
script RMA {
    input src = close;
    input length = 14;
    def   alpha = 1 / length;
    def sum;
    sum = if IsNaN(sum[1]) then SimpleMovingAvg(src, length) else alpha * src + (1 - alpha) * nz(sum[1]);
    plot  Return = sum;
}
#ATR_Calc(_price, _length, _atrcalc) =>
script ATR_Calc {
    input _price = close;
    input _length = 0;
    input _atrcalc = "RMA";
    def ATR_Calc = if _atrcalc == "RMA" then RMA(_price, _length) else
                   if _atrcalc == "SMA" then SimpleMovingAvg(_price, _length) else
                   if _atrcalc == "EMA" then ExpAverage(_price, _length) else
                    WMA(_price, _length);
    plot return = ATR_Calc;
}
#=================================================================================================
#                                 Inputs
#=================================================================================================

input Src         = close;    # Price
input BaselineLength = 10;    # Baseline Length
input AtrLength   = 10;       # ATR Avg Length
input MAType      = {default "RMA", "SMA", "EMA", "WMA"}; # MA Calculation
input ChopLevel   = 0.5;      # Chop Level
input smooth      = 3;        # Smooth
input EMAFilter   = 20;       # EMA Filter
input ShowAlert   = yes;

#=================================================================================================
#                                  Calculations
#=================================================================================================
declare lower;
def na = Double.NaN;

#//calculate baseline price - added other slow MA's
def baseline    = (Highest(high, BaselineLength) + Lowest(low, BaselineLength)) / 2;

#// Calculate ATR
def tr = if IsNaN(close[1]) then high - low else
                Max(Max(high - low, AbsValue(high - close[1])), AbsValue(low - close[1]));

def ATR = ATR_Calc(tr, BaselineLength, MAType);

#// CBS value is basically how far is current price from the baseline in terms of "ATR units"
def cbs    = (Src - baseline) / ATR;
def scbs1  =  WMA(cbs, smooth);
def scbs   =  WMA(scbs1, smooth);
#// check where is price wrt the filter line to determine recommended trading direction
#// in v1, we use an EMA-based filter as it's most popular -- may add other MA types in future.
def f_modelong1  = Src > ExpAverage(Src, EMAFilter);
def f_modelong = f_modelong1;

# =================================================================================================
#                                  Plots
# =================================================================================================

plot zeroLine = 0;        # Zero Line
zeroLine.SetPaintingStrategy(PaintingStrategy.DASHES);
zeroLine.SetDefaultColor(Color.GRAY);
def h0          = ChopLevel;     # "Chop Zone - Upper"
def h1          = -ChopLevel;    # "Chop Zone - Lower"

AddChart(high = if f_modelong then h0 else na,
         low = if f_modelong then h1 else na,
         open =  if f_modelong then h0 else na,
         close = if f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor = CreateColor(0,100,0));
AddChart(high = if !f_modelong then h0 else na,
         low = if !f_modelong then h1 else na,
         open = if !f_modelong then h0 else na,
         close = if !f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor =CreateColor(100,0,0));

plot CBSSmooth = scbs;    # "CBS Smooth"
CBSSmooth.AssignValueColor(if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
          if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
CBSSmooth.SetLineWeight(3);
#====================================================================================
#                                  Alerts
#====================================================================================
plot up = if ShowAlert and f_modelong and (cbs crosses above ChopLevel) and scbs > scbs[1] then ChopLevel else na;
plot dn = if ShowAlert and !f_modelong and (cbs crosses below -ChopLevel) and scbs < scbs[1] then -ChopLevel else na;
up.SetPaintingStrategy(PaintingStrategy.SQUARES);
up.SetDefaultColor(Color.GREEN);
up.SetLineWeight(2);
dn.SetPaintingStrategy(PaintingStrategy.SQUARES);
dn.SetDefaultColor(Color.RED);
dn.SetLineWeight(2);

### END
 
Last edited by a moderator:

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

nice job. this looks much better on higher (i.e., daily or weekly) timeframes for swing trading @samer800 but I did not adjust default settings
thanks. I just provided the setting as per the creator. Different setting may be better for different market. you need to keep adjust the setting till you reach to your suitable trading strategy. As general guidelines, you can't only depends on indicators.
 
Hi @samer800, Is it possible to add the divergence to this indicator? Thanks
add below as requested.

CSS:
#// © RedKTrader
#// plots a centered oscillator based on how many ATR units the source price is from a price baseline (could be a Donchian midline or another slow MA)
#// the Chop Zone is detected when the price is within a customizable ATR-based distance above or below the baseline
#// a filter is then applied (using EMA - but can be other types of long-term MA) to indicate the preferred trade direction (long vs. short)
#// when the CBS line is inside the chop zone, trading is not recommended for the conservative trader
#// Breakouts are found when the CBS line exits the Chop zone (in agreement with the filter direction)
#// An aggressive swing trader can consider positions when the CBS line crosses the 0 line in the filter direction
#indicator('RedK Chop & Breakout Scout ', shorttitle='C&B_Scout v2.0'
#https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/
# Converted and mod by Sam4Cok@Samer800 - 08/2022
# Updated - Added divergence by Sam4Cok@Samer800 - 10/2022

#//                                  ATR Calculation Function
#// ==============================================================================================
script nz {
    input data = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
# RMA(src, length)=>
script RMA {
    input src = close;
    input length = 14;
    def   alpha = 1 / length;
    def sum;
    sum = if IsNaN(sum[1]) then SimpleMovingAvg(src, length) else alpha * src + (1 - alpha) * nz(sum[1]);
    plot  Return = sum;
}
#ATR_Calc(_price, _length, _atrcalc) =>
script ATR_Calc {
    input _price = close;
    input _length = 0;
    input _atrcalc = "RMA";
    def ATR_Calc = if _atrcalc == "RMA" then RMA(_price, _length) else
                   if _atrcalc == "SMA" then SimpleMovingAvg(_price, _length) else
                   if _atrcalc == "EMA" then ExpAverage(_price, _length) else
                    WMA(_price, _length);
    plot return = ATR_Calc;
}
#=================================================================================================
#                                 Inputs
#=================================================================================================

input Src         = close;    # Price
input BaselineLength = 10;    # Baseline Length
input AtrLength   = 10;       # ATR Avg Length
input MAType      = {default "RMA", "SMA", "EMA", "WMA"}; # MA Calculation
input ChopLevel   = 0.5;      # Chop Level
input smooth      = 3;        # Smooth
input EMAFilter   = 20;       # EMA Filter
input ShowAlert   = yes;

#=================================================================================================
#                                  Calculations
#=================================================================================================
declare lower;
def na = Double.NaN;

#//calculate baseline price - added other slow MA's
def baseline    = (Highest(high, BaselineLength) + Lowest(low, BaselineLength)) / 2;

#// Calculate ATR
def tr = if IsNaN(close[1]) then high - low else
                Max(Max(high - low, AbsValue(high - close[1])), AbsValue(low - close[1]));

def ATR = ATR_Calc(tr, BaselineLength, MAType);

#// CBS value is basically how far is current price from the baseline in terms of "ATR units"
def cbs    = (Src - baseline) / ATR;
def scbs1  =  WMA(cbs, smooth);
def scbs   =  WMA(scbs1, smooth);
#// check where is price wrt the filter line to determine recommended trading direction
#// in v1, we use an EMA-based filter as it's most popular -- may add other MA types in future.
def f_modelong1  = Src > ExpAverage(Src, EMAFilter);
def f_modelong = f_modelong1;

# =================================================================================================
#                                  Plots
# =================================================================================================

plot zeroLine = 0;        # Zero Line
zeroLine.SetPaintingStrategy(PaintingStrategy.DASHES);
zeroLine.SetDefaultColor(Color.GRAY);
def h0          = ChopLevel;     # "Chop Zone - Upper"
def h1          = -ChopLevel;    # "Chop Zone - Lower"

AddChart(high = if f_modelong then h0 else na,
         low = if f_modelong then h1 else na,
         open =  if f_modelong then h0 else na,
         close = if f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor = CreateColor(0,100,0));
AddChart(high = if !f_modelong then h0 else na,
         low = if !f_modelong then h1 else na,
         open = if !f_modelong then h0 else na,
         close = if !f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor =CreateColor(100,0,0));

plot CBSSmooth = scbs;    # "CBS Smooth"
CBSSmooth.AssignValueColor(if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
          if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
CBSSmooth.SetLineWeight(3);
#====================================================================================
#                                  Alerts
#====================================================================================
plot up = if ShowAlert and f_modelong and (cbs crosses above ChopLevel) and scbs > scbs[1] then ChopLevel else na;
plot dn = if ShowAlert and !f_modelong and (cbs crosses below -ChopLevel) and scbs < scbs[1] then -ChopLevel else na;
up.SetPaintingStrategy(PaintingStrategy.SQUARES);
up.SetDefaultColor(Color.GREEN);
up.SetLineWeight(2);
dn.SetPaintingStrategy(PaintingStrategy.SQUARES);
dn.SetDefaultColor(Color.RED);
dn.SetLineWeight(2);
#----Div-----------
input LookbackRight  = 5;           # "Pivot Lookback Right"
input LookbackLeft  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = scbs;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL+1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL+1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#valuewhen (Cond, source, lbr, occurrence)
script valuewhen {
  input cond = 0;
  input src = close;
  input lbr = 0;
  input occurrence = 0;
  def n = occurrence + 1;
  def offset = fold j = 0 to 200 with p=1 while p < n + 1
    do p + ( if p == n then j - n else if cond[j]==yes then 1 else 0 );
  plot price = GetValue(src[lbr], offset-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookbackLeft, LookbackRight);
def ph = findpivots(divSrc, 1, LookbackLeft, LookbackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound = valuewhen(plFound, divSrc, 0, 1);
def vhFound = valuewhen(phFound, divSrc, 0, 1);

def plPrice = valuewhen(plFound, l, 0, 1);
def phPrice = valuewhen(phFound, h, 0, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc[LookbackRight] < vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceHL = l[LookbackRight] > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def oscLH   = divSrc < vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

### END
 
add below as requested.

CSS:
#// © RedKTrader
#// plots a centered oscillator based on how many ATR units the source price is from a price baseline (could be a Donchian midline or another slow MA)
#// the Chop Zone is detected when the price is within a customizable ATR-based distance above or below the baseline
#// a filter is then applied (using EMA - but can be other types of long-term MA) to indicate the preferred trade direction (long vs. short)
#// when the CBS line is inside the chop zone, trading is not recommended for the conservative trader
#// Breakouts are found when the CBS line exits the Chop zone (in agreement with the filter direction)
#// An aggressive swing trader can consider positions when the CBS line crosses the 0 line in the filter direction
#indicator('RedK Chop & Breakout Scout ', shorttitle='C&B_Scout v2.0'
#https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/
# Converted and mod by Sam4Cok@Samer800 - 08/2022
# Updated - Added divergence by Sam4Cok@Samer800 - 10/2022

#//                                  ATR Calculation Function
#// ==============================================================================================
script nz {
    input data = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
# RMA(src, length)=>
script RMA {
    input src = close;
    input length = 14;
    def   alpha = 1 / length;
    def sum;
    sum = if IsNaN(sum[1]) then SimpleMovingAvg(src, length) else alpha * src + (1 - alpha) * nz(sum[1]);
    plot  Return = sum;
}
#ATR_Calc(_price, _length, _atrcalc) =>
script ATR_Calc {
    input _price = close;
    input _length = 0;
    input _atrcalc = "RMA";
    def ATR_Calc = if _atrcalc == "RMA" then RMA(_price, _length) else
                   if _atrcalc == "SMA" then SimpleMovingAvg(_price, _length) else
                   if _atrcalc == "EMA" then ExpAverage(_price, _length) else
                    WMA(_price, _length);
    plot return = ATR_Calc;
}
#=================================================================================================
#                                 Inputs
#=================================================================================================

input Src         = close;    # Price
input BaselineLength = 10;    # Baseline Length
input AtrLength   = 10;       # ATR Avg Length
input MAType      = {default "RMA", "SMA", "EMA", "WMA"}; # MA Calculation
input ChopLevel   = 0.5;      # Chop Level
input smooth      = 3;        # Smooth
input EMAFilter   = 20;       # EMA Filter
input ShowAlert   = yes;

#=================================================================================================
#                                  Calculations
#=================================================================================================
declare lower;
def na = Double.NaN;

#//calculate baseline price - added other slow MA's
def baseline    = (Highest(high, BaselineLength) + Lowest(low, BaselineLength)) / 2;

#// Calculate ATR
def tr = if IsNaN(close[1]) then high - low else
                Max(Max(high - low, AbsValue(high - close[1])), AbsValue(low - close[1]));

def ATR = ATR_Calc(tr, BaselineLength, MAType);

#// CBS value is basically how far is current price from the baseline in terms of "ATR units"
def cbs    = (Src - baseline) / ATR;
def scbs1  =  WMA(cbs, smooth);
def scbs   =  WMA(scbs1, smooth);
#// check where is price wrt the filter line to determine recommended trading direction
#// in v1, we use an EMA-based filter as it's most popular -- may add other MA types in future.
def f_modelong1  = Src > ExpAverage(Src, EMAFilter);
def f_modelong = f_modelong1;

# =================================================================================================
#                                  Plots
# =================================================================================================

plot zeroLine = 0;        # Zero Line
zeroLine.SetPaintingStrategy(PaintingStrategy.DASHES);
zeroLine.SetDefaultColor(Color.GRAY);
def h0          = ChopLevel;     # "Chop Zone - Upper"
def h1          = -ChopLevel;    # "Chop Zone - Lower"

AddChart(high = if f_modelong then h0 else na,
         low = if f_modelong then h1 else na,
         open =  if f_modelong then h0 else na,
         close = if f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor = CreateColor(0,100,0));
AddChart(high = if !f_modelong then h0 else na,
         low = if !f_modelong then h1 else na,
         open = if !f_modelong then h0 else na,
         close = if !f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor =CreateColor(100,0,0));

plot CBSSmooth = scbs;    # "CBS Smooth"
CBSSmooth.AssignValueColor(if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
          if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
CBSSmooth.SetLineWeight(3);
#====================================================================================
#                                  Alerts
#====================================================================================
plot up = if ShowAlert and f_modelong and (cbs crosses above ChopLevel) and scbs > scbs[1] then ChopLevel else na;
plot dn = if ShowAlert and !f_modelong and (cbs crosses below -ChopLevel) and scbs < scbs[1] then -ChopLevel else na;
up.SetPaintingStrategy(PaintingStrategy.SQUARES);
up.SetDefaultColor(Color.GREEN);
up.SetLineWeight(2);
dn.SetPaintingStrategy(PaintingStrategy.SQUARES);
dn.SetDefaultColor(Color.RED);
dn.SetLineWeight(2);
#----Div-----------
input LookbackRight  = 5;           # "Pivot Lookback Right"
input LookbackLeft  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = scbs;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL+1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL+1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#valuewhen (Cond, source, lbr, occurrence)
script valuewhen {
  input cond = 0;
  input src = close;
  input lbr = 0;
  input occurrence = 0;
  def n = occurrence + 1;
  def offset = fold j = 0 to 200 with p=1 while p < n + 1
    do p + ( if p == n then j - n else if cond[j]==yes then 1 else 0 );
  plot price = GetValue(src[lbr], offset-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookbackLeft, LookbackRight);
def ph = findpivots(divSrc, 1, LookbackLeft, LookbackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound = valuewhen(plFound, divSrc, 0, 1);
def vhFound = valuewhen(phFound, divSrc, 0, 1);

def plPrice = valuewhen(plFound, l, 0, 1);
def phPrice = valuewhen(phFound, h, 0, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc[LookbackRight] < vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceHL = l[LookbackRight] > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def oscLH   = divSrc < vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

### END
Thanks, ma. You have done a fantastic job.
 
  • Like
Reactions: ASC
View attachment 15627
I added alert to be shows on the indicator.

Message from the author:
The RedK Chop & Breakout Scout (C&BS or just CBS) is a centered oscillator that helps traders identify when the price is in a chop zone, where it's recommended to avoid trading or exit existing trades - and helps identify (good & tradeable) price breakouts.

This concept is similar to a Stochastic Oscillator - with the main difference being that we're utilizing units of ATR (instead of a channel width) to calculate the main indicator line - which will then lead to a non-restricted oscillator (rather than a +/- 100%) - given that ATR changes with the underlying and the timeframe, among other variables.

https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/

CODE BELOW

CSS:
#// © RedKTrader
#// plots a centered oscillator based on how many ATR units the source price is from a price baseline (could be a Donchian midline or another slow MA)
#// the Chop Zone is detected when the price is within a customizable ATR-based distance above or below the baseline
#// a filter is then applied (using EMA - but can be other types of long-term MA) to indicate the preferred trade direction (long vs. short)
#// when the CBS line is inside the chop zone, trading is not recommended for the conservative trader
#// Breakouts are found when the CBS line exits the Chop zone (in agreement with the filter direction)
#// An aggressive swing trader can consider positions when the CBS line crosses the 0 line in the filter direction
#indicator('RedK Chop & Breakout Scout ', shorttitle='C&B_Scout v2.0'
#https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/
# Converted and mod by Sam4Cok@Samer800 - 08/2022

#//                                  ATR Calclatioin Function
#// ==============================================================================================
script nz {
    input data = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
# RMA(src, length)=>
script RMA {
    input src = close;
    input length = 14;
    def   alpha = 1 / length;
    def sum;
    sum = if IsNaN(sum[1]) then SimpleMovingAvg(src, length) else alpha * src + (1 - alpha) * nz(sum[1]);
    plot  Return = sum;
}
#ATR_Calc(_price, _length, _atrcalc) =>
script ATR_Calc {
    input _price = close;
    input _length = 0;
    input _atrcalc = "RMA";
    def ATR_Calc = if _atrcalc == "RMA" then RMA(_price, _length) else
                   if _atrcalc == "SMA" then SimpleMovingAvg(_price, _length) else
                   if _atrcalc == "EMA" then ExpAverage(_price, _length) else
                    WMA(_price, _length);
    plot return = ATR_Calc;
}
#=================================================================================================
#                                 Inputs
#=================================================================================================

input Src         = close;    # Price
input BaselineLength = 10;    # Baseline Length
input AtrLength   = 10;       # ATR Avg Length
input MAType      = {default "RMA", "SMA", "EMA", "WMA"}; # MA Calculation
input ChopLevel   = 0.5;      # Chop Level
input smooth      = 3;        # Smooth
input EMAFilter   = 20;       # EMA Filter
input ShowAlert   = yes;

#=================================================================================================
#                                  Calculations
#=================================================================================================
declare lower;
def na = Double.NaN;

#//calculate baseline price - added other slow MA's
def baseline    = (Highest(high, BaselineLength) + Lowest(low, BaselineLength)) / 2;

#// Calculate ATR
def tr = if IsNaN(close[1]) then high - low else
                Max(Max(high - low, AbsValue(high - close[1])), AbsValue(low - close[1]));

def ATR = ATR_Calc(tr, BaselineLength, MAType);

#// CBS value is basically how far is current price from the baseline in terms of "ATR units"
def cbs    = (Src - baseline) / ATR;
def scbs1  =  WMA(cbs, smooth);
def scbs   =  WMA(scbs1, smooth);
#// check where is price wrt the filter line to determine recommended trading direction
#// in v1, we use an EMA-based filter as it's most popular -- may add other MA types in future.
def f_modelong1  = Src > ExpAverage(Src, EMAFilter);
def f_modelong = f_modelong1;

# =================================================================================================
#                                  Plots
# =================================================================================================

plot zeroLine = 0;        # Zero Line
zeroLine.SetPaintingStrategy(PaintingStrategy.DASHES);
zeroLine.SetDefaultColor(Color.GRAY);
def h0          = ChopLevel;     # "Chop Zone - Upper"
def h1          = -ChopLevel;    # "Chop Zone - Lower"

AddChart(high = if f_modelong then h0 else na,
         low = if f_modelong then h1 else na,
         open =  if f_modelong then h0 else na,
         close = if f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor = CreateColor(0,100,0));
AddChart(high = if !f_modelong then h0 else na,
         low = if !f_modelong then h1 else na,
         open = if !f_modelong then h0 else na,
         close = if !f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor =CreateColor(100,0,0));

plot CBSSmooth = scbs;    # "CBS Smooth"
CBSSmooth.AssignValueColor(if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
          if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
CBSSmooth.SetLineWeight(3);
#====================================================================================
#                                  Alerts
#====================================================================================
plot up = if ShowAlert and f_modelong and (cbs crosses above ChopLevel) and scbs > scbs[1] then ChopLevel else na;
plot dn = if ShowAlert and !f_modelong and (cbs crosses below -ChopLevel) and scbs < scbs[1] then -ChopLevel else na;
up.SetPaintingStrategy(PaintingStrategy.SQUARES);
up.SetDefaultColor(Color.GREEN);
up.SetLineWeight(2);
dn.SetPaintingStrategy(PaintingStrategy.SQUARES);
dn.SetDefaultColor(Color.RED);
dn.SetLineWeight(2);

### END
Can someone add in price color based on blue, white and red line in the indicator???
 
Can someone add in price color based on blue, white and red line in the indicator???
add the below at the end of the code.

CSS:
input colorBars = yes;

AssignPriceColor(if !colorBars then Color.CURRENT else
                if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
                if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
 
add the below at the end of the code.

CSS:
input colorBars = yes;

AssignPriceColor(if !colorBars then Color.CURRENT else
                if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
                if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
 
Last edited:
is there any way to change the code for the chop zone histogram into lines, so that is its viewable on mobile? RedK is an awesome author for scripts!
 
add below as requested.

CSS:
#// © RedKTrader
#// plots a centered oscillator based on how many ATR units the source price is from a price baseline (could be a Donchian midline or another slow MA)
#// the Chop Zone is detected when the price is within a customizable ATR-based distance above or below the baseline
#// a filter is then applied (using EMA - but can be other types of long-term MA) to indicate the preferred trade direction (long vs. short)
#// when the CBS line is inside the chop zone, trading is not recommended for the conservative trader
#// Breakouts are found when the CBS line exits the Chop zone (in agreement with the filter direction)
#// An aggressive swing trader can consider positions when the CBS line crosses the 0 line in the filter direction
#indicator('RedK Chop & Breakout Scout ', shorttitle='C&B_Scout v2.0'
#https://www.tradingview.com/script/jnWK8gZg-RedK-Chop-Breakout-Scout-C-B-Scout/
# Converted and mod by Sam4Cok@Samer800 - 08/2022
# Updated - Added divergence by Sam4Cok@Samer800 - 10/2022

#//                                  ATR Calculation Function
#// ==============================================================================================
script nz {
    input data = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
# RMA(src, length)=>
script RMA {
    input src = close;
    input length = 14;
    def   alpha = 1 / length;
    def sum;
    sum = if IsNaN(sum[1]) then SimpleMovingAvg(src, length) else alpha * src + (1 - alpha) * nz(sum[1]);
    plot  Return = sum;
}
#ATR_Calc(_price, _length, _atrcalc) =>
script ATR_Calc {
    input _price = close;
    input _length = 0;
    input _atrcalc = "RMA";
    def ATR_Calc = if _atrcalc == "RMA" then RMA(_price, _length) else
                   if _atrcalc == "SMA" then SimpleMovingAvg(_price, _length) else
                   if _atrcalc == "EMA" then ExpAverage(_price, _length) else
                    WMA(_price, _length);
    plot return = ATR_Calc;
}
#=================================================================================================
#                                 Inputs
#=================================================================================================

input Src         = close;    # Price
input BaselineLength = 10;    # Baseline Length
input AtrLength   = 10;       # ATR Avg Length
input MAType      = {default "RMA", "SMA", "EMA", "WMA"}; # MA Calculation
input ChopLevel   = 0.5;      # Chop Level
input smooth      = 3;        # Smooth
input EMAFilter   = 20;       # EMA Filter
input ShowAlert   = yes;

#=================================================================================================
#                                  Calculations
#=================================================================================================
declare lower;
def na = Double.NaN;

#//calculate baseline price - added other slow MA's
def baseline    = (Highest(high, BaselineLength) + Lowest(low, BaselineLength)) / 2;

#// Calculate ATR
def tr = if IsNaN(close[1]) then high - low else
                Max(Max(high - low, AbsValue(high - close[1])), AbsValue(low - close[1]));

def ATR = ATR_Calc(tr, BaselineLength, MAType);

#// CBS value is basically how far is current price from the baseline in terms of "ATR units"
def cbs    = (Src - baseline) / ATR;
def scbs1  =  WMA(cbs, smooth);
def scbs   =  WMA(scbs1, smooth);
#// check where is price wrt the filter line to determine recommended trading direction
#// in v1, we use an EMA-based filter as it's most popular -- may add other MA types in future.
def f_modelong1  = Src > ExpAverage(Src, EMAFilter);
def f_modelong = f_modelong1;

# =================================================================================================
#                                  Plots
# =================================================================================================

plot zeroLine = 0;        # Zero Line
zeroLine.SetPaintingStrategy(PaintingStrategy.DASHES);
zeroLine.SetDefaultColor(Color.GRAY);
def h0          = ChopLevel;     # "Chop Zone - Upper"
def h1          = -ChopLevel;    # "Chop Zone - Lower"

AddChart(high = if f_modelong then h0 else na,
         low = if f_modelong then h1 else na,
         open =  if f_modelong then h0 else na,
         close = if f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor = CreateColor(0,100,0));
AddChart(high = if !f_modelong then h0 else na,
         low = if !f_modelong then h1 else na,
         open = if !f_modelong then h0 else na,
         close = if !f_modelong then h1 else na,
         type = ChartType.CANDLE, growcolor =CreateColor(100,0,0));

plot CBSSmooth = scbs;    # "CBS Smooth"
CBSSmooth.AssignValueColor(if f_modelong and cbs > ChopLevel then CreateColor(41,98,255) else
          if !f_modelong and cbs < -ChopLevel then CreateColor(242,54,69) else Color.WHITE);
CBSSmooth.SetLineWeight(3);
#====================================================================================
#                                  Alerts
#====================================================================================
plot up = if ShowAlert and f_modelong and (cbs crosses above ChopLevel) and scbs > scbs[1] then ChopLevel else na;
plot dn = if ShowAlert and !f_modelong and (cbs crosses below -ChopLevel) and scbs < scbs[1] then -ChopLevel else na;
up.SetPaintingStrategy(PaintingStrategy.SQUARES);
up.SetDefaultColor(Color.GREEN);
up.SetLineWeight(2);
dn.SetPaintingStrategy(PaintingStrategy.SQUARES);
dn.SetDefaultColor(Color.RED);
dn.SetLineWeight(2);
#----Div-----------
input LookbackRight  = 5;           # "Pivot Lookback Right"
input LookbackLeft  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = scbs;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL+1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL+1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#valuewhen (Cond, source, lbr, occurrence)
script valuewhen {
  input cond = 0;
  input src = close;
  input lbr = 0;
  input occurrence = 0;
  def n = occurrence + 1;
  def offset = fold j = 0 to 200 with p=1 while p < n + 1
    do p + ( if p == n then j - n else if cond[j]==yes then 1 else 0 );
  plot price = GetValue(src[lbr], offset-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookbackLeft, LookbackRight);
def ph = findpivots(divSrc, 1, LookbackLeft, LookbackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound = valuewhen(plFound, divSrc, 0, 1);
def vhFound = valuewhen(phFound, divSrc, 0, 1);

def plPrice = valuewhen(plFound, l, 0, 1);
def phPrice = valuewhen(phFound, h, 0, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc[LookbackRight] < vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceHL = l[LookbackRight] > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def oscLH   = divSrc < vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

### END
Is there a way to add a moving average to this indicator? This is a wonderful indicator.
Thanks Samer800
 
Hi Samer800, Thank you very much for all you do! I was wondering if it's possible to add a target and stop loss function so that when paint bars = Yes the close of the first blue bar is the entry and then have the ability to set target ATR and target stop. Additionally, it would be excellent to see labels in upper left of chart with P/L $'s, losses in $'s, win rate %, total # of wins and losses. Thank you so much

Also be great to have the same target and stop loss function for the first red bar to short. Thank you
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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