# sideways_trend_00c
# trur is always 0 ?? , rma function
addlabel(1, "sideways_trend_00a", color.yellow);
declare lower;
#https://usethinkscript.com/threads/covert-tradingview-or-is-there-a-sideways-indicator-like-this-one.9561/
#Covert TradingView or Is there a Sideways Indicator Like this one?
#dmillz Jan 6, 2022
# This indicator has basically +1 0 -1 to avoid sideways action wondering if there is a indicator like this one for TOS?
# https://www.tradingview.com/script/zsDLpeBT-Trend-Type-Indicator-by-BobRivera990/
#The purpose of this indicator is to programmatically determine the type of price trend using technical analysis tools.
#You can do a quick check on the asset’s higher and lower time frames. For example, if you are trading on an H1 chart, you can check the m5 chart to ensure that the trend is in the same direction and similarly check the H4 chart to ensure that the higher time frame price is also moving in the same direction.
#If multiple time frame charts confirm a similar trend, then it is considered a very strong trend and ideal for Trend trading.
#By default, the last status is related to 8 periods before the latest closing price.
#The three basic types of trends are up, down, and sideways.
#1. Uptrend
#An uptrend describes the price movement of a financial asset when the overall direction is upward. The uptrend is composed of higher swing lows and higher swing highs.
#Some market participants ("long" trend traders) only choose to trade during uptrends.
#2. Downtrend
#A downtrend refers to the price action of a security that moves lower in price as it fluctuates over time.
#The downtrend is composed of lower swing lows and lower swing highs.
#3. Sideways
#A sideways trend is the horizontal price movement that occurs when the forces of supply and demand are nearly equal. This typically occurs during a period of consolidation before the price continues a prior trend or reverses into a new trend.
#How it works:
#Step 1: Sideways Trend Detection
#In this step we want to distinguish the sideways trend from uptrend and downtrend. For this purpose, we use two common technical analysis tools: ATR and ADX
#1. Average True Range (ATR)
#The average true range (ATR) is a technical analysis indicator that measures market volatility .
#We also use a 20-period moving average of the ATR.
#When the ATR is below the average of its last 20-periods, it means that the rate of price volatility has decreased and we conclude that the current trend is sideways
#2. Average Directional Index ( ADX )
#The average directional index ( ADX ) is a technical analysis indicator used by some traders to determine the strength of a trend.
#The trend has strength when ADX is above 25.
#So when the ADX is less than or equal to 25, there is no strong trend, and we conclude that the current type of trend is sideways.
#Step 2: Detect uptrend from downtrend
#If it turns out that the current price trend is not sideways, then it is either uptrend or downtrend.
#For this purpose, we use plus and minus directional Indicators (+ DI & -DI ).
#A general interpretation would be that during a strong trend, when +DI is higher than -DI , it is an uptrend. When -DI is higher than +DI , it is a downtrend.
#Parameters:
#"Use ATR …" ________________________// Use Average True Range (ATR) to detect Sideways Movements
#"ATR Length"_______________________ // length of the Average True Range (ATR) used to detect Sideways Movements
#"ATR Moving Average Type" ___________// Type of the moving average of the ATR used to detect Sideways Movements
#"ATR MA Length" ____________________// length of the moving average of the ATR used to detect Sideways Movements
#"Use ADX ..."_______________________ // Use Average Directional Index ( ADX ) to detect Sideways Movements
#"ADX Smoothing”____________________// length of the Average Directional Index ( ADX ) used to detect Sideways Movements
#"DI Length"_________________________// length of the Plus and Minus Directional Indicators ( +DI & -DI ) used to determine the direction of the trend
#"ADX Limit" ________________________// A level of ADX used as the boundary between Trend Market and Sideways Market
#"Smoothing Factor"__________________// Factor used for smoothing the oscillator
#"Lag"______________________________// lag used to match indicator and chart
# ======================================================
def na = double.nan;
def bn = barnumber();
def src = close;
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © BobRivera990
#//@version=4
#study(title = "Trend Type Indicator by BobRivera990", overlay = false)
# ===== [Inputs]======================================================
input Use_ATR_to_detect_Sideways_Movements = yes;
def useAtr = Use_ATR_to_detect_Sideways_Movements;
#useAtr = input(true, title = "Use ATR to detect Sideways Movements")
# // Use Average True Range (ATR) to detect Sideways Movements
input atrlen = 14;
#atrLen = input(14, minval = 1, title = "ATR Length")
# // length of the Average True Range (ATR) used to detect Sideways Movements
input atrMaType = AverageType.simple;
#atrMaType = input("SMA", options = ["SMA", "EMA"], title = "ATR Moving Average Type")
# // Type of the moving #average of the ATR used to detect Sideways Movements
input ATR_MA_Length = 20;
def atrMaLen = ATR_MA_Length;
#atrMaLen = input(20, minval = 1, title = "ATR MA Length")
# // length of the moving average of the ATR used to detect Sideways Movements
input Use_ADX_to_detect_Sideways_Movements = yes;
def useAdx = Use_ADX_to_detect_Sideways_Movements;
#useAdx = input(true, title = "Use ADX to detect Sideways Movements")
# // Use Average Directional Index (ADX) to detect Sideways Movements
input ADX_Smoothing_len = 14;
def adxlen = ADX_Smoothing_len;
#adxLen = input(14, minval = 1, maxval = 50, title = "ADX Smoothing")
# // length of the Average Directional Index (ADX) used to detect Sideways Movements
input diLen = 14;
#diLen = input(14, minval = 1, title = "DI Length")
# // length of the Plus and Minus Directional Indicators (+DI & -DI) used to determine the direction of the trend
input adxLim = 25;
#adxLim = input(25, minval = 1, title = "ADX Limit")
# // A level of ADX used as the boundary between Trend Market and Sideways Market
input Smoothing_Factor = 3;
def smooth = Smoothing_Factor;
#smooth = input(3, minval = 1, maxval = 5, title = "Smoothing Factor")
# // Factor used for smoothing the oscillator
input lag2 = 8;
def lag = if lag2 < 0 then 0 else if lag2 > 15 then 15 else lag2;
#lag = input(8, minval = 0, maxval = 15, title = "Lag")
# // lag used to match indicator and chart
#//================================================================================
# ==== [Initial Calculations]======================================================
def atr = atr(atrlen);
#atr = atr(atrLen)
# // Calculate the Average True Range (ATR)
def atrma = MovingAverage(atrMaType, close, atrMaLen);
#atrMa = atrMaType == "EMA" ? ema(atr, atrMaLen) : sma(atr, atrMaLen)
# // Calculate the moving average of the ATR
input test8 = no;
addlabel(test8, "test8", color.yellow);
addchartbubble(test8 and !isnan(close), 0,
atrlen + "\n" +
atr + "\n" +
atrMaLen + "\n" +
atrma
, color.yellow, no);
def up = high[0] - high[1];
#up = change(high)
# // Calculate parameter related to ADX, +DI and -DI
# https://www.tradingview.com/pine-script-reference/#fun_change
# Difference between current value and previous, x - x[y].
# Offset from the current bar to the previous bar. Optional, if not given, length = 1 is used.
def down = low[0] - low[1];
#down = -change(low)
# // Calculate parameter related to ADX, +DI and -DI
def plusdm = if isnan(up) then na else if (up > down and up > 0) then up else 0;
#plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
# // Calculate parameter related to ADX, +DI and -DI
# https://www.tradingview.com/pine-script-reference/#fun_na
# expr1 ? expr2 : expr3
# expr2 if expr1 is evaluated to true, expr3 otherwise. Zero value (0 and also NaN, +Infinity, -Infinity) is considered to be false, any other value is true.
def minusDM = if isnan(down) then na else if (down > up and down > 0) then down else 0;
#minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
# // Calculate parameter related to ADX, +DI and -DI
#============================================================
# sub script
# not sure about the sum := conversion
#def trur = rma( close , dilen);
#trur = rma(tr, diLen)
# // Calculate parameter related to ADX, +DI and -DI
# https://www.tradingview.com/pine-script-reference/#fun_rma
#rma()
#Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
#rma(source, length) ? series
#EXAMPLE
#plot(rma(close, 15))
#
#//the same on pine
#pine_rma(src, length) =>
# alpha = length
# sum = 0.0
# sum := na(sum[1]) ? sma(src, length) : (src + (alpha - 1) * nz(sum[1])) / alpha
#plot(pine_rma(close, 15))
#RETURNS
#Exponential moving average of x with alpha = 1 / y.
#script nz {
# input data = 0;
# def ret_val = if isNaN(data) then 0 else data;
# plot return = ret_val;
#}
script rma {
input src = close;
input length = 0;
def alpha = length;
#def sum = 0.0
#def sum := na(sum[1]) ? sma(src, length) : (src + (alpha - 1) * nz(sum[1])) / alpha
def sum1 = 0;
def x = if sum1 <> isnan(sum1[1]) then average(close, length) else ((src + (alpha - 1) *
( if isnan(sum1[1]) then 0 else sum1[1] )) / alpha );
# nz - Replaces NaN values with zeros (or given value) in a series.
#plot(pine_rma(close, 15))
#RETURNS
#Exponential moving average of x with alpha = 1 / y.
plot z = x;
}
# end of sub script
# ==========================================
def trur = rma(close , dilen);
# trur is always 0 ?? , rma function
input test6 = no;
addlabel(test6, "test6", color.yellow);
addchartbubble(test6 and !isnan(close), 0,
close + "\n" +
dilen + "\n" +
trur + " trur"
, color.yellow, no);
# ---------------------------------------
def plus = (100 * rma(plusDM, diLen) / trur);
#plus = fixnan(100 * rma(plusDM, diLen) / trur)
# // Calculate Plus Directional Indicator (+DI)
def minus = (100 * rma(minusDM, diLen) / trur);
#minus = fixnan(100 * rma(minusDM, diLen) / trur)
# // Calculate Minus Directional Indicator (-DI)
# trur = 0 , /0 = na
input test5 = no;
addlabel(test5, "test5", color.yellow);
addchartbubble(test5 and !isnan(close), 0,
plusDM + "\n" +
dilen + "\n" +
rma(plusDM, diLen) + "\n" +
trur + "\n" +
plus
, color.yellow, no);
# ---------------------------------------
def sum = plus + minus;
#sum = plus + minus
# // Calculate parameter related to ADX
def adx = 100 * rma(absvalue(plus - minus) / (if sum == 0 then 1 else sum), adxLen);
#adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxLen)
# // Calculate Average Directional Index (ADX)
#//==========================================================================
#//====== [Conditions]=======================================================
def cndNa = isnan(atr) or isnan(adx) or isnan(plus) or isnan(minus) or isnan(atrMaLen);
# na true if x is not a valid number (x is NaN), otherwise false.
#cndNa = na(atr) or na(adx) or na(plus) or na(minus) or na(atrMaLen)
# // Conditions for lack of sufficient data for calculations
def cndSidwayss1 = useAtr and (atr <= atrMa);
#cndSidwayss1 = useAtr and atr <= atrMa
# // Sideways Movement condition (based on ATR)
def cndSidwayss2 = useAdx and (adx <= adxLim);
#cndSidwayss2 = useAdx and adx <= adxLim
# // Sideways Movement condition (based on ADX)
input test7 = no;
addlabel(test7, "test7", color.yellow);
addchartbubble(test7 and !isnan(close), 0,
useAtr + "\n" +
atr + "\n" +
atrMa + "\n" +
cndSidwayss1 + "\n" +
useAdx + "\n" +
adx + "\n" +
adxLim + "\n" +
cndSidwayss2
, color.yellow, no);
def cndSidways = cndSidwayss1 or cndSidwayss2;
#cndSidways = cndSidwayss1 or cndSidwayss2
# // General Sideways Movement condition
def cndUp = plus > minus;
#cndUp = plus > minus
# // uptrend condition
def cndDown = minus >= plus;
#cndDown = minus >= plus
# // downtrend condition
# all 4 = na
input test4 = no;
addlabel(test4, "test4", color.yellow);
addchartbubble(test4 and !isnan(close), 0,
plus + "\n" +
minus + "\n" +
cndup + "\n" +
cnddown
, color.yellow, no);
#-----------------------------
def trendType = if cndNa then na else if cndSidways then 0 else if cndUp then 2 else -2;
#trendType = cndNa ? na : cndSidways ? 0 : cndUp ? 2 : -2
# // Determine the type of trend
# cndna = 1 , cndSidways = 1 , cndup = na , trendType = na
input test3 = no;
addlabel(test3, "test3", color.yellow);
addchartbubble(test3 and !isnan(close), 0,
cndna + "\n" +
cndSidways + "\n" +
cndup + "\n" +
trendtype
, color.yellow, no);
#-----------------------------
# ?? average
def smoothType = if isnan(trendType) then na else ( round(average(trendType, smooth) / 2) * 2);
#smoothType = na(trendType) ? na : round(sma(trendType, smooth) / 2) * 2
# // Calculate the smoothed trend type oscillator
# all 3 = NA's
input test2 = yes;
addlabel(test2, "test2", color.yellow);
addchartbubble(test2 and !isnan(close), 0,
trendtype + "\n" +
average(trendType, smooth) + "\n" +
smoothtype
, color.yellow, no);
#-----------------------------
#//===========================================================================
#//======== [Drawing]=========================================================
#colGreen30 = color.new(color.green, 30)
# // Define the color used in the drawings
#colGreen90 = color.new(color.green, 90)
# // Define the color used in the drawings
#colGray = color.new(color.gray, 20)
# // Define the color used in the drawings
#colWhite90 = color.new(color.white, 90)
# // Define the color used in the drawings
#colRed30 = color.new(color.red, 30)
# // Define the color used in the drawings
#colRed90 = color.new(color.red, 90)
# // Define the color used in the drawings
plot band3 = if !isnan(close) then 3 else na;
Band3.setdefaultcolor(color.black);
#band3 = plot(+3, title = "Band_3", color=color.black)
# // Draw the upper limit of the uptrend area
plot band2 = if !isnan(close) then 1 else na;
Band2.setdefaultcolor(color.black);
#band2 = plot(+1, title = "Band_2", color=color.black)
# // Draw the boundary between Sideways and Uptrend areas
plot band1 = if !isnan(close) then -1 else na;
Band1.setdefaultcolor(color.black);
#band1 = plot(-1, title = "Band_1", color=color.black)
# // Draw the boundary between Sideways and Downtrend areas
plot band0 = if !isnan(close) then -3 else na;
Band0.setdefaultcolor(color.black);
#band0 = plot(-3, title = "Band_0", color=color.black)
# // Draw the lower limit of the downtrend area
input show_clouds = yes;
addcloud((if show_clouds then band3 else na), band2, color.green);
#fill(band2, band3, title = "Uptrend area", color = colGreen90)
# // Highlight the Uptrend area
addcloud((if show_clouds then band2 else na), band1, color.light_gray);
#fill(band1, band2, title = "Sideways area", color = colWhite90)
# // Highlight the Sideways area
addcloud((if show_clouds then band1 else na), band0, color.red);
#fill(band0, band1, title = "Downtrend area", color = colRed90)
# // Highlight the Downtrend area
input bubble_offset = 2;
def x1 = ( !isnan(close[bubble_offset+1]) and isnan(close[bubble_offset]) );
addchartbubble(x1, 1.5, "UP", color.green, yes);
#var label lblUp = na
#label.delete(lblUp)
#lblUp := label.new(x = time, y = 2, text = "UP",
# color = color.new(color.green, 100), textcolor = color.black,
# style = label.style_label_left, xloc = xloc.bar_time,
# yloc = yloc.price, size=size.normal, textalign = text.align_left)
# // Show Uptrend area label
#var label lblSideways = na
#label.delete(lblSideways)
#lblSideways := label.new(x = time, y = 0, text = "SIDEWAYS",
# color = color.new(color.green, 100), textcolor = color.black,
# style = label.style_label_left, xloc = xloc.bar_time,
# yloc = yloc.price, size = size.normal, textalign = text.align_left)
# // Show Sideways area label
addchartbubble(x1, -1.5, "DOWN", color.red, no);
#var label lblDown = na
#label.delete(lblDown)
#lblDown := label.new(x = time, y = -2, text = "DOWN",
# color = color.new(color.green, 100), textcolor = color.black,
# style = label.style_label_left, xloc = xloc.bar_time,
# yloc = yloc.price, size = size.normal, textalign = text.align_left)
# // Show Downtrend area label
#var label lblCurrentType = na
#label.delete(lblCurrentType)
#lblCurrentType := label.new(x = time, y = smoothType,
# color = color.new(color.blue, 30), style = label.style_label_right,
# xloc = xloc.bar_time, yloc = yloc.price, size = size.small)
# // Show the latest status label
#trendCol = smoothType == 2 ? colGreen30 : smoothType == 0 ? colGray : colRed30
# // Determine the color of the oscillator in different conditions
plot z1 = smoothtype[-lag];
z1.setdefaultcolor(color.yellow);
z1.setlineweight(3);
#plot(smoothType, title = "Trend Type Oscillator", color = trendCol,
# linewidth = 3, offset = -lag, style = plot.style_stepline)
# // Draw the trend type oscillator
#-------------------------
plot z = if !isnan(close) then 0 else na;
z.setdefaultcolor(color.white);
#-------------------------------------------------------
input test1 = no;
addlabel(test1, "test1", color.yellow);
addchartbubble(test1 and !isnan(close), 0,
smoothtype + "\n" +
lag + "\n" +
z1
, color.yellow, no);
#