Strategy · Pine Script v5 · On the chart

Dual Momentum Strategy

by nxtaiapp· code credited to TradeLabX - Dual Momentum Strategy

A monthly rotation strategy based on the global equity momentum approach.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code221
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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

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

dual_momentum_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 Strategy
// Based on Gary Antonacci's Global Equity Momentum (GEM) methodology

//@version=5
strategy("Dual Momentum Strategy [TradeLabX]", 
     overlay=true, 
     default_qty_type=strategy.percent_of_equity, 
     default_qty_value=100,
     initial_capital=10000,
     commission_type=strategy.commission.percent,
     commission_value=0.1,
     slippage=1,
     process_orders_on_close=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

// ═══════════════════════════════════════════════════════════════════════════════
// STRATEGY EXECUTION
// ═══════════════════════════════════════════════════════════════════════════════

// Execute strategy based on signals (works on any chart)
if currentSignal == 1
    strategy.entry("Long US", strategy.long)
if currentSignal == 2
    strategy.entry("Long INTL", strategy.long)
if currentSignal == 3
    strategy.entry("Long DEF", strategy.long)

// ═══════════════════════════════════════════════════════════════════════════════
// 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, "STRATEGY", 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 Strategy requests monthly closes for a US equity ETF, an international equity ETF and a bond ETF, compares their returns over a lookback in months and checks the stronger equity against a manually entered Treasury bill rate. The strategy then holds the chosen asset using the full equity by default, with commission and slippage set in the code. It has no stop loss, a signal table and alerts on changes and at month end.

Details

Published by

nxtaiapp on GitHub

Code credit

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

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum

Markets

Stocks

Timeframes

H4 and above

Risk Notes

  • The strategy enters trades without a stop loss

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

330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

MACD Strategy

by TradersPost
218 stars

This overlay strategy is built around MACD inputs for a fast average, a slow average, and a signal line. Comments say the script keeps MACD values available and can draw a histogram and zero line in a separate pane, with an optional overlay on price. Settings

Strategy v6 Oscillators & momentumMoving averages
Updated 3 months ago · None stated GitHub repository of MACD Strategy

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers