Repaints Accumulation Swing Index MTF Indicator for ThinkorSwim

Repaints

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
A request was made for a MTF (Multi Timeframe) version of the TOS Accumulation Swing Index. I use to rely on MTF indicators extensively. Using a higher agg, eliminated the little flubbles that would kick me out too early.

However, the downside of MTF indicator as part of an exit strategy is that you have to wait for the higher aggregation candle to close before the signal is confirmed and if a stock is headed south waiting for a 10-20min candle is a long wait. Therefore I do not use MTF indicators as part of my exit strategies. A non-MTF indicator combined with zscore is more efficient.

Code:
# TOS MTF AccumulationSwingIndex
#global variables
input agg  = AggregationPeriod.TEN_MIN ;
def cclose = close(period = agg);
def oopen  = open(period = agg);
def hhigh  = high(period = agg);
def llow   = low(period = agg);
# 
input smaLength = 10;
def limit = 30;
def AbsHighClose = AbsValue(hhigh - cclose[1]);
def AbsLowClose = AbsValue(llow - cclose[1]);
def AbsCloseOpen = AbsValue(cclose[1] - oopen[1]);
def K = If(AbsHighClose >= AbsLowClose, AbsHighClose, AbsLowClose);
def R = If(AbsHighClose >= AbsLowClose,
        If(AbsHighClose >= (hhigh - llow), AbsHighClose - 0.5 * AbsLowClose + 0.25 * AbsCloseOpen, (hhigh - llow) + 0.25 * AbsCloseOpen),
        If(AbsLowClose >= (hhigh - llow),  AbsLowClose - 0.5 * AbsHighClose + 0.25 * AbsCloseOpen, (hhigh - llow) + 0.25 * AbsCloseOpen));
def nRes = If(R != 0,
            (50 * (((cclose - cclose[1]) + 0.50 * (cclose - oopen) + 0.25 * (cclose[1] - oopen[1])) / R ) * K / limit) + if !IsNaN(nRes[1]) then nRes[1] else 0,
            0 + if !IsNaN(nRes[1]) then nRes[1] else 0);
def ASI = nRes;
def sma = SimpleMovingAvg(ASI,smaLength);
# ########################################################
# charting and formatting
declare lower;
plot pASI = ASI;
pASI.SetLineWeight(3);
pASI.AssignValueColor(if asi>sma then Color.Green else Color.RED);

plot pSMA = sma;
pSMA.SetPaintingStrategy(PaintingStrategy.DASHES);
pSMA.SetLineWeight(1);
pSMA.AssignValueColor(Color.VIOLET);

DefineGlobalColor("bear",  CreateColor(225, 0, 0)) ;
DefineGlobalColor("bull",  CreateColor(0, 165, 0)) ;
AddCloud(pASI, pSMA, GlobalColor("bull"), GlobalColor("bear"));

A10fi0U.png
 
Last edited:
thanks for that. and for referencing z score indicator!

p.s. the ASI_MTF indicator code seems to be missing a plot, according to my error, as well as: declare lower; .... i think.
 
@floydddd The study works fine. A common error when using MTF indicators is trying to use a time frame that is lower than the chart you are posting it on. In ThinkorSwim, you can display data from a higher timeframe onto a lower timeframe but not the other way around.
 
@Jonas99
Z-Score Label:
Ruby:
#Computes and plots the Zscore
#Provided courtesy of ThetaTrend.com
#Feel free to share the indicator, but please provide a link back to ThetaTrend.com

input price = close;
input length = 20;
input ZavgLength = 20;

#Initialize values
def oneSD = stdev(price,length);
def avgClose = simpleMovingAvg(price,length);
def ofoneSD = oneSD*price[1];
def Zscorevalue = ((price-avgClose)/oneSD);
def avgZv = average(Zscorevalue,20);

#Compute and plot Z-Score
def Zscore = ((price-avgClose)/oneSD);

DefineGlobalColor("Bear",  CreateColor(225, 0, 0)) ;
DefineGlobalColor("Bull",  CreateColor(0, 165, 0)) ;
AddLabel(yes, "Zscore: " +Zscore, if Zscore>0 then GlobalColor("Bull") else GlobalColor("Bear"));

@Docbrown83
Original Indicator: https://www.thetatrend.com/z-score-an-indicator-to-define-overbought-and-oversold-thinkscript/
 
