Strategy · Pine Script v4 · On the chart

Algo Trading Simple 3-EMA Strategy + Trailstop

by doppelgunner

This strategy plots three EMAs (50, 100, 200) on the price chart for crossover signals.

View on GitHub

GitHub stars4on the repository
Pine versionv4older, still runs
Lines of code98
Settings12inputs
LicenceMIT
Last update5 years ago16 Sep 2021

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

98 lines of Pine Script v4 from 0002_Free 3-EMA Crossover Strategy + ATR Trailing Stoploss/Algo Trading Simple 3-EMA Strategy with ATR Trailstop.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

Algo Trading Simple 3-EMA Strategy with ATR Trailstop.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © doppelgunner

//@version=4
initial_capital = 10000
percent_risk = input(2, "% Risk per trade (of equity)", minval=0, type=input.float, group="Risk Management Settings", tooltip="This is important for position sizing") / 100
strategy("Algo Trading: Simple 3-EMA Strategy + Trailstop", overlay=true, initial_capital=initial_capital, commission_type=strategy.commission.percent, commission_value=0.04)
ave_loss_percent = input(2, "% of average loss (backtesting)", minval=0, type=input.float, group="Risk Management Settings", tooltip="This is important for position sizing") / 100

enter_long = input(true, "Enter Long?", type=input.bool, group="Backtest Settings")
enter_short = input(true, "Enter Short?", type=input.bool, group="Backtest Settings")

ema_fast_length = input(50, "EMA  Fast Length", minval=1, group="EMA Settings")
ema_mid_length = input(100, "EMA  Mid Length", minval=1, group="EMA Settings")
ema_slow_length = input(200, "EMA  Slow Length", minval=1, group="EMA Settings")

atr_mul = input(5, "Multiplier", minval=1, group="ATR Settings")
atr_length = input(14, "Length", minval=1, group="ATR Settings")
atr_smoothing = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"], group="ATR Settings")
atr_ma_function(source, length) =>
    if atr_smoothing == "RMA"
        rma(source, length)
    else
        if atr_smoothing == "SMA"
            sma(source, length)
        else
            if atr_smoothing == "EMA"
                ema(source, length)
            else
                wma(source, length)
                
atr = atr_ma_function(tr(true), atr_length)

ema_slow = ema(close, ema_slow_length)
ema_mid = ema(close, ema_mid_length)
ema_fast = ema(close, ema_fast_length)

plot(ema_slow, "EMA Slow", color=color.black, linewidth=3)
plot(ema_mid, "EMA Mid", color=color.red, linewidth=2)
plot(ema_fast, "EMA Fast", color=color.blue, linewidth=1)

buy = crossover(ema_fast, ema_mid) and close > ema_slow
sell = crossunder(ema_fast, ema_mid) and close < ema_slow

risk_money = strategy.equity * percent_risk
stop_risk = abs(close - (close * ave_loss_percent))
diffSR = abs(close - stop_risk)

position_size = risk_money / diffSR

strategy.entry("long", strategy.long, when=buy and enter_long, qty=position_size)
strategy.close("long", when=sell)

strategy.entry("short", strategy.short, when=sell and enter_short, qty=position_size)
strategy.close("short", when=buy)

inLong = strategy.position_size > 0
inShort = strategy.position_size < 0
notInTrade = strategy.position_size == 0

use_trailstop = input(true, "Use trailstop?", type=input.bool, group="Backtest Settings")

computeTrailstopLong() =>
    longTrailstop = close - (atr_mul * atr)
    
computeTrailstopShort() =>
    shortTrailstop = close + (atr_mul * atr)

var float longTrailstop = na
var float shortTrailstop = na

if (buy and enter_long and use_trailstop)
    longTrailstop := computeTrailstopLong()

if (inLong and use_trailstop)
    if (longTrailstop < computeTrailstopLong())
        longTrailstop := computeTrailstopLong()
    
if (sell and enter_short and use_trailstop)
    shortTrailstop := computeTrailstopShort()

if (inShort and use_trailstop)
    if (shortTrailstop > computeTrailstopShort())
        shortTrailstop := computeTrailstopShort()

strategy.exit("long", stop=longTrailstop, when=inLong or (buy and enter_long))
strategy.exit("short", stop=shortTrailstop, when=inShort or (sell and enter_short))

showBGColor = input(false, "Show BG Color?", type=input.bool, group="Color Settings")
bgcolor(notInTrade or (not showBGColor) ? color.white : inLong ? color.green : color.red)

ema_close = ema(close, 2)
close_plot = plot(ema_close, "EMA Close", color=color.new(color.white, 100))
long_trail_plot = plot(inLong ? longTrailstop : na, "Long Trail Stop", color=color.green, style=plot.style_linebr)
short_trail_plot = plot(inShort ? shortTrailstop : na, "Short Trail Stop", color=color.red, style=plot.style_linebr)

fill(close_plot, long_trail_plot, title="Trailstop Long", color=color.green)
fill(close_plot, short_trail_plot, title="Trailstop Short", color=color.red)

Overview

Long entries occur when fast EMA crosses above mid EMA and close exceeds slow EMA; short entries when fast crosses below mid and close is below slow. It uses ATR trailing stop loss for exits and calculates position sizes based on equity risk percentage and average loss percentage.

Details

Published by

doppelgunner on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Moving averages, Trend, Volatility & bands

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
% Risk per trade (of equity)float2percent_risk
% of average loss (backtesting)float2ave_loss_percent
Enter Long?booltrueenter_long
Enter Short?booltrueenter_short
EMA Fast Lengthint50ema_fast_length
EMA Mid Lengthint100ema_mid_length
EMA Slow Lengthint200ema_slow_length
Multiplierint5atr_mul
Lengthint14atr_length
SmoothingstringRMAatr_smoothing
Use trailstop?booltrueuse_trailstop
Show BG Color?boolfalseshowBGColor
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 mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce
106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
104 stars

This overlay strategy combines a Chandelier Exit with a zero-lag least squares moving average. Although the header mentions Heikin Ashi candles, the calculations use ordinary closes. An ATR trailing stop sets long and short levels, and direction flips when pri

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of Chandelier Exit & ZLSMA 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