Indicator · Pine Script v6 · On the chart

Colored TMA Trend Signals [josseliani]

by theonetrade· code credited to josseliani

Colored TMA Trend Signals calculates a trailing Triangular Moving Average (TMA) and surrounding standard deviation bands based on a selectable price source, with optional EMA smoothing.

View on GitHub

GitHub stars34on the repository
Pine versionv6current
Lines of code145
Settings13inputs
LicenceMIT
Last update2 weeks ago8 Nov 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

145 lines of Pine Script v6 from assets/indicator/bit-exact/colored_tma_trend_signals_josseliani_LOqMbiyG.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

colored_tma_trend_signals_josseliani_LOqMbiyG.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © josseliani

//@version=6
indicator("Colored TMA Trend Signals [josseliani]", overlay=true, max_labels_count=500)

// ─────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────
groupTma = "TMA"
halfLength = input.int(12, "Half Length", minval=1, group=groupTma)
priceMode = input.string("Weighted Price", "Price Source", options=["Close", "Open", "High", "Low", "Median Price", "Typical Price", "Weighted Price"], group=groupTma)
bandsDeviation = input.float(2.0, "Band Deviation", minval=0.1, step=0.1, group=groupTma, tooltip="Standard-deviation multiplier for the bands around TMA.")
useSmoothing = input.bool(false, "Use Source Smoothing", group=groupTma)
smoothingPeriod = input.int(12, "Smoothing Period", minval=1, group=groupTma)

groupVisual = "VISUAL"
showBands = input.bool(true, "Show Bands", group=groupVisual)
showTrendSignals = input.bool(true, "Show TMA Color-Change Signals", group=groupVisual)
lineWidth = input.int(2, "TMA Line Width", minval=1, maxval=5, group=groupVisual)

groupTrade = "TRADE SIGNALS"
showTradeSignals = input.bool(true, "Show BUY/SELL Labels", group=groupTrade, tooltip="Visual option only. Trade alerts remain active when labels are hidden.")
tradeLevel = input.string("TMA", "Break Level", options=["TMA", "Bands"], group=groupTrade)
confirmBars = input.int(3, "Confirm Bars", minval=1, maxval=10, group=groupTrade, tooltip="Confirmation is checked exactly on the Nth consecutive close beyond the selected level. If blocked, the sequence must reset before another confirmation is checked.")
tradeOnlyWithTrend = input.bool(true, "Only With TMA Trend", group=groupTrade, tooltip="BUY only while TMA is green, SELL only while red.")
onePerColor = input.bool(true, "One Trade Per Color", group=groupTrade, tooltip="A bullish turn unlocks one BUY and blocks SELL. A bearish turn unlocks one SELL and blocks BUY. After a signal, that direction stays locked until a new matching color turn.")

// ─────────────────────────────────────────────────────────────
// PRICE SOURCE
// ─────────────────────────────────────────────────────────────
src = switch priceMode
    "Open" => open
    "High" => high
    "Low" => low
    "Median Price" => hl2
    "Typical Price" => hlc3
    "Weighted Price" => hlcc4
    => close

base = useSmoothing ? ta.ema(src, smoothingPeriod) : src

// ─────────────────────────────────────────────────────────────
// TMA AND STANDARD-DEVIATION BANDS
// ─────────────────────────────────────────────────────────────
// Two equal-length SMAs produce a trailing triangular MA.
// Effective length: halfLength * 2 - 1. No future bars are used.
tmaLen = halfLength * 2 - 1
tma = ta.sma(ta.sma(base, halfLength), halfLength)
deviation = ta.stdev(base, tmaLen)
upperBand = tma + deviation * bandsDeviation
lowerBand = tma - deviation * bandsDeviation
atr = ta.atr(14)

trendUp = tma > tma[1]
trendDown = tma < tma[1]
tmaColor = trendUp ? color.lime : trendDown ? color.red : color.gray

// ─────────────────────────────────────────────────────────────
// CONFIRMED COLOR CHANGES
// ─────────────────────────────────────────────────────────────
// Flat bars preserve the last directional trend for turn detection.
var int lastSolidTrend = 0
currTrend = trendUp ? 1 : trendDown ? -1 : 0
bullishTurn = false
bearishTurn = false

if barstate.isconfirmed and currTrend != 0
    bullishTurn := currTrend == 1 and lastSolidTrend == -1
    bearishTurn := currTrend == -1 and lastSolidTrend == 1
    lastSolidTrend := currTrend

// ─────────────────────────────────────────────────────────────
// TRADE CONFIRMATION
// ─────────────────────────────────────────────────────────────
bullBreakLevel = tradeLevel == "Bands" ? upperBand : tma
bearBreakLevel = tradeLevel == "Bands" ? lowerBand : tma

// These counters run independently of TMA color changes.
var int barsAbove = 0
var int barsBelow = 0
barsAbove := close > bullBreakLevel ? barsAbove + 1 : 0
barsBelow := close < bearBreakLevel ? barsBelow + 1 : 0

var bool longUsedThisColor = false
var bool shortUsedThisColor = false

if bullishTurn
    longUsedThisColor := false
    shortUsedThisColor := true