Last edited:
@Jonas99
Z-Score Label:
Ruby:
#Computes and plots the Zscore
#Provided courtesy of ThetaTrend.com
#Feel free to share the indicator, but please provide a link back to ThetaTrend.com

input price = close;
input length = 20;
input ZavgLength = 20;

#Initialize values
def oneSD = stdev(price,length);
def avgClose = simpleMovingAvg(price,length);
def ofoneSD = oneSD*price[1];
def Zscorevalue = ((price-avgClose)/oneSD);
def avgZv = average(Zscorevalue,20);

#Compute and plot Z-Score
def Zscore = ((price-avgClose)/oneSD);

DefineGlobalColor("Bear",  CreateColor(225, 0, 0)) ;
DefineGlobalColor("Bull",  CreateColor(0, 165, 0)) ;
AddLabel(yes, "Zscore: " +Zscore, if Zscore>0 then GlobalColor("Bull") else GlobalColor("Bear"));

@Docbrown83
Original Indiciator: https://www.thetatrend.com/z-score-an-indicator-to-define-overbought-and-oversold-thinkscript/
@MerryDay Thank you so much for this, just saw this.
 
Hey good people...

I've been playing around with this lovely indicator and think I may have stumbled upon a decent swing/scalp strategy.

I'm usually focused only on futures and forex...not sure how well this would work for other securities. Here's the deal:

  • 30 min chart
  • MTF Accumulation Swing index on 1hr, 9
  • StochRSI; 21, 21, 8, 5
  • ATR 14

With the StochRSI below 25, enter long on next bar after MFT ASI changes from red to green. TP = 2x ATR, SL = 1x ATR

With the StochRSI above 75, enter short on next bar after MFT ASI changes from green to red. TP = 2x ATR, SL = 1x ATR

That's it. Pretty easy, eh?

By combining with the StochRSI, it seems to do a good job of weeding out the poor/false signals for the ASI. Of course it's not perfect. As you can see on the chart below I've cherry picked some entries. Looks like there's an entry that would have stopped out...nothing is perfect.

Play around with it and report back with any success stories or updates/tweaks! @MerryDay how does this jive with your technique with this indicator?

I will try to get this version of the ASI coded up in Tradingview...would love to backtest the strategy further and play around with the TP. Better yet I'd love to get it coded into MT4 or MT5 if anyone is up for the challenge?

rE6nTxg.jpg
 
@MerryDay, @BenTen is it possible you guys can help us to create a scan, watchlist column, and alerts when there is a trend reversal on this swing index?

Please check the image where it would be useful to add the signals:

rpNyk5r.png


I have tested it and I just get rid of 10+ indicators for just using this one which, compared to many other indicators, won't produce too much notice and false signals if used combined
Hi, How can I get your upper-level cloud indicator? It looks interesting and I should like to try it. Thanks in advance
 
Hi, How can I get your upper-level cloud indicator? It looks interesting and I should like to try it. Thanks in advance
Hey,

Yes, this is the code for EMA clouds

Code:
#Multiple EMA Cloud
#For Stock Analysis : http://TheTopList.com
input ema1low = 5;
input ema1high = 13;
input ema2low = 34;
input ema2high = 50;
input ema3low = 72;
input ema3high = 89;
def ema5 = ExpAverage(close, ema1low);
def ema13 = ExpAverage(close, ema1high);
AddCloud(ema5, ema13, Color.green, Color.RED);
def ema34 = ExpAverage(close, ema2low);
def ema50 = ExpAverage(close, ema2high);
AddCloud(ema34, ema50, Color.cyan, Color.light_gray);
def ema72 = ExpAverage(close, ema3low);
def ema89 = ExpAverage(close, ema3high);
AddCloud(ema72, ema89, Color.blue, Color.yellow);
 
Thanks So much I do appreciate it. Please, What are you using to show the buy and the sell signal. Can I also have it? or could you guide me on how to get it if it already posted here?
 
Thanks So much I do appreciate it. Please, What are you using to show the buy and the sell signal. Can I also have it? or could you guide me on how to get it if it already posted here?
Yes, no problem, https://tos.mx/UftNtlU, I have it combined with Keltner Channel. PLease check it.

The code is:

Code:
# MomentumKeltnerChannels
# Pensar
# 06/06/2020
# Based on the FW_MOBO code by TOS user davidinc (aka Firstwave, aka David Elliott)
# Modified code to use Keltner Channels, changed code structure.
# Added colored price and user-adjustable global colors.

# Trend Reversal Scanner
# Scanner by [URL]https://usethinkscript.com/u/theelderwand[/URL]
# Discuss [URL]https://usethinkscript.com/d/183-trend-reversal-indicator-with-signals-for-thinkorswim[/URL]


#Inputs
input length       =     34;
input factor       =     0.5;
input displace     =     0;
input price        =     close;
input type         =     AverageType.SIMPLE;
input pricecolor   =     yes;
input fill         =     yes;
input arrows       =     yes;
input alerts       =     yes;
input sound        =     {default "Ding", "Bell", "Chimes", "NoSound", "Ring"};

#Variables
def nan      =   double.nan;
def shift    =   factor * MovingAverage(type, TrueRange(high, close, low), length);
def avg      =   MovingAverage(type, price, length);
def line1    =   avg[-displace] - shift[-displace];
def line2    =   avg[-displace] + shift[-displace];
def Chg      =   if(close > line2, 1, if(close < line1, -1, 0));
def Hold     =   CompoundValue(1,if(Hold[1] == Chg or Chg == 0, Hold[1], if(Chg == 1, 1, -1)), 0);
def ArUp     =   if !arrows or Hold[0] == Hold[1] then nan else if Hold[0] == 1 then line1 else nan;
def ArDn     =   if !arrows or Hold[0] == Hold[1] then nan else if Hold[0] == -1 then line2 else nan;
def LBUp     =   if fill and Hold[0] == 1 then line2 else nan;
def UBUp     =   if fill and Hold[0] == 1 then line1 else nan;
def LBDn     =   if fill and Hold[0] == -1 then line2 else nan;
def UBDn     =   if fill and Hold[0] == -1 then line1 else nan;
def AlertUp  =   alerts and Hold[1] ==  1 and (Hold[1] <> Hold[2]);
def AlertDn  =   alerts and Hold[1] == -1 and (Hold[1] <> Hold[2]);

#Colors
DefineGlobalColor("Cloud Up", color.dark_green);
DefineGlobalColor("Cloud Dn", color.dark_red);
DefineGlobalColor("Channel Up", color.green);
DefineGlobalColor("Channel Down", color.red);
DefineGlobalColor("Price Up", color.green);
DefineGlobalColor("Price Neutral", color.gray);
DefineGlobalColor("Price Down", color.red);

#Plots
plot UB = line1;
     UB.SetLineWeight(1);
     UB.AssignValueColor(if Hold[0] == 1 then GlobalColor("Channel Up")
                         else GlobalColor("Channel Down"));
plot LB = line2;
     LB.SetLineWeight(1);
     LB.AssignValueColor(if Hold[0] == 1 then GlobalColor("Channel Up")
                         else GlobalColor("Channel Down"));
plot BOA = ArUp;
     BOA.SetPaintingStrategy(PaintingStrategy.Arrow_Up);
     BOA.SetDefaultColor(color.green);
     BOA.SetLineWeight(2);
plot BDA = ArDn;
     BDA.SetPaintingStrategy(PaintingStrategy.Arrow_Down);
     BDA.SetDefaultColor(color.red);
     BDA.SetLineWeight(2);

#Clouds
AddCloud(LBUp, UBUp, GlobalColor("Cloud Up"), GlobalColor("Cloud Dn"));
AddCloud(LBDn, UBDn, GlobalColor("Cloud Dn"), GlobalColor("Cloud Up"));

#Price Color
#AssignPriceColor(if pricecolor then if close > line2 then GlobalColor("Price Up")
                 #else if close < line1 then GlobalColor("Price Down")
                 #else GlobalColor("Price Neutral")
                 #else color.current);

#Alerts
Alert(AlertUp, "BREAKOUT!",  Alert.Bar, Sound);
Alert(AlertDn, "BREAKDOWN!", Alert.Bar, Sound);


input bubbles = yes;
input bubbleoffset = .0005;

def price2 = close;
def superfast_length = 9;
def fast_length = 14;
def slow_length = 21;
def displace2 = 0;

