Strategy · Pine Script v5 · On the chart

MA Trend Percent Target Strategy

by g-moe· code credited to goodgains

MA Trend Percent Target Strategy is a trend-following overlay strategy that executes trades based on price crossovers with a moving average.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code93
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago27 May 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

93 lines of Pine Script v5 from Tradingview/ma-trend-percent-target-strategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

ma-trend-percent-target-strategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodgains


//@version=5
strategy("MA Trend Percent Target Strategy", overlay=true, margin_long=100, margin_short=100)

// @keywords: moving-average-trend, ma-crossover-entry, ma-crossunder-entry, long-short-toggle, percent-take-profit, percent-stop-loss, optional-profit-target, optional-stop-loss, entry-price-plot, target-price-plot, stop-price-plot, profit-zone-shading, loss-zone-shading, trend-following, hull-moving-average, volume-weighted-ma, configurable-ma-type, ma-length-input, strategy-start-date, opposite-signal-exit

// input settings
ma_type = input.string("SMA", title = 'Moving Average Type',
 options = ['SMA', 'EMA', 'WMA', 'HMA', 'VWMA'], group = 'Strategy Settings')
ma_length = input.int(20, title = 'Moving Average Length', group = 'Strategy Settings')

strategy_start = input.time(timestamp("01 January 2020 00:00:00 UTC-5"), "Strategy Start Date", group = "Strategy Settings")
long_trades = input.bool(true, title = "Long Trades    |    ", group = "Strategy Settings", inline = '1')
short_trades = input.bool(true, title = "Short Trades", group = "Strategy Settings", inline = '1')

alt_target = input.bool(false, title = '% Target',  group = "Strategy Settings", inline = '2')
_tp_pct = input.float(1.05, title = ' ',  group = "Strategy Settings", inline = '2')

alt_stop = input.bool(false, title = '% Stop  ',  group = "Strategy Settings", inline = '3')
_sl_pct = input.float(1.05, title = ' ',  group = "Strategy Settings", inline = '3')

past_startdate = time > strategy_start

// calc ma
float ma_value = switch ma_type
    "EMA" => ta.ema(close, ma_length)
    "SMA" => ta.sma(close, ma_length)
    "WMA" => ta.wma(close, ma_length)
    "VWMA" => ta.vwma(close, ma_length)
    "HMA" => ta.hma(close, ma_length)
    => ta.sma(close, ma_length)

plot(ma_value, title = 'MA', color = close > ma_value ? color.rgb(0, 206, 185) : color.rgb(255, 0, 0),
 linewidth = 2)


// calc normal entry/exit
long_cross = ta.crossover(close, ma_value)
short_cross = ta.crossunder(close, ma_value)

long_entry = long_trades and long_cross
short_entry = short_trades and short_cross

long_exit = not short_trades and short_cross
short_exit = not long_trades and long_cross


// calc target/stop S
var float tgt_price = na
var float sl_price = na

if alt_target
    tgt_price := strategy.position_size > 0 ? (strategy.position_avg_price + (strategy.position_avg_price * (_tp_pct/100))) 
     : strategy.position_size < 0 ? (strategy.position_avg_price - (strategy.position_avg_price * (_tp_pct/100))) 
     : na

if alt_stop
    sl_price := strategy.position_size > 0 ? (strategy.position_avg_price - (strategy.position_avg_price * (_sl_pct/100))) 
     : strategy.position_size < 0 ? (strategy.position_avg_price + (strategy.position_avg_price * (_sl_pct/100))) 
     : na


p_entry = plot(strategy.position_avg_price, title = 'Entry', color = color.blue, style = plot.style_circles)
p_tgt = plot(tgt_price, title = 'Target', color = color.lime, style = plot.style_circles)
p_sl = plot(sl_price, title = 'Stop', color = color.fuchsia, style = plot.style_circles)


fill(p_entry, p_tgt, title = 'Profit Background', color = alt_target ? color.new(color.teal, 80) : na)
fill(p_entry, p_sl, title = 'Loss Background', color = alt_stop ? color.new(color.red, 80) : na)

if past_startdate
    // entry orders
    if (long_entry)
        strategy.entry("LE", strategy.long)

    if (short_entry)
        strategy.entry("SS_E", strategy.short)

    // target/stop orders
    if strategy.position_size > 0
        strategy.exit("TP/SL", from_entry = "LE", limit = tgt_price, stop = sl_price, comment_profit = "TP", comment_loss = "SL")
    if strategy.position_size < 0
        strategy.exit("TP/SL", from_entry = "SS_E", limit = tgt_price, stop = sl_price, comment_profit = "TP", comment_loss = "SL")

    // exit orders
    if (long_exit)
        strategy.close("LE", comment = "LX")

    if (short_exit)
        strategy.close("SS_E", comment = "SS_X")

Overview

MA Trend Percent Target Strategy supports multiple moving average types, including SMA, EMA, WMA, VWMA, and HMA. Trades enter when price crosses above or below the selected average. Exits occur on opposite crossover signals or through optional percentage-based take-profit and stop-loss levels. The strategy plots the moving average line, average entry price, target levels, and stop loss points directly on the price chart.

Details

Published by

g-moe on GitHub

Code credit

goodgains, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

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
Moving Average TypestringSMAma_type
Moving Average Lengthint20ma_length
Strategy Start Datetimetimestamp("01 January 2020 00:00:00 UTC-5")strategy_start
Long Trades | booltruelong_trades
Short Tradesbooltrueshort_trades
% Targetboolfalsealt_target
float1.05_tp_pct
% Stop  boolfalsealt_stop
float1.05_sl_pct
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
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
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

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