Alphatrends 5-Day Simple Moving Average

andytos

New member
VIP
Hello Samer800,
Can you write a script for Brian Shannon's Alphatrends 5-Day Simple Moving Average for TOS. Thank you
 
Solution
Enjoy!
Code:
def agg_ticks = GetAggregationPeriod();       # milliseconds per candle
def market_1day_ticks = 23400000;             # 6.5 h x 60 x 60 x 1000
def length = (5 * market_1day_ticks) / agg_ticks;        # candles in 5 days
plot D5_MovAvg = MovingAverage(averageType.SIMPLE, close, length);

Or if you'd like just one line of code: The above equals this.
Code:
plot D5_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());
Enjoy!
Code:
def agg_ticks = GetAggregationPeriod();       # milliseconds per candle
def market_1day_ticks = 23400000;             # 6.5 h x 60 x 60 x 1000
def length = (5 * market_1day_ticks) / agg_ticks;        # candles in 5 days
plot D5_MovAvg = MovingAverage(averageType.SIMPLE, close, length);

Or if you'd like just one line of code: The above equals this.
Code:
plot D5_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());
 
Last edited by a moderator:
Solution

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

Enjoy!
Code:
def agg_ticks = GetAggregationPeriod();       # milliseconds per candle
def market_1day_ticks = 23400000;             # 6.5 h x 60 x 60 x 1000
def length = (5 * market_1day_ticks) / agg_ticks;        # candles in 5 days
plot 5D_MovAvg = MovingAverage(averageType.SIMPLE, close, length);

Or if you'd like just one line of code: The above equals this.
Code:
plot 5D_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());
This code is not working. Received error message. Thank you
 
Last edited by a moderator:
Looking at the original code (plot D5_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod())) and doing a quick analysis we find the intent is to calculate a 5-day simple moving average (D5_MovAvg) by dividing a constant (117,000,000) by the aggregation period (in milliseconds) to determine the lookback period.

Aggregation Period: GetAggregationPeriod() returns the chart’s time interval in milliseconds (e.g., 1 minute = 60,000 ms, 1 day = 86,400,000 ms).

We would calculate:

117,000,000 ms ≈ 1.354 days (since 86,400,000 ms = 1 day).

117000000 / GetAggregationPeriod() adjusts the period dynamically. For a daily chart (86,400,000 ms), this yields ~1.354, which is scaled to ~5 days when interpreted as a target number of bars (multiplying by a factor to approximate 5 trading days, likely an intended adjustment).

The issue is that the division alone doesn’t directly yield a 5-day period unless the constant and logic are adjusted. It seems the intent was to approximate 5 trading days (~1,080 minutes or 64,800,000 ms for 5 days with 6.5-hour trading sessions), but 117,000,000 ms suggests a miscalculation. I’ll assume the goal is a 5-day SMA and correct the logic.

To achieve a true 5-day simple moving average we calculate a trading day is ~6.5 hours (23,400,000 ms), and 5 days = 117,000,000 ms. However, GetAggregationPeriod() is the chart’s interval, not total session time. For a daily chart, the period should be 5 bars (since 1 bar = 1 day). The original formula likely intended 117000000 as a proxy for 5 days in milliseconds, but it needs adjustment. I’ll use a fixed 5-bar lookback for daily charts and scale appropriately for other timeframes.

The scanner will identify stocks where the closing price crosses above or below the 5-day SMA, a common trading signal. I’ll include a filter to detect this condition, adjustable via input.

Code:
# Scanner for 5-Day Simple Moving Average Cross  DAILY ONLY
# Adapted from: plot D5_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());
# v.1 scanner by Antwerks 07/26/2025

# --- Inputs ---
input crossType = {default "Above", "Below"}; # Choose cross direction
input priceType = {default "Close", "Open", "High", "Low"}; # Price to compare

# --- Variables ---
def aggPeriod = GetAggregationPeriod();
def barsPerDay = if aggPeriod <= 86400000 then 86400000 / aggPeriod else 1; # Bars per day (approx.)
def lookbackPeriod = if aggPeriod <= 86400000 then 5 * (86400000 / aggPeriod) else 5; # 5-day equivalent
def movAvg = MovingAverage(averageType.SIMPLE, close, lookbackPeriod);
def comparePrice = if priceType == priceType.Close then close
                  else if priceType == priceType.Open then open
                  else if priceType == priceType.High then high
                  else low;

# --- Scan Condition ---
plot scan = if crossType == crossType.Above and comparePrice crosses above movAvg then 1
            else if crossType == crossType.Below and comparePrice crosses below movAvg then 1
            else 0;
 
Last edited by a moderator:
Indicator with thermal and labels:
Code:
DEF D5_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());


input showSMA = yes;
input colorSlope = yes;
input showLabel = yes;

def isDaily = GetAggregationPeriod();
def sma = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());

plot SMA5 = if showSMA then sma else Double.NaN;

# Slope coloring
def slopeUp = sma > sma[1];
def slopeDn = sma < sma[1];

SMA5.AssignValueColor(
if !colorSlope then Color.WHITE
else if slopeUp then Color.GREEN
else if slopeDn then Color.RED
else Color.GRAY
);

SMA5.SetLineWeight(3);
SMA5.SetStyle(Curve.FIRM);

# Label
AddLabel(showLabel, "5-Day SMA: " + Round(sma, 2),
if slopeUp then Color.GREEN
else if slopeDn then Color.RED
else Color.GRAY
);
 
Last edited by a moderator:
Indicator with thermal and labels:
Code:
DEF D5_MovAvg = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());


input showSMA = yes;
input colorSlope = yes;
input showLabel = yes;

def isDaily = GetAggregationPeriod();
def sma = MovingAverage(averageType.SIMPLE, close, 117000000/GetAggregationPeriod());

plot SMA5 = if showSMA then sma else Double.NaN;

# Slope coloring
def slopeUp = sma > sma[1];
def slopeDn = sma < sma[1];

SMA5.AssignValueColor(
if !colorSlope then Color.WHITE
else if slopeUp then Color.GREEN
else if slopeDn then Color.RED
else Color.GRAY
);

SMA5.SetLineWeight(3);
SMA5.SetStyle(Curve.FIRM);

# Label
AddLabel(showLabel, "5-Day SMA: " + Round(sma, 2),
if slopeUp then Color.GREEN
else if slopeDn then Color.RED
else Color.GRAY
);
Love this but would love the ability to color bars when slope color changes and ability to change the colors of the slope ( and obviously this will change the bar colors).
 
Love this but would love the ability to color bars when slope color changes and ability to change the colors of the slope ( and obviously this will change the bar colors).
TRY THIS
Code:
# Enhanced 5-Day SMA with Matching Candle Coloring (Fixed to Red/Green)

# --- Inputs ---
input showSMA = yes;
input colorSlope = yes;
input showLabel = yes;
input slopeUpColor = {default GREEN, RED, WHITE, YELLOW, CYAN, MAGENTA, GRAY}; # Default GREEN
input slopeDownColor = {default RED, GREEN, WHITE, YELLOW, CYAN, MAGENTA, GRAY}; # Default RED

# --- SMA Calculation ---
def isDaily = GetAggregationPeriod();
def sma = MovingAverage(averageType.SIMPLE, close, 117000000 / GetAggregationPeriod());

plot SMA5 = if showSMA then sma else Double.NaN;

# --- Slope Logic ---
def slopeUp = sma > sma[1];
def slopeDn = sma < sma[1];

# --- SMA Coloring and Styling ---
SMA5.AssignValueColor(
    if !colorSlope then Color.WHITE
    else if slopeUp then if slopeUpColor == slopeUpColor.GREEN then Color.GREEN else GetColor(slopeUpColor)
    else if slopeDn then if slopeDownColor == slopeDownColor.RED then Color.RED else GetColor(slopeDownColor)
    else Color.GRAY
);
SMA5.SetLineWeight(3);
SMA5.SetStyle(Curve.FIRM);

# --- Candle Coloring ---
AssignPriceColor(
    if !colorSlope then Color.CURRENT
    else if slopeUp then if slopeUpColor == slopeUpColor.GREEN then Color.GREEN else GetColor(slopeUpColor)
    else if slopeDn then if slopeDownColor == slopeDownColor.RED then Color.RED else GetColor(slopeDownColor)
    else Color.CURRENT
);

# --- Label ---
AddLabel(showLabel, "5-Day SMA: " + Round(sma, 2),
    if !colorSlope then Color.GRAY
    else if slopeUp then if slopeUpColor == slopeUpColor.GREEN then Color.GREEN else GetColor(slopeUpColor)
    else if slopeDn then if slopeDownColor == slopeDownColor.RED then Color.RED else GetColor(slopeDownColor)
    else Color.GRAY
);
 
Last edited by a moderator:
Cool, but maybe allow for the colors to be in globals and allow to change both the line/slope and candle bars. In this instance I see orange candles above and below, which I believe should be different for above and below the sma
1753661133605.png
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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