if bearishTurn
    shortUsedThisColor := false
    longUsedThisColor := true

trendAllowsLong = not tradeOnlyWithTrend or trendUp
trendAllowsShort = not tradeOnlyWithTrend or trendDown
longSlotFree = not onePerColor or not longUsedThisColor
shortSlotFree = not onePerColor or not shortUsedThisColor
tradeBull = false
tradeBear = false

// Exact equality is intentional: blocked confirmations are not reused.
// Signal calculation is independent of label visibility.
if barstate.isconfirmed
    if barsAbove == confirmBars and trendAllowsLong and longSlotFree
        tradeBull := true
        longUsedThisColor := true

    if barsBelow == confirmBars and trendAllowsShort and shortSlotFree
        tradeBear := true
        shortUsedThisColor := true

// ─────────────────────────────────────────────────────────────
// PLOTS
// ─────────────────────────────────────────────────────────────
plot(tma, title="TMA", color=tmaColor, linewidth=lineWidth)
plot(showBands ? upperBand : na, title="Upper Band", color=color.new(color.gray, 50))
plot(showBands ? lowerBand : na, title="Lower Band", color=color.new(color.gray, 50))

plotshape(showTrendSignals and bullishTurn ? tma : na, title="TMA Bullish Color Change", style=shape.triangleup, location=location.absolute, color=color.lime, size=size.tiny)
plotshape(showTrendSignals and bearishTurn ? tma : na, title="TMA Bearish Color Change", style=shape.triangledown, location=location.absolute, color=color.red, size=size.tiny)

// ─────────────────────────────────────────────────────────────
// BUY / SELL LABELS
// ─────────────────────────────────────────────────────────────
// Vertical spacing only. Labels remain on the actual signal bar.
labelGapAtr = 1.5
gap = math.max(atr * labelGapAtr, high - low)

if showTradeSignals and tradeBull
    label.new(bar_index, low - gap, "BUY", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_up, color=color.new(color.lime, 70), textcolor=color.lime, size=size.small)

if showTradeSignals and tradeBear
    label.new(bar_index, high + gap, "SELL", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_down, color=color.new(color.red, 70), textcolor=color.red, size=size.small)

// ─────────────────────────────────────────────────────────────
// ALERTS
// ─────────────────────────────────────────────────────────────
alertcondition(bullishTurn, title="TMA Bullish Color Change", message="Colored TMA: bullish color change on {{ticker}} {{interval}}")
alertcondition(bearishTurn, title="TMA Bearish Color Change", message="Colored TMA: bearish color change on {{ticker}} {{interval}}")
alertcondition(bullishTurn or bearishTurn, title="Any TMA Color Change", message="Colored TMA: color changed on {{ticker}} {{interval}}")
alertcondition(tradeBull, title="Trade Long", message="Colored TMA: trade long on {{ticker}} {{interval}}")
alertcondition(tradeBear, title="Trade Short", message="Colored TMA: trade short on {{ticker}} {{interval}}")
alertcondition(tradeBull or tradeBear, title="Any Trade Signal", message="Colored TMA: trade signal on {{ticker}} {{interval}}")

Overview

Colored TMA Trend Signals [josseliani] colors the TMA trend line to indicate directional changes and plots visual BUY and SELL breakout signals when price closes beyond the TMA or volatility bands for a set number of confirmation bars. Inputs allow customization of TMA half-length, band multiplier, confirmation bar counts, trend alignment filters, and single-signal-per-color toggles. It plots directly on the main price chart.

Details

Published by

theonetrade on GitHub

Code credit

josseliani, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Half Lengthint12halfLength
Price SourcestringWeighted PricepriceMode
Band Deviationfloat2.0bandsDeviation
Use Source SmoothingboolfalseuseSmoothing
Smoothing Periodint12smoothingPeriod
Show BandsbooltrueshowBands
Show TMA Color-Change SignalsbooltrueshowTrendSignals
TMA Line Widthint2lineWidth
Show BUY/SELL LabelsbooltrueshowTradeSignals
Break LevelstringTMAtradeLevel
Confirm Barsint3confirmBars
Only With TMA TrendbooltruetradeOnlyWithTrend
Show all 13 settings
SettingTypeDefaultVariable
One Trade Per ColorbooltrueonePerColor
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

321 stars

This indicator plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 8 days ago · MIT GitHub repository of Multiple Moving Averages

NVDA Trend Ribbon

by longsurf-ai
280 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated 4 weeks ago · MIT GitHub repository of NVDA Trend Ribbon

Bollinger Bands Force

by harryguiacorn
220 stars

This indicator modifies standard Bollinger Bands to measure directional trend force based on line alignment. It calculates a simple moving average basis along with upper and lower volatility bands. When all three lines move upward or downward simultaneously, i

Indicator v5 Volatility & bandsTrend
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Force

Adaptive MA Slope

by capissimo
114 stars

This indicator calculates Kaufman's Adaptive Moving Average (KAMA) on a chosen price source and determines trend direction based on the slope across a configurable lookback window. Signals can be filtered by short-term volatility expansion using ATR comparison

Indicator v4 Moving averagesTrend
Updated 2 years ago · None stated GitHub repository of Adaptive MA Slope

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers