Strategy · Pine Script v5 · On the chart

EMA Crossover ATR Strategy v2

by g-moe· code credited to goodgains

This strategy executes long positions based on a fast and slow exponential moving average crossover.

View on GitHub

Repaints

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code156
Settings17inputs
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

156 lines of Pine Script v5 from Tradingview/ema-crossover-atr-strategy-v2-strategy.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

ema-crossover-atr-strategy-v2-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("EMA Crossover ATR Strategy v2 Strategy", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 2.0, initial_capital = 100000, calc_on_order_fills = false, calc_on_every_tick = true)

// @keywords: ema-crossover, atr-stop-loss, profit-target, manage-ema, long-entry, short-exit, stop-level, position-management, risk-reward, entry-line, target-line, stop-line, crossover-signal, crossunder-exit, percent-loss-limit, partial-close, strategy-orders, cloud-fill, bar-highlight, alternate-alerts

use_alt_alerts = input.bool(true, 'Use Alternate Alerts')

////////////////
//ENTRY CRITERIA
////////////////
ma1_length = input.int(3, "Short EMA", group = 'Entry')
ma2_length = input.int(27, "Long EMA", group = 'Entry')

ma_1 = ta.ema(close, ma1_length)
ma_2 = ta.ema(close, ma2_length)

ma1 = plot(ma_1, "Short EMA", color = color.new(color.orange,40))
ma2 = plot(ma_2, "Long EMA", color = color.new(color.yellow,40))
fill(ma1, ma2 , color = ma_1 >= ma_2 ? color.new(color.teal,80) : color.new(color.red,80))

long_entry_cond = ta.crossover(ma_1, ma_2)
long_exit_cond = ta.crossunder(ma_1,ma_2)

/////////////////////
//POSITION MANAGEMENT
/////////////////////
use_atr_stop = input.bool(true, title = ' ', group = 'Position Management', inline = '1')
atr_stop_amount = input.float(1.50, minval = 0.1, title = "ATR Stop Amount", group = 'Position Management' ,inline = '1')
atr_value = ta.atr(3) * atr_stop_amount

use_max_pct_loss = input.bool(true, title = ' ', group = 'Position Management', inline = '2')
max_pct_loss_amount = input.float(20.00, minval = 0.1, title = "Max % Loss Amount", group = 'Position Management', inline = '2')

profit_target_amount = input.float(20.00, minval = 0.1, title = "Profit Tgt % Amount", group = 'Position Management', inline = '3')

manage_length = input.int(16, "Manage EMA", group = 'Position Management', inline = '4')
manage_ema = ta.ema(close, manage_length)
manageema = plot(manage_ema, title = "Manage EMA", color = color.new(color.white,90))

/////////////////////
//STRATEGY LOGIC
/////////////////////
entry_price = strategy.position_avg_price

var atr_stop_level = 0.00
var pct_stop_level = 0.00
var stop_level = 0.00
var tgt_1_level = 0.00

//New Long
if not na(entry_price) and na(entry_price[1])
    
    tgt_1_level := open + (open * (profit_target_amount/100))
    atr_stop_level := low[1] - atr_value
    pct_stop_level := (entry_price - (entry_price * (max_pct_loss_amount / 100)))
    
    if use_atr_stop and use_max_pct_loss
        stop_level := math.max(atr_stop_level, pct_stop_level)
    else if not use_atr_stop and use_max_pct_loss
        stop_level := pct_stop_level
    else if use_atr_stop and not use_max_pct_loss
        stop_level := atr_stop_level
    else
        stop_level := na
    
//Position Management
var first_target_hit = false 
var primary_move_stop = false //when cloud switches colors move stop to low of candle
var secondary_move_stop = false //when close crosses below manage ema move stop to low of candle
var stopped_out = false
    
if not na(entry_price)

    first_target_hit := high >= tgt_1_level and first_target_hit[1] == false ? true : first_target_hit[1]
    
    primary_move_stop := long_exit_cond
    secondary_move_stop := ta.crossunder(close, manage_ema)

    if long_entry_cond[1] and first_target_hit and not first_target_hit[1]
        stop_level := entry_price
        
    else if first_target_hit and not first_target_hit[1]
        stop_level := math.max(entry_price, stop_level[1])
        
    if primary_move_stop[1] or secondary_move_stop[1]
        stop_level := low[1]
        
    stopped_out := low <= stop_level and not long_entry_cond[1] ? true : false
    
else if na(entry_price)
    stop_level := na
    primary_move_stop := false
    secondary_move_stop := false
    
    first_target_hit := false  
    tgt_1_level := na
    stopped_out := stopped_out[1]
    
else
    stop_level := stop_level[1]
    primary_move_stop := primary_move_stop[1]
    secondary_move_stop := secondary_move_stop[1]
    
    first_target_hit := first_target_hit[1]  
    tgt_1_level := tgt_1_level[1]
    stopped_out := stopped_out[1]

//SEND ORDERS
strategy.entry("LE", direction = strategy.long, when = long_entry_cond, alert_message = 'Long Entry')

if strategy.position_size > 0 
    strategy.exit("Stop", "LE", qty = strategy.position_size, stop = stop_level, alert_message = 'Stop')
    strategy.close("LE", when = first_target_hit and not first_target_hit[1], qty_percent = profit_target_amount, comment = "Tgt", alert_message = 'Tgt Hit') //secondary move stop sell 20% and then move stop
    strategy.close("LE", when = secondary_move_stop and not long_entry_cond[1], qty_percent = profit_target_amount, comment = "LM", alert_message = 'Long Management') //secondary move stop sell 20% and then move stop

    strategy.close_all(when = stopped_out, comment = 'Stop', alert_message = 'Stop')
/////////////////////
//VISUAL
/////////////////////
plot(entry_price, title = 'Entry', color = entry_price > 0 ? color.gray : color.new(color.white,100), style = plot.style_stepline)
plot(entry_price > 0 and first_target_hit[1] == false ? tgt_1_level : na, title = 'TGT 1', color = first_target_hit[1] == false and entry_price > 0 ? color.lime : color.new(color.white,100), style = plot.style_stepline)
plot(stop_level, title = 'Stop Loss', color = entry_price > 0 ? color.fuchsia : color.new(color.white,100), style = plot.style_stepline)

color_candles = input.bool(true, title = 'Color Candles', group = 'Additional Visual Settings')
color_bg = input.bool(true, title = 'Color BG', group = 'Additional Visual Settings')
default_color = input.color(color.new(color.gray,0), title = 'Default Color', group = 'Additional Visual Settings')
long_entry_color = input.color(color.new(#50ff00,0), title = 'Long Entry Color', group = 'Additional Visual Settings')
long_exit_color = input.color(color.new(#ff0000,0), title = 'Long Exit Color', group = 'Additional Visual Settings')
tgt_hit_color = input.color(color.new(#00e3ff,0), title = 'Tgt Hit Color', group = 'Additional Visual Settings')
manage_ema_color = input.color(color.new(#ffee58,0), title = 'Manage EMA Cross Color', group = 'Additional Visual Settings')
stopped_out_color = input.color(color.new(color.fuchsia,0), title = 'Stop Color', group = 'Additional Visual Settings')

candle_color = na(entry_price) and not na(entry_price[1]) ? stopped_out_color : long_entry_cond ? long_entry_color : primary_move_stop ? long_exit_color :  first_target_hit and not first_target_hit[1] ? tgt_hit_color : secondary_move_stop ? manage_ema_color : default_color
barcolor(color_candles ? candle_color : na)
bgcolor(color_bg and strategy.position_size > 0 ? color.new(long_entry_color,95) : na)

if use_alt_alerts

    if stopped_out and not stopped_out[1]
        alert("Stopped Out", alert.freq_once_per_bar)

    if long_entry_cond
        alert("Long Entry", alert.freq_once_per_bar)

    if primary_move_stop and barstate.isconfirmed
        alert("Long Exit", alert.freq_once_per_bar)
        
    if first_target_hit and not first_target_hit[1]
        alert("Tgt Hit", alert.freq_once_per_bar)

    if secondary_move_stop and barstate.isconfirmed
        alert("Manage EMA Cross", alert.freq_once_per_bar)

Overview

EMA Crossover ATR Strategy v2 manages open positions using an ATR-based stop loss, an optional maximum percentage loss floor, a percentage-based profit target, and a dedicated management EMA to trail or adjust stops. Signals and EMA clouds are plotted directly on the price chart with customizable bar coloring. Note that calc_on_every_tick is enabled, which recalculates orders on intra-bar ticks.

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

  • Signals can change on the live bar or after it closes (repainting)

Settings

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

SettingTypeDefaultVariable
Use Alternate Alertsbooltrueuse_alt_alerts
Short EMAint3ma1_length
Long EMAint27ma2_length
booltrueuse_atr_stop
ATR Stop Amountfloat1.50atr_stop_amount
booltrueuse_max_pct_loss
Max % Loss Amountfloat20.00max_pct_loss_amount
Profit Tgt % Amountfloat20.00profit_target_amount
Manage EMAint16manage_length
Color Candlesbooltruecolor_candles
Color BGbooltruecolor_bg
Default Colorcolorcolor.new(color.gray,0)default_color
Show all 17 settings
SettingTypeDefaultVariable
Long Entry Colorcolorcolor.new(#50ff00,0)long_entry_color
Long Exit Colorcolorcolor.new(#ff0000,0)long_exit_color
Tgt Hit Colorcolorcolor.new(#00e3ff,0)tgt_hit_color
Manage EMA Cross Colorcolorcolor.new(#ffee58,0)manage_ema_color
Stop Colorcolorcolor.new(color.fuchsia,0)stopped_out_color
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