Strategy · Pine Script v6 · On the chart

Strategy Template

by iamrichardD

This strategy template implements an EMA trend filter paired with MACD momentum confirmations.

View on GitHub

GitHub stars57on the repository
Pine versionv6current
Lines of code145
Settings10inputs
LicenceApache-2.0
Last update1 year ago19 Aug 2025

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

145 lines of Pine Script v6 from templates/strategy-template.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

strategy-template.pine
// Strategy Template v6 - Institutional Grade
// License: [License Type]
// Contributors: [Team Members]
//@version=6

strategy("[Strategy Name] v[Version]", "[SHORT_NAME]", 
         overlay=true, default_qty_type=strategy.percent_of_equity, 
         default_qty_value=5, commission_type=strategy.commission.percent, 
         commission_value=0.075, slippage=2, calc_on_every_tick=false)

//=====================================================================================================================
// 📊 STRATEGY CONFIGURATION - Input Parameters & Settings
//=====================================================================================================================

// === TRADING PARAMETERS ===
// Group input parameters by functionality with descriptive tooltips
longEntry = input.bool(true, "Enable Long Entries", group="Trading Direction")
shortEntry = input.bool(true, "Enable Short Entries", group="Trading Direction")

// === TECHNICAL INDICATORS ===
fastEMA = input.int(21, "Fast EMA Length", minval=5, maxval=50, group="Technical Indicators")
slowEMA = input.int(55, "Slow EMA Length", minval=20, maxval=100, group="Technical Indicators")
macdFast = input.int(12, "MACD Fast Length", minval=5, maxval=50, group="MACD Settings")
macdSlow = input.int(26, "MACD Slow Length", minval=20, maxval=100, group="MACD Settings")
macdSignal = input.int(9, "MACD Signal Length", minval=5, maxval=20, group="MACD Settings")

// === RISK MANAGEMENT ===
riskPercent = input.float(2.0, "Risk Per Trade (%)", minval=0.5, maxval=5.0, step=0.1, group="Risk Management")
atrMultiplier = input.float(2.0, "ATR Stop Multiplier", minval=1.0, maxval=5.0, step=0.1, group="Risk Management")
atrLength = input.int(14, "ATR Length", minval=5, maxval=50, group="Risk Management")

//=====================================================================================================================
// 🔧 TECHNICAL INDICATORS & CALCULATIONS - All Technical Analysis
//=====================================================================================================================

// Pre-calculate all ta.* and math.* functions outside conditionals
emaFast = ta.ema(close, fastEMA)
emaSlow = ta.ema(close, slowEMA)
[macdLine, signalLine, histogram] = ta.macd(close, macdFast, macdSlow, macdSignal)
atr = ta.atr(atrLength)

// Trend determination
trendUp = emaFast > emaSlow
trendDown = emaFast < emaSlow

//=====================================================================================================================
// 📈 SIGNAL LOGIC - Entry/Exit Signal Generation
//=====================================================================================================================

// Long entry conditions
longSignal = longEntry and trendUp and ta.crossover(macdLine, signalLine) and histogram > 0

// Short entry conditions  
shortSignal = shortEntry and trendDown and ta.crossunder(macdLine, signalLine) and histogram < 0

// Exit conditions
longExit = ta.crossunder(macdLine, signalLine) or not trendUp
shortExit = ta.crossover(macdLine, signalLine) or not trendDown

//=====================================================================================================================
// 🛡️ RISK MANAGEMENT - Position Sizing & Risk Controls
//=====================================================================================================================

// ATR-based position sizing
calculatePositionSize(entryPrice, stopLoss, riskPct) =>
    if na(entryPrice) or na(stopLoss) or riskPct <= 0
        0.0
    else
        equity = strategy.equity
        riskAmount = equity * (riskPct / 100)
        stopDistance = math.abs(entryPrice - stopLoss)
        positionSize = riskAmount / stopDistance
        math.max(positionSize, 1.0)

// Dynamic stop levels
longStopLoss = close - (atr * atrMultiplier)
shortStopLoss = close + (atr * atrMultiplier)

//=====================================================================================================================
// ⚡ STRATEGY EXECUTION - Trade Management Logic
//=====================================================================================================================

// Entry execution with validation
if longSignal and strategy.position_size == 0
    posSize = calculatePositionSize(close, longStopLoss, riskPercent)
    strategy.entry("Long", strategy.long, qty=posSize)
    strategy.exit("Long Exit", "Long", stop=longStopLoss)

if shortSignal and strategy.position_size == 0
    posSize = calculatePositionSize(close, shortStopLoss, riskPercent)
    strategy.entry("Short", strategy.short, qty=posSize)
    strategy.exit("Short Exit", "Short", stop=shortStopLoss)

// Exit execution
if longExit and strategy.position_size > 0
    strategy.close("Long", comment="Signal Exit")

if shortExit and strategy.position_size < 0
    strategy.close("Short", comment="Signal Exit")

//=====================================================================================================================
// 🧪 TESTING FRAMEWORK - Dual Test Suite Implementation
//=====================================================================================================================

// Basic validation tests (implement comprehensive test suite)
var int testsPassed = 0
var int testsTotal = 0

// Test 1: Configuration Validation
testConfigValid = fastEMA < slowEMA and riskPercent > 0 and riskPercent <= 5.0
if barstate.islast
    testsTotal += 1
    if testConfigValid
        testsPassed += 1

// Test 2: Signal Validity
testSignalValid = not (longSignal and shortSignal)
if barstate.islast
    testsTotal += 1
    if testSignalValid
        testsPassed += 1

// Add more tests as needed...

//=====================================================================================================================
// 📊 VISUALIZATION & MONITORING - Charts, Alerts & Analytics
//=====================================================================================================================

// Plot key levels and signals
plot(emaFast, "Fast EMA", color=color.blue, linewidth=1)
plot(emaSlow, "Slow EMA", color=color.red, linewidth=1)

// Signal visualization
plotshape(longSignal, "Long Signal", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(shortSignal, "Short Signal", shape.triangledown, location.abovebar, color.red, size=size.small)

// Performance monitoring
if barstate.islast
    testPassRate = testsTotal > 0 ? (testsPassed / testsTotal) * 100 : 0
    label.new(bar_index, high, "Test Pass Rate: " + str.tostring(testPassRate, "#.##") + "%", 
              style=label.style_label_down, color=testPassRate >= 90 ? color.green : color.red)

// Alerts
alertcondition(longSignal, "Long Entry Signal", "Long entry signal generated")
alertcondition(shortSignal, "Short Entry Signal", "Short entry signal generated")

Overview

Long positions trigger when the fast EMA is above the slow EMA alongside a bullish MACD crossover and positive histogram, while short positions require the reverse. Trades exit on MACD signal reversals or trend invalidation, with risk controls utilizing ATR-based stop levels. User settings configure EMA lengths, MACD parameters, and ATR stop multipliers. The strategy plots directly on the main price chart.

Details

Published by

iamrichardD on GitHub

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages

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.

Settings

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

SettingTypeDefaultVariable
Enable Long EntriesbooltruelongEntry
Enable Short EntriesbooltrueshortEntry
Fast EMA Lengthint21fastEMA
Slow EMA Lengthint55slowEMA
MACD Fast Lengthint12macdFast
MACD Slow Lengthint26macdSlow
MACD Signal Lengthint9macdSignal
Risk Per Trade (%)float2.0riskPercent
ATR Stop Multiplierfloat2.0atrMultiplier
ATR Lengthint14atrLength
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

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average
218 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

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

SMA RSI Strategy

by PythonForForex
64 stars

This strategy evaluates simple moving averages and the Relative Strength Index to generate trading signals. It calculates a 10-period SMA, a 30-period SMA, and a 14-period RSI. Long positions are entered when the fast SMA crosses above the slow SMA while RSI i

Strategy v5 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of SMA RSI 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