Indicator · Pine Script v5 · On the chart

Dual Momentum

by nxtaiapp· code credited to TradeLabX - Dual Momentum Indicator

An overlay indicator based on the global equity momentum approach of comparing assets over a monthly lookback.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code202
Settings11inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago20 Jan 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

202 lines of Pine Script v5 from dual_momentum_indicator_v1-1.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

dual_momentum_indicator_v1-1.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradeLabX - Dual Momentum Indicator
// Based on Gary Antonacci's Global Equity Momentum (GEM) methodology

//@version=5
indicator("Dual Momentum [TradeLabX]",
     overlay=true)

// ═══════════════════════════════════════════════════════════════════════════════
// INPUTS
// ═══════════════════════════════════════════════════════════════════════════════

// Asset Configuration
grp_assets = "═══ ASSET CONFIGURATION ═══"
usEquitySymbol = input.symbol("SPY", "US Equities Symbol", group=grp_assets, tooltip="Primary US equity ETF (default: SPY)")
intlEquitySymbol = input.symbol("EFA", "International Equities Symbol", group=grp_assets, tooltip="International developed markets ETF (default: EFA)")
defensiveSymbol = input.symbol("AGG", "Defensive Asset Symbol", group=grp_assets, tooltip="Bond ETF for defensive positioning (default: AGG)")

// Strategy Parameters
grp_params = "═══ STRATEGY PARAMETERS ═══"
lookbackMonths = input.int(12, "Lookback Period (Months)", minval=1, maxval=24, group=grp_params, tooltip="Number of months for momentum calculation (classic = 12)")
tbillRate = input.float(4.0, "T-Bill Annual Rate (%)", minval=0, maxval=20, step=0.25, group=grp_params, tooltip="Current T-Bill rate for absolute momentum test. Update this manually based on current rates.")

// Display Settings
grp_display = "═══ DISPLAY SETTINGS ═══"
showTable = input.bool(true, "Show Signal Table", group=grp_display)
tablePosition = input.string("top_right", "Table Position", options=["top_right", "top_left", "bottom_right", "bottom_left", "top_center", "bottom_center"], group=grp_display)
showBackground = input.bool(true, "Show Background Color", group=grp_display)
bgTransparency = input.int(90, "Background Transparency", minval=50, maxval=99, group=grp_display)

// Alert Settings
grp_alerts = "═══ ALERT SETTINGS ═══"
alertOnChange = input.bool(true, "Alert on Signal Change", group=grp_alerts)
alertOnMonthEnd = input.bool(true, "Alert on Month End", group=grp_alerts)

// ═══════════════════════════════════════════════════════════════════════════════
// DATA RETRIEVAL
// ═══════════════════════════════════════════════════════════════════════════════

// Request monthly closing prices for each asset
usEquityClose = request.security(usEquitySymbol, "M", close, lookahead=barmerge.lookahead_off)
intlEquityClose = request.security(intlEquitySymbol, "M", close, lookahead=barmerge.lookahead_off)
defensiveClose = request.security(defensiveSymbol, "M", close, lookahead=barmerge.lookahead_off)

// Get historical prices for return calculation
usEquityPast = request.security(usEquitySymbol, "M", close[lookbackMonths], lookahead=barmerge.lookahead_off)
intlEquityPast = request.security(intlEquitySymbol, "M", close[lookbackMonths], lookahead=barmerge.lookahead_off)

// ═══════════════════════════════════════════════════════════════════════════════
// MOMENTUM CALCULATIONS
// ═══════════════════════════════════════════════════════════════════════════════

// Calculate 12-month (or custom lookback) returns
usReturn = (usEquityClose - usEquityPast) / usEquityPast * 100
intlReturn = (intlEquityClose - intlEquityPast) / intlEquityPast * 100

// Convert annual T-Bill rate to comparable period return
tbillReturn = tbillRate  // Already annualized, compare directly to annualized equity returns

// Annualize the equity returns for proper comparison
usReturnAnnualized = usReturn / lookbackMonths * 12
intlReturnAnnualized = intlReturn / lookbackMonths * 12

// ═══════════════════════════════════════════════════════════════════════════════
// DUAL MOMENTUM LOGIC
// ═══════════════════════════════════════════════════════════════════════════════

// Step 1: Relative Momentum - Which equity market is stronger?
usWinsRelative = usReturn > intlReturn
relativeWinner = usWinsRelative ? "US" : "INTL"
winnerReturn = usWinsRelative ? usReturn : intlReturn
winnerReturnAnnualized = usWinsRelative ? usReturnAnnualized : intlReturnAnnualized

// Step 2: Absolute Momentum - Is the winner beating T-Bills?
absoluteMomentumPass = winnerReturnAnnualized > tbillReturn

// Step 3: Final Signal
// Signal codes: 1 = US Equities, 2 = International Equities, 3 = Defensive (Bonds)
var int currentSignal = 3  // Start defensive

if absoluteMomentumPass
    currentSignal := usWinsRelative ? 1 : 2
else
    currentSignal := 3

// Signal names for display
signalName = currentSignal == 1 ? "US EQUITIES" : currentSignal == 2 ? "INTL EQUITIES" : "DEFENSIVE"
signalTicker = currentSignal == 1 ? usEquitySymbol : currentSignal == 2 ? intlEquitySymbol : defensiveSymbol

// ═══════════════════════════════════════════════════════════════════════════════
// MONTH-END DETECTION
// ═══════════════════════════════════════════════════════════════════════════════

// Detect new month for signal change tracking
isNewMonth = month(time) != month(time[1])

// Track signal changes
signalChanged = ta.change(currentSignal) != 0

// ═══════════════════════════════════════════════════════════════════════════════
// VISUAL DISPLAY - BACKGROUND
// ═══════════════════════════════════════════════════════════════════════════════

// Background colors based on signal
bgColorUS = color.new(color.green, bgTransparency)
bgColorIntl = color.new(color.blue, bgTransparency)
bgColorDef = color.new(color.red, bgTransparency)

bgColor = currentSignal == 1 ? bgColorUS : currentSignal == 2 ? bgColorIntl : bgColorDef
bgcolor(showBackground ? bgColor : na, title="Signal Background")

// ═══════════════════════════════════════════════════════════════════════════════
// VISUAL DISPLAY - TABLE
// ═══════════════════════════════════════════════════════════════════════════════

// Table position mapping
tablePos = tablePosition == "top_right" ? position.top_right :
           tablePosition == "top_left" ? position.top_left :
           tablePosition == "bottom_right" ? position.bottom_right :
           tablePosition == "bottom_left" ? position.bottom_left :
           tablePosition == "top_center" ? position.top_center :
           position.bottom_center

// Create and populate table
var table signalTable = table.new(tablePos, 2, 12, bgcolor=color.new(color.black, 20), border_width=1, border_color=color.gray)

if showTable and barstate.islast
    // Header
    table.cell(signalTable, 0, 0, "DUAL MOMENTUM", text_color=color.white, bgcolor=color.new(#1F4E79, 0), text_size=size.normal)
    table.cell(signalTable, 1, 0, "INDICATOR", text_color=color.white, bgcolor=color.new(#1F4E79, 0), text_size=size.normal)

    // Current Signal Section
    table.cell(signalTable, 0, 1, "─── SIGNAL ───", text_color=color.yellow, bgcolor=color.new(color.black, 50), text_size=size.small)
    table.cell(signalTable, 1, 1, "", bgcolor=color.new(color.black, 50))

    signalColor = currentSignal == 1 ? color.green : currentSignal == 2 ? color.blue : color.red
    table.cell(signalTable, 0, 2, "HOLD:", text_color=color.white, bgcolor=color.new(color.black, 70), text_size=size.normal)
    table.cell(signalTable, 1, 2, signalName, text_color=color.white, bgcolor=signalColor, text_size=size.normal)

    table.cell(signalTable, 0, 3, "Ticker:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 3, signalTicker, text_color=color.white, bgcolor=color.new(color.black, 70), text_size=size.small)

    // Momentum Data Section
    table.cell(signalTable, 0, 4, "─── RETURNS ───", text_color=color.yellow, bgcolor=color.new(color.black, 50), text_size=size.small)
    table.cell(signalTable, 1, 4, "", bgcolor=color.new(color.black, 50))

    // US Returns
    usReturnColor = usReturn > 0 ? color.green : color.red
    table.cell(signalTable, 0, 5, "US " + str.tostring(lookbackMonths) + "mo:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 5, str.tostring(usReturn, "#.##") + "%", text_color=usReturnColor, bgcolor=color.new(color.black, 70), text_size=size.small)

    // International Returns
    intlReturnColor = intlReturn > 0 ? color.green : color.red
    table.cell(signalTable, 0, 6, "INTL " + str.tostring(lookbackMonths) + "mo:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 6, str.tostring(intlReturn, "#.##") + "%", text_color=intlReturnColor, bgcolor=color.new(color.black, 70), text_size=size.small)

    // Relative Winner
    relWinnerColor = usWinsRelative ? color.green : color.blue
    table.cell(signalTable, 0, 7, "Rel Winner:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 7, relativeWinner, text_color=relWinnerColor, bgcolor=color.new(color.black, 70), text_size=size.small)

    // Absolute Momentum Section
    table.cell(signalTable, 0, 8, "─── ABS MOM ───", text_color=color.yellow, bgcolor=color.new(color.black, 50), text_size=size.small)
    table.cell(signalTable, 1, 8, "", bgcolor=color.new(color.black, 50))

    table.cell(signalTable, 0, 9, "Winner Ann:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 9, str.tostring(winnerReturnAnnualized, "#.##") + "%", text_color=winnerReturnAnnualized > tbillRate ? color.green : color.red, bgcolor=color.new(color.black, 70), text_size=size.small)

    table.cell(signalTable, 0, 10, "T-Bill Rate:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 10, str.tostring(tbillRate, "#.##") + "%", text_color=color.white, bgcolor=color.new(color.black, 70), text_size=size.small)

    absMomColor = absoluteMomentumPass ? color.green : color.red
    absMomText = absoluteMomentumPass ? "PASS ✓" : "FAIL ✗"
    table.cell(signalTable, 0, 11, "Abs Mom Test:", text_color=color.silver, bgcolor=color.new(color.black, 70), text_size=size.small)
    table.cell(signalTable, 1, 11, absMomText, text_color=absMomColor, bgcolor=color.new(color.black, 70), text_size=size.small)

// ═══════════════════════════════════════════════════════════════════════════════
// ALERTS
// ═══════════════════════════════════════════════════════════════════════════════

// Alert on signal change
alertcondition(signalChanged and alertOnChange, title="Signal Changed", message="Dual Momentum Signal Changed!")

// Alert on new month
alertcondition(isNewMonth and alertOnMonthEnd, title="Month End Review", message="New Month - Review Dual Momentum Signal")

// Specific signal alerts
alertcondition(currentSignal == 1 and signalChanged, title="Switch to US Equities", message="Dual Momentum: Switch to US EQUITIES (SPY)")
alertcondition(currentSignal == 2 and signalChanged, title="Switch to Intl Equities", message="Dual Momentum: Switch to INTERNATIONAL EQUITIES (EFA)")
alertcondition(currentSignal == 3 and signalChanged, title="Switch to Defensive", message="Dual Momentum: Switch to DEFENSIVE (AGG)")

// Plot signal for reference (hidden from chart)
plot(currentSignal, title="Current Signal", display=display.none)

// ═══════════════════════════════════════════════════════════════════════════════
// MONTHLY SIGNAL MARKERS
// ═══════════════════════════════════════════════════════════════════════════════

// Plot signal change markers on chart
plotshape(signalChanged and currentSignal == 1, title="US Signal", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="US")
plotshape(signalChanged and currentSignal == 2, title="INTL Signal", style=shape.triangleup, location=location.belowbar, color=color.blue, size=size.small, text="INTL")
plotshape(signalChanged and currentSignal == 3, title="DEF Signal", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="DEF")

Overview

Dual Momentum requests monthly closes for a US equity ETF, an international equity ETF and a bond ETF, and compares their returns over a set number of months, 12 by default, with a manually entered Treasury bill rate as the absolute momentum test. It shows the resulting allocation signal in a table and background colour, with alerts on signal change and at month end. It uses monthly data, so signals change slowly.

Details

Published by

nxtaiapp on GitHub

Code credit

TradeLabX - Dual Momentum Indicator, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum, Screeners & dashboards

Markets

Stocks

Timeframes

H4 and above

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.

Settings

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

SettingTypeDefaultVariable
US Equities SymbolsymbolSPYusEquitySymbol
International Equities SymbolsymbolEFAintlEquitySymbol
Defensive Asset SymbolsymbolAGGdefensiveSymbol
Lookback Period (Months)int12lookbackMonths
T-Bill Annual Rate (%)float4.0tbillRate
Show Signal TablebooltrueshowTable
Table Positionstringtop_righttablePosition
Show Background ColorbooltrueshowBackground
Background Transparencyint90bgTransparency
Alert on Signal ChangebooltruealertOnChange
Alert on Month EndbooltruealertOnMonthEnd
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

This overlay indicator screens a pasted list of up to forty symbols and draws a table on the price chart. It classifies bullish or bearish setups from the percent change between the current candle and the candle 250 bars back, then shows RSI with a simple movi

Indicator v5 Oscillators & momentumVolume
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - Ankush Bajaj Momentum Investing Setup
330 stars

This multi-symbol indicator evaluates a combined trading condition across up to 40 user-defined symbols. It processes MACD bullish crossovers, RSI thresholds, Bollinger Band boundaries, and DMI/ADX trend filters using security calls. When buy or sell criteria

Indicator v5 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Multi MACD + BB + RSI [Alorse]
218 stars

TradersPost Trading Checklist is an overlay indicator that evaluates a suite of popular technical conditions for long and short trade setups. It checks session-anchored VWAP, fast and slow EMA alignments and crosses, 200 SMA, RSI overbought or oversold conditi

Indicator v6 Screeners & dashboardsTrend
Updated 3 months ago · None stated GitHub repository of TradersPost Trading Checklist

8zz反指標v2

by hansai-art
121 stars

The 8zz Contrarian Indicator plots reverse sentiment trading signals directly on the price chart based on tracked retail post activity. It generates bullish signals during retail panic and bearish signals during market euphoria. The indicator features adjustab

Indicator v6 Moving averagesOscillators & momentum
Updated 3 months ago · None stated GitHub repository of 8zz反指標v2

Chart Background

by be-thomas
65 stars

This indicator colors the chart background using a full-screen single-cell table based on the 20-period Relative Strength Index (RSI). When the RSI is above 50, the table applies a bullish background color, and when below 50, a bearish color. The background up

Indicator v4 Oscillators & momentumScreeners & dashboards
Updated 5 days ago · GPL-3.0 GitHub repository of Chart Background
53 stars

This indicator analyzes historical candle direction and price range over a configurable lookback window to gauge market trend. It categorizes trend direction using candle count, price range sum, or both. Signals are filtered using a Simple Moving Average to en

Indicator v6 TrendOscillators & momentum
Updated 2 months ago · MPL-2.0 GitHub repository of Candle Counter + MA + RSI + Mode

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers