Strategy · Pine Script v4 · On the chart

Triple EMA + Sloping Trend Long Strategy

by krosenfeld7

This strategy evaluates bullish trend strength by calculating three Exponential Moving Averages (50, 100, and 150 periods) alongside their average slope angles in degrees.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code164
Settings17inputs
LicenceApache-2.0
Last update3 years ago12 May 2023

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

164 lines of Pine Script v4 from Triple_EMA+Sloping_Trend/Triple_EMA+Sloping_Trend_Long_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

Triple_EMA+Sloping_Trend_Long_Strategy.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © krosenfeld7

//@version=4
strategy("Triple EMA + Sloping Trend Long Strategy", overlay = true, pyramiding = 0, 
         margin_long = 100, margin_short = 100, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 20, initial_capital = 2000, 
         process_orders_on_close = true)

// Set the starting point for backtesting
start = input(title = "Backtesting Start", type = input.time,
     defval = timestamp("1 Jan 2015"))
maxTimeOpen = input(title = "Order Expiration", type = input.integer,
     defval = 100, minval = 1)
tpSlStrategy = input(title = "Take Profit Strategy", type = input.string,
     defval = "Percent", options = ["Percent", "ATR"])
trailingStop = input(title = "Trailing Stop", type = input.string,
     defval = "Fixed", options = ["Fixed", "Trail"])

// ATR For Stop Loss
atrLength = input(title = "ATR SL Length", defval = 14,
     minval = 1)
atrMultiplier = input(title = "ATR Multiplier", type = input.float, 
     defval = 1, minval = 0.1)
riskLevel = input(title = "Risk Level", type = input.float, 
     defval = 1, minval = 0.1)

longProfitPercent = input(title = "Take Profit %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100
longLossPercent = input(title = "Stop Loss %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100

// Algorithm / Strategy Goes here
// Set long variables to execute positions below
emaShort    = input(title = "Short EMA Length", type = input.integer, defval = 50,  minval = 1)
emaShortSrc = input(title = "Short EMA Src",    type = input.source,  defval = close)
emaMed      = input(title = "Med EMA Length",   type = input.integer, defval = 100, minval = 1)
emaMedSrc   = input(title = "Med EMA Src",      type = input.source,  defval = close)
emaLong     = input(title = "Long EMA Length",  type = input.integer, defval = 150, minval = 1)
emaLongSrc  = input(title = "Long EMA Src",     type = input.source,  defval = close)
slopeRange  = input(title = "Slope Range",      type = input.integer, defval = 10,  minval = 1)
slopeDegLim = input(title = "Slope Angle Limit",type = input.float,   defval = 30,  minval = 1)

ema50  = ema(close, 50)
ema100 = ema(close, 100)
ema150 = ema(close, 150)

plot(ema50, color=color.blue, linewidth = 2)
plot(ema100, color=color.yellow, linewidth = 2)
plot(ema150, color=color.red, linewidth = 2)

calculate_slope(_range, _src) =>
    _y = _src - nz(_src[_range])
    _angle = atan(_y/_range)
    _angle

calculate_avg_slope(_range, _src) =>
    _total = 0.0
    for i = 1 to _range
        _total += calculate_slope(i, _src)
    
    _total / _range

slopeEMA1 = todegrees(calculate_avg_slope(slopeRange, ema50))
slopeEMA2 = todegrees(calculate_avg_slope(slopeRange, ema100))
slopeEMA3 = todegrees(calculate_avg_slope(slopeRange, ema150))

// Bullish
// 50 MA > 100 MA > 200 MA all with slopes > 30 deg
// closes below 50 EMA, but above 100 EMA, long when candle closes above 50 EMA

closeBelow50  = crossunder(close, ema50)
closeBelow100 = crossunder(close, ema100)
closeBelow150 = crossunder(close, ema150)

correctBullOrder = barssince(closeBelow50) < barssince(closeBelow100)

tempLongPos = ema50 > ema100 and ema100 > ema150 and correctBullOrder and crossover(close, ema50)

emaLongPos = barssince(tempLongPos) < barssince(close < ema100) and barssince(tempLongPos) < barssince(close < ema150)

slopeLongPos = slopeEMA1 > slopeDegLim and slopeEMA2 > slopeDegLim and slopeEMA3 > slopeDegLim

// Bearish
// 50 MA < 100 MA < 200 MA all with slopes < -30 deg
// closes above, but below 100 EMA, short when candle closes below 50 EMA

closeAbove50  = crossover(close, ema50)
closeAbove100 = crossover(close, ema100)
closeAbove150 = crossover(close, ema150)

correctBearOrder = barssince(closeAbove50) < barssince(closeAbove100)

tempShortPos = ema50 < ema100 and ema100 < ema150 and correctBearOrder and crossunder(close, ema50)

emaShortPos = barssince(tempShortPos) < barssince(close > ema100) and barssince(tempShortPos) < barssince(close > ema150)

slopeShortPos =  slopeEMA1 < -slopeDegLim and slopeEMA2 < -slopeDegLim and slopeEMA3 < -slopeDegLim

// Computing Strategy
long  = emaLongPos  and slopeLongPos
short = emaShortPos and slopeShortPos

// End Algorithm

longExitPrice = 0.0
longStopPrice = 0.0

// Calculating exact prices for stop loss and exit prices
longExitPercentPrice = strategy.position_avg_price * (1 + 
     (longProfitPercent * riskLevel))
longStopPercentPrice = strategy.position_avg_price * (1 - 
     longLossPercent)

// Profit & Loss via ATR
atr = atr(atrLength)

atr := valuewhen(strategy.position_size == 0, atr, 0)

longExitAtrPrice = strategy.position_avg_price + (atr * 
     atrMultiplier * riskLevel)
longStopAtrPrice = strategy.position_avg_price - (atr * 
     atrMultiplier)

if tpSlStrategy == "Percent"
    longExitPrice := longExitPercentPrice
    
    if trailingStop == "Fixed"
        longStopPrice := longStopPercentPrice
    else if trailingStop == "Trail"
        stopValue      = close * (1 - longLossPercent)
        longStopPrice := (strategy.position_size > 0) ? 
             max(stopValue, longStopPrice[1]) : 0

else if tpSlStrategy == "ATR"
    if strategy.position_size > 0
        longExitPrice := longExitAtrPrice
        
    if trailingStop == "Fixed"
        longStopPrice := longStopAtrPrice
    else if trailingStop == "Trail"
        stopValue      = close - (atr * atrMultiplier)
        longStopPrice := (strategy.position_size > 0) ? 
             max(stopValue, longStopPrice[1]) : 0

// Plotting profit / loss targets
plot(series = (strategy.position_size > 0) ? longExitPrice : na, 
     color = color.green, style = plot.style_linebr, 
     linewidth = 3, title = "Long Target")
plot(series = (strategy.position_size > 0) ? longStopPrice : na, 
     color = color.red, style = plot.style_linebr, 
     linewidth = 3, title = "Long Stop Loss")

// Submit entry orders
if time >= start
    strategy.entry(id = "Long", long = strategy.long, 
         comment = "Long Open", when = long)

// Submit exit orders
strategy.exit(id = "Long", limit = longExitPrice, stop = longStopPrice, 
     comment = "Long Close", when = strategy.position_size > 0)
strategy.close(id = "Long", comment = "Expired: >" + tostring(maxTimeOpen), 
     when = (barssince(change(strategy.opentrades)) + 1) >= maxTimeOpen)

Overview

Triple EMA + Sloping Trend Long Strategy plots the EMAs on the price chart and triggers long entries when the moving averages are aligned in bullish order, slopes meet a degree threshold, and price crosses back above the short EMA after pulling back. Exits are managed using configurable percentage or ATR-based stop loss and take profit levels, trailing stops, and trade expiration after a set number of bars.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Trend, 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
Backtesting Starttimetimestamp("1 Jan 2015")start
Order Expirationint100maxTimeOpen
Take Profit StrategystringPercenttpSlStrategy
Trailing StopstringFixedtrailingStop
ATR SL Lengthint14atrLength
ATR Multiplierfloat1atrMultiplier
Risk Levelfloat1riskLevel
Take Profit %float10longProfitPercent
Stop Loss %float10longLossPercent
Short EMA Lengthint50emaShort
Short EMA SrcsourcecloseemaShortSrc
Med EMA Lengthint100emaMed
Show all 17 settings
SettingTypeDefaultVariable
Med EMA SrcsourcecloseemaMedSrc
Long EMA Lengthint150emaLong
Long EMA SrcsourcecloseemaLongSrc
Slope Rangeint10slopeRange
Slope Angle Limitfloat30slopeDegLim
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