DEMA Adjusted Average True Range For ThinkOrSwim

SugarTrader

Member
Author states:
The use of the Double Exponential Moving Average (DEMA) within your Adjusted Average True Range (ATR) calculation serves as a cornerstone for enhancing the indicator's responsiveness to market changes. To delve deeper into why DEMA is employed specifically in the context of your ATR calculation, let's explore the inherent qualities of DEMA and its impact on the ATR's performance.

DEMA and Its Advantages
As previously mentioned, DEMA was designed to offer a more responsive alternative to the traditional Exponential Moving Average (EMA). By giving more weight to recent price data, DEMA reduces the lag typically associated with moving averages. This reduction in lag is especially beneficial for short-term traders looking to capitalize on trend reversals and other market movements as swiftly as possible.

The calculation of DEMA involves the following steps:
Calculate EMA1: This is the Exponential Moving Average of the price.
Calculate EMA2: This is the Exponential Moving Average of EMA1, thus it is a smoothing of a smoothing, leading to a greater lag.
Formulate DEMA: The formula
EMA1 = EMA of price
EMA2 = EMA of EMA1
DEMA = (2 x EMA1) - EMA2
effectively doubles the weighting of the most recent data points by subtracting the lagged, double-smoothed EMA2 from twice the single-smoothed EMA1.
This process enhances the moving average's sensitivity to recent price movements, allowing the DEMA to adhere more closely to the price bars than either EMA1 or EMA2 alone.

Integration with ATR
In the context of your ATR calculation, the integration of DEMA plays a crucial role in defining the indicator's core functionality. Here's a detailed explanation of how DEMA affects the ATR calculation:

Initial Determination of DEMA: By applying the DEMA formula to the chosen source data (which can be adjusted to use Heikin Ashi candle close prices for an even smoother analysis), you set a foundation for a more reactive trend-following mechanism within the ATR framework.
Application to ATR Bands: The calculated DEMA serves as the central line from which the ATR bands are derived. The ATR value, multiplied by a user-defined factor, is added to and subtracted from the DEMA to form the upper and lower bands, respectively. This dynamic adjustment not only reflects the volatility based on the ATR but does so in a way that is closely aligned with the most recent price action, thanks to the utilization of DEMA.
Enhanced Signal Quality: The responsiveness of DEMA ensures that the ATR bands adjust more promptly to changes in market conditions. This quality is vital for traders who rely on the ATR bands to identify potential entry and exit points, trend reversals, or to assess market volatility.

By employing DEMA as the core component in calculating the Adjusted Average True Range, your indicator leverages DEMA's reduced lag and increased weight on recent data to provide a more timely and accurate measure of market volatility. This innovative approach enhances the utility of the ATR by making it not only a tool for assessing volatility but also a more reactive indicator for trend analysis and trading signal generation.

The main concept of combining these is to reduce lag, get a more robust signal and still capture clear trends over medium time horizons.
For me, this is best used in confluence with other indicators, it can be made faster in order to get fasters response time, or slower. This is all depending on the needs of you as a trader.
gd9BBXQ.png


Original Tradingview script can be found:
https://www.tradingview.com/script/FqwJYrJP-DEMA-Adjusted-Average-True-Range-BackQuant/
New ThinkOrSwim code is in next post
 
Last edited by a moderator:

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

Hello,
I would really appreciate if someone could help converting from Pinescript to TOS.
Just the simple line, I don't even need candle color, alerts, or the extra moving average.
Thank you so much.

https://www.tradingview.com/script/FqwJYrJP-DEMA-Adjusted-Average-True-Range-BackQuant/
check the below:

CSS:
#// Indicator for TOS
#// © BackQuant
# title="DEMA Adjusted Average True Range [BackQuant]",
# shorttitle = "DEMA ATR [BackQuant]",
# Converted by Sam4Cok@Samer800    - 11/2024

input timeframe         = AggregationPeriod.MIN;
input showDemaAtr       = yes;     # "Plot Dema Atr on Chart?"
input atrMovAvgType     = {"SMA", "Hull", "EMA", "WMA",default "DEMA"}; # "MA Type"
input demaPeriod        = 7;       # "Dema Period"
input demaSource        = FundamentalType.CLOSE;   # "Calculation Source"
input AtrPeriod         = 14;      # "Period"
input atrFactor         = 1.7;     # "Factor"
input colorCandles      = no;      # "Paint Candles According to trend?"
input showBand          = yes;
input showAtrMovAvg     = no; #false, "Show Atr Moving Average as Confluence?"
input movingAverageType = {"SMA", "Hull", default "EMA", "WMA", "DEMA"}; # "MA Type"
input movingAveragePeriod = 50;    # "Moving Average Period"

def na = Double.NaN;
def last = IsNaN(close);
def current = GetAggregationPeriod();
def tf = Max(current, timeframe);
def sourceDema = demaSource;
def source = Fundamental(FundamentalType = demaSource, Period = tf);

DefineGlobalColor("up", Color.CYAN);
DefineGlobalColor("dn", CreateColor(247,82,95));
Script ma {
    input src = close;
    input len = 7;
    input type = "DEMA";
    def maOut = if type == "SMA" then Average(src, len) else
                if type == "Hull" then HullMovingAvg(src, len) else
                if type == "WMA" then WMA(src, len) else
                if type == "EMA" then ExpAverage(src, len) else DEMA(src, len);
    plot out = maOut;
}
#// Function
script DemaAtrWithBands {
    input src = close;
    input lookback = 14;
    input atrFactor = 1.7;
    input tf = 300000;
    def tr  = TrueRange(high(Period = tf), close(Period = tf), low(Period = tf));
    def nzTr = if isNaN(tr) then nzTr[1] else tr;
    def atr = WildersAverage(nzTr, lookback);
    def trueRange = atr * atrFactor;
    def DemaAtr;
    def PreDemaAtr = if DemaAtr[1] then DemaAtr[1] else src;
    def trueRangeUpper = src + trueRange;
    def trueRangeLower  = src - trueRange;
    if trueRangeLower > PreDemaAtr {
        DemaAtr = trueRangeLower;
    } else if trueRangeUpper < PreDemaAtr {
        DemaAtr = trueRangeUpper;
    } else {
        DemaAtr = PreDemaAtr;
    }
    plot dtr = if DemaAtr then DemaAtr else Double.NaN;
    plot up = if DemaAtr then DemaAtr + trueRange else Double.NaN;
    plot dn = if DemaAtr then DemaAtr - trueRange else Double.NaN;
}
#// Function Out
def movAvgSrc = ma(source, demaPeriod, atrMovAvgType);
def DemaAtr = DemaAtrWithBands(movAvgSrc, AtrPeriod, atrFactor, tf).dtr;
def DemaAtrUp = DemaAtrWithBands(movAvgSrc, AtrPeriod, atrFactor, tf).up;
def DemaAtrDn = DemaAtrWithBands(movAvgSrc, AtrPeriod, atrFactor, tf).dn;
def maOut = ma(DemaAtr, movingAveragePeriod, movingAverageType);

#// Conditions
def DemaAtrLong  = DemaAtr > DemaAtr[1] ;
def DemaAtrShort = DemaAtr < DemaAtr[1];
def Trend = if DemaAtrLong then 1 else if DemaAtrShort then -1 else Trend[1];
def dir = if !showBand then na else if trend>0 then 1 else if trend < 0 then -1 else 0;

#// Plotting
plot nATR = if showDemaAtr and !last then DemaAtr else na;     # "ATR"
plot MovAvg = if showAtrMovAvg and !last then maOut else na;   # "Moving Average"
MovAvg.SetDefaultColor(Color.YELLOW);
nATR.SetLineWeight(2);
nATR.AssignValueColor(if Trend > 0 then GlobalColor("up") else
                      if Trend < 0 then GlobalColor("dn") else Color.GRAY);

# Cloud
AddCloud(if (dir > 0 or dir[1] > 0) then DemaAtrUp else na, DemaAtrDn, Color.DARK_GREEN);
AddCloud(if (dir < 0 or dir[1] < 0) then DemaAtrUp else na, DemaAtrDn, Color.DARK_RED);
AddCloud(if (dir == 0 or dir[1] == 0) then DemaAtrUp else na, DemaAtrDn, Color.DARK_GRAY);

# bar Color

AssignPriceColor(if !colorCandles then Color.CURRENT else
                 if Trend > 0 then Color.GREEN else
                 if Trend < 0 then Color.RED else Color.GRAY);

#-- END of CODE
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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