Natural Moving Average For ThinkOrSwim

halcyonguy

Moderator - Expert
VIP
Lifetime
@MLlalala
@jpmcewen

convert pine study from here
https://www.tradingview.com/script/WkBFJbJD-Natural-Moving-Average-CC/

Code:
# Natural_Moving_Average_00

#//@version=4
#// Copyright (c) 2019-present, Franklin Moormann (cheatcountry)
#// Natural Moving Average [CC] script may be freely distributed under the MIT license.
#study("Natural Moving Average [CC]", overlay=true)

#inp = input(title="Source", type=input.source, defval=close)
#res = input(title="Resolution", type=input.resolution, defval="")
#rep = input(title="Allow Repainting?", type=input.bool, defval=false)
#bar = input(title="Allow Bar Color Change?", type=input.bool, defval=true)
#length = input(title="Length", type=input.integer, defval=40, minval=1)

def bn = barnumber();
def na = double.nan;

input inp = close;
#input res = agg
input rep = no;
input bar = yes;
input length = 40;

#src = security(syminfo.tickerid, res, inp[rep ? 0 : barstate.isrealtime ? 1 : 0])[rep ? 0 : barstate.isrealtime ? 0 : 1]

input src = close;


script nz {
    input data = 0;
    def ret_val = if isNaN(data) then 0 else data;
    plot return = ret_val;
}


#ln = log(src) * 1000
def ln = log(src) * 1000;

#num = 0.0
#denom = 0.0
#for i = 0 to length - 1
#    oi = abs(nz(ln[i]) - nz(ln[i + 1]))
#    num += oi * (sqrt(i + 1) - sqrt(i))
#    denom += oi

def num = fold i = 0 to length - 1
  with p
  while bn > length
  do p + (absvalue( (if isNaN(getvalue(ln, i)) then 0 else getvalue(ln, i)) -
  (if isNaN(getvalue(ln, i+1)) then 0 else getvalue(ln, i+1)) ))
  * (sqrt(i + 1) - sqrt(i));

def denom = fold j = 0 to length - 1
  with q
  do q + (absvalue( (if isNaN(getvalue(ln, j)) then 0 else getvalue(ln, j)) -
  (if isNaN(getvalue(ln, j+1)) then 0 else getvalue(ln, j+1)) ));


#ratio = denom != 0 ? num / denom : 0
def ratio = if denom != 0 then (num / denom) else 0;

#nma = (src * ratio) + (nz(src[1]) * (1 - ratio))
def nma = (src * ratio) + (nz(src[1]) * (1 - ratio));

#slo = src - nma
def slo = src - nma;

#sig = slo > 0 ? slo > nz(slo[1]) ? 2 : 1 : slo < 0 ? slo < nz(slo[1]) ? -2 : -1 : 0
def sig =
 if slo > 0 then
   if slo > nz(slo[1]) then 2 else 1
 else if slo < 0 then
   if slo < nz(slo[1]) then -2 else -1
else 0;


#alertcondition(crossover(sig, 1), "Strong Buy Signal", "Strong Bullish Change Detected")
#alertcondition(crossunder(sig, -1), "Strong Sell Signal", "Strong Bearish Change Detected")
#alertcondition(crossover(sig, 0), "Buy Signal", "Bullish Change Detected")
#alertcondition(crossunder(sig, 0), "Sell Signal", "Bearish Change Detected")

#addchartbubble(1, low, sig, color.yellow, no);

def c = if sig == 2 and sig[1] != 2 then 2
  else if sig == 1 and sig[1] != 1 then 1
  else if sig == -1 and sig[1] != -1 then -1
  else if sig == -22 and sig[1] != -2 then -2
  else 0;


addlabel(1, " ", color.black);
addlabel(c == 2, "Strong Buy Signal", color.green);
addlabel(c == 1, "Buy Signal", color.light_green);
addlabel(c == -1, "Sell Signal", color.light_red);
addlabel(c == -2, "Strong Sell Signal", color.red);


#nmaColor = sig > 1 ? color.green : sig > 0 ? color.lime : sig < -1 ? color.maroon : sig < 0 ? color.red : color.black
#barcolor(bar ? nmaColor : na)
#plot(nma, color=nmaColor, linewidth=2)

plot z = if bar then nma else na;
z.AssignValueColor(
 if sig > 1 then color.green else if sig > 0 then color.lime else if sig < -1 then color.magenta else if sig < 0 then  color.red else  color.black);
z.setlineweight(2);
z.hidebubble();
#
 
Last edited:

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

So I too was hacking away on this. I did a conversion as halcyonguy did, not as complete, but following the same code. I didn't like the way it plotted. So I went on a quest for some different code.

I tried reading the original. It didn't make much sense. I couldn't come up with a way to implement it. I found a version somewhere that used linear regressions... that wasn't right at all. Then I found a bit of code here: https://www.forexfactory.com/thread/958317-mt4-indicators-nmas-ocean I think and it seems to have provided a better implementation that I was otherwise able to come up with.

The code from that site calculated NMA this way:
Code:
nma[i] = nma[i+1]+ratio*(rawPrice-nma[i+1]);
after calculating the ratio in the same way as the top code in this thread.

I have attached my code here.
Code:
declare upper;

def src = close;
input length = 100;
def ln = log(src) * 1000;
# addLabel(yes, "  ln: " + ln + "  ", color.black);

# addLabel(yes, "  ln - ln-1: " + (ln - ln[1]) + "  ", color.black);

def num = fold i = 1 to (length - 1) with a = 0.0 do a + (
        absValue(GetValue(ln, i, length - 1) - GetValue(ln, i + 1, length - 1)) 
            * 
        (sqrt(i + 1) - sqrt(i))
    );

def denom = fold k = 1 to length - 1 with b = 0.0 do b + (
        absValue(GetValue(ln, k, length - 1) - GetValue(ln, k + 1, length - 1))
    );

def ratio = if denom != 0 then num / denom else double.nan;
# addLabel(yes, "  ratio  " + ratio + "  ", color.black);
# def nma_raw = (src * ratio) + ((src[1]) * (1 - ratio));

def nma_raw = nma_raw[1] + ratio * (src - (nma_raw[1]));
plot nma = if barNumber() >= length - 1 then nma_raw else double.nan;
def slo = src - nma;
addLabel(yes, " Ocean Slope: " + slo * 1 + "  ", color.blue);

nma.AssignValueColor(if nma >= nma[1] then color.blue else color.dark_orange);

# AddLabel(yes, " Current NMA: " + nma + "  ", color.blue);

There are a lot of AddLabel() in there that I used for debugging. and if you're not taken with the colours, they're relatively straight forward to change.

Again, not to take away from what @halcyonguy did. But just to offer an alternative. I still don't have a reference for whether my implementation is correct or not.

-mashume
 
So I too was hacking away on this. I did a conversion as halcyonguy did, not as complete, but following the same code. I didn't like the way it plotted. So I went on a quest for some different code.

I tried reading the original. It didn't make much sense. I couldn't come up with a way to implement it. I found a version somewhere that used linear regressions... that wasn't right at all. Then I found a bit of code here: https://www.forexfactory.com/thread/958317-mt4-indicators-nmas-ocean I think and it seems to have provided a better implementation that I was otherwise able to come up with.

The code from that site calculated NMA this way:
Code:
nma[i] = nma[i+1]+ratio*(rawPrice-nma[i+1]);
after calculating the ratio in the same way as the top code in this thread.

I have attached my code here.
Code:
declare upper;

def src = close;
input length = 100;
def ln = log(src) * 1000;
# addLabel(yes, "  ln: " + ln + "  ", color.black);

# addLabel(yes, "  ln - ln-1: " + (ln - ln[1]) + "  ", color.black);

def num = fold i = 1 to (length - 1) with a = 0.0 do a + (
        absValue(GetValue(ln, i, length - 1) - GetValue(ln, i + 1, length - 1))
            *
        (sqrt(i + 1) - sqrt(i))
    );

def denom = fold k = 1 to length - 1 with b = 0.0 do b + (
        absValue(GetValue(ln, k, length - 1) - GetValue(ln, k + 1, length - 1))
    );

def ratio = if denom != 0 then num / denom else double.nan;
# addLabel(yes, "  ratio  " + ratio + "  ", color.black);
# def nma_raw = (src * ratio) + ((src[1]) * (1 - ratio));

def nma_raw = nma_raw[1] + ratio * (src - (nma_raw[1]));
plot nma = if barNumber() >= length - 1 then nma_raw else double.nan;
def slo = src - nma;
addLabel(yes, " Ocean Slope: " + slo * 1 + "  ", color.blue);

nma.AssignValueColor(if nma >= nma[1] then color.blue else color.dark_orange);

# AddLabel(yes, " Current NMA: " + nma + "  ", color.blue);

There are a lot of AddLabel() in there that I used for debugging. and if you're not taken with the colours, they're relatively straight forward to change.

Again, not to take away from what @halcyonguy did. But just to offer an alternative. I still don't have a reference for whether my implementation is correct or not.

-mashume
hi @mashume can you add a candles colors input option, meaning if the price is above the moving average colors candles green and if is below then color red. thanks in advance
 
hi @mashume can you add a candles colors input option, meaning if the price is above the moving average colors candles green and if is below then color red. thanks in advance
Add these lines at the end of the script:
Code:
input color_candles = no;
AssignPriceColor(if color_candles == yes then if close > nma then color.green else color.red else color.current);

-mashume
 
How is this beneficial vs regular Weighted moving average set at 3? I have no idea please enlighten me.
 
How is this beneficial vs regular Weighted moving average set at 4? I have no idea please enlighten me.
Moving Average Indicators are one of the most popular indicators on the Forum. Whether one is more "beneficial" than another is dependent on how you are using it.
Because no indicator should be used in isolation, it is important to find the one that provides confirmation to the other indicators in your strategy.
# # # # #
Recommend you put them both on your chart. Nothing beats personal experience ;)
The only way you will know what the plots are doing, is to observe them on your charts and how they inter-relate with your other indicators.

To determine if this indicator brings value, analyze your overall strategy over different timeframes, across history and with multiple instruments.
# # # # #
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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