def mov_avg9 = ExpAverage(price2[-displace2], superfast_length);
def mov_avg14 = ExpAverage(price2[-displace2], fast_length);
def mov_avg21 = ExpAverage(price2[-displace2], slow_length);

#moving averages
def Superfast = mov_avg9;
def Fast = mov_avg14;
def Slow = mov_avg21;

def buy = mov_avg9 > mov_avg14 and mov_avg14 > mov_avg21 and low > mov_avg9;
def stopbuy = mov_avg9 <= mov_avg14;
def buynow = !buy[1] and buy;
def buysignal = CompoundValue(1, if buynow and !stopbuy then 1 else if buysignal[1] == 1 and stopbuy then 0 else buysignal[1], 0);

def Buy_Signal = buysignal[1] == 0 and buysignal == 1;
def Momentum_Down = buysignal[1] == 1 and buysignal == 0;

def sell = mov_avg9 < mov_avg14 and mov_avg14 < mov_avg21 and high < mov_avg9;
def stopsell = mov_avg9 >= mov_avg14;
def sellnow = !sell[1] and sell;
def sellsignal = CompoundValue(1, if sellnow and !stopsell then 1 else if sellsignal[1] == 1 and stopsell then 0 else sellsignal[1], 0);
def Sell_Signal = sellsignal[1] == 0 and sellsignal;


input method = {default average, high_low};
def percentamount = .01;
def revAmount = .05;
def atrreversal = 2.0;
def atrlength = 5;
def pricehigh = high;
def pricelow = low;
def averagelength = 5;
def averagetype = AverageType.EXPONENTIAL;
def mah = MovingAverage(averagetype, pricehigh, averagelength);
def mal = MovingAverage(averagetype, pricelow, averagelength);
def priceh = if method == method.high_low then pricehigh else mah;
def pricel = if method == method.high_low then pricelow else mal;
def EI = ZigZagHighLow("price h" = priceh, "price l" = pricel, "percentage reversal" = percentamount, "absolute reversal" = revAmount, "atr length" = atrlength, "atr reversal" = atrreversal);
rec EISave = if !IsNaN(EI) then EI else GetValue(EISave, 1);
def chg2 = (if EISave == priceh then priceh else pricel) - GetValue(EISave, 1);
def isUp = chg2 >= 0;
def EIL = if !IsNaN(EI) and !isUp then pricel else GetValue(EIL, 1);
def EIH = if !IsNaN(EI) and isUp then priceh else GetValue(EIH, 1);
def dir = CompoundValue(1, if EIL != EIL[1] or pricel == EIL[1] and pricel == EISave then 1 else if EIH != EIH[1] or priceh == EIH[1] and priceh == EISave then -1 else dir[1], 0);
def signal = CompoundValue(1, if dir > 0 and pricel > EIL then if signal[1] <= 0 then 1 else signal[1] else if dir < 0 and priceh < EIH then if signal[1] >= 0 then -1 else signal[1] else signal[1], 0);
def zz = ZigZagHighLow("price h" = high, "price l" = low, "percentage reversal" = PercentAmount,
"absolute reversal" = RevAmount, "atr length" = ATRlength, "atr reversal" = ATRreversal);

def ReversalAmount = if (close * PercentAmount / 100) > Max(RevAmount < ATRreversal * reference ATR(ATRlength), RevAmount)
                     then (close * PercentAmount / 100)
                     else if RevAmount < ATRreversal * reference ATR(ATRlength)
                          then ATRreversal * reference ATR(ATRlength)
                          else RevAmount;

def isConf = AbsValue(chg) >= ReversalAmount or (IsNaN(GetValue(zz, 1)) and GetValue(isConf, 1));
def zzSave = if !IsNaN(zz) then zz else GetValue(zzSave, 1);
def chgN = (if zzSave == high then high else low) - GetValue(zzSave, 1);
def isUpN = chg >= 0;


def bullish2 = signal > 0 and signal[1] <= 0;
plot upArrow = bullish2;
upArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
upArrow.SetDefaultColor(CreateColor(145, 210, 144));

def bearish2 = signal < 0 and signal[1] >= 0;
plot downArrow = bearish2;
downArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
downArrow.SetDefaultColor(CreateColor(255, 15, 10));

#AssignPriceColor(if bullish2 then Color.YELLOW else if bearish2 then Color.YELLOW else Color.CURRENT);


# RSI IFT

def over_Bought = .5;
def over_Sold = -.5;

def R = reference RSI(5, close) - 50;
def AvgRSI = MovingAverage(AverageType.EXPONENTIAL, R, 9);
def inverseRSI = (Power(Double.E, 2 * AvgRSI) - 1) / (Power(Double.E, 2 * AvgRSI) + 1);
def RSI_IFT_Buy =  (inverseRSI > 0) and (inverseRSI[1] < 0);
def RSI_IFT_Sell = (inverseRSI[1] > 0) and (inverseRSI < 0);

# Buy/Sell Signals

input buySellStrategy = { "BalanceOfPower", default "RSI_IFT" };

#AssignPriceColor(if RSI_IFT_Buy then Color.CYAN else if RSI_IFT_Sell then Color.MAGENTA else Color.CURRENT);


AddChartBubble(bubbles and RSI_IFT_Sell, if isUpN then high * (1 + BubbleOffset) else high * (1 + BubbleOffset), "SELL", Color.magenta, if isUpN then yes else yes);
#AddChartBubble(bubbles and bearish2 , high, "swing high", Color.magenta, no);

AddChartBubble(bubbles and RSI_IFT_Buy,  if isUpN then low * (1 - BubbleOffset) else low * (1 - BubbleOffset), "BUY", Color.cyan,  if isUpN then no else no);
#AddChartBubble(bubbles and bullish2 , low, "swing low", Color.CYAN, no);



# --- End code ---



If you want to disable clouds then comment these lines as follows:

#Clouds
#AddCloud(LBUp, UBUp, GlobalColor("Cloud Up"), GlobalColor("Cloud Dn"));
#AddCloud(LBDn, UBDn, GlobalColor("Cloud Dn"), GlobalColor("Cloud Up"));

If you want to see price color in the candles, un-comment these lines as follows:

#Price Color
AssignPriceColor(if pricecolor then if close > line2 then GlobalColor("Price Up")
                 else if close < line1 then GlobalColor("Price Down")
                 else GlobalColor("Price Neutral")
                 else color.current);

Bearish2 and bullish2 repaints, because it's based on the Trend reversal Indicator, but the buy and sell bubbles is based on RSI_IFT, and it doesn't repaint. Use in conjunction with more indicators to confirm entries...
 
Hey good people...

I've been playing around with this lovely indicator and think I may have stumbled upon a decent swing/scalp strategy.

I'm usually focused only on futures and forex...not sure how well this would work for other securities. Here's the deal:

  • 30 min chart
  • MTF Accumulation Swing index on 1hr, 9
  • StochRSI; 21, 21, 8, 5
  • ATR 14

With the StochRSI below 25, enter long on next bar after MFT ASI changes from red to green. TP = 2x ATR, SL = 1x ATR

With the StochRSI above 75, enter short on next bar after MFT ASI changes from green to red. TP = 2x ATR, SL = 1x ATR

That's it. Pretty easy, eh?

By combining with the StochRSI, it seems to do a good job of weeding out the poor/false signals for the ASI. Of course it's not perfect. As you can see on the chart below I've cherry picked some entries. Looks like there's an entry that would have stopped out...nothing is perfect.

Play around with it and report back with any success stories or updates/tweaks! @MerryDay how does this jive with your technique with this indicator?

I will try to get this version of the ASI coded up in Tradingview...would love to backtest the strategy further and play around with the TP. Better yet I'd love to get it coded into MT4 or MT5 if anyone is up for the challenge?

rE6nTxg.jpg
Looks really promising for futures. Any that you've had the best luck with? Also for the stoch rsi, are you looking for the crossdown on the slow line?
 
Hey, does anyone have a read-up on the accumulation swing index I see on the web there's data on Accumulative, the codes that are similar but the scaling doesn't have the zero line? any insight?
 
Hey, does anyone have a read-up on the accumulation swing index I see on the web there's data on Accumulative, the codes that are similar but the scaling doesn't have the zero line? any insight?
Check this out for an explanation on the main line. The second line is just an average of the ASI. 9 times out of 10 when you see any kind of crossover, the second line that gets crossed is just an average of the first
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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