Strategy · Pine Script v4 · On the chart

200 EMA + Stochastic + Triple Supertrend Long Strategy

by krosenfeld7

This long-only strategy combines a 200-period Exponential Moving Average, Stochastic RSI, and three distinct Supertrend indicators with varying ATR periods and multipliers.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code170
Settings24inputs
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

170 lines of Pine Script v4 from 200_EMA+Triple_Supertrend+Stochastic/200_EMA+Triple_Supertrend+Stochastic_Long_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

200_EMA+Triple_Supertrend+Stochastic_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

// This strategy is best on the 4 hour timeframe
//@version=4
strategy("200 EMA + Stochastic + Triple Supertrend Long Strategy (4H)", 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"))
// Expiration time on orders
maxTimeOpen = input(title="Order Expiration", type=input.integer, defval=100, minval=1)
stopLossMethod = input(title="Stop Loss Method?", type=input.string, options=["Trend Lines", "Percent %", "ATR"], defval="Trend Lines")
risk_level = input(title="Risk Level", type=input.float, defval=1.5, minval=0.1)

// Algorithm / Strategy Goes here
// Set long / short variables to execute positions below
// 200 period EMA Section
len1 = input(200, minval=1, title="EMA Length")
src1 = input(close, title="EMA Source")
offset = input(title="EMA Offset", type=input.integer, defval=0, minval=-500, maxval=500)
ema200 = ema(src1, len1)
plot(ema200, title="EMA", color=color.white, offset=offset, linewidth=3)

emaLong = close > ema200
emaShort = close < ema200

// Stochastic RSI Section
smoothK = input(3, "Stochastic K", minval=1)
smoothD = input(3, "Stochastic D", minval=1)
lengthRSI = input(14, "RSI Length", minval=1)
lengthStoch = input(14, "Stochastic Length", minval=1)
src2 = input(close, title="RSI Source")
rsi1 = rsi(src2, lengthRSI)
k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(k, smoothD)

stoLong = k < 20 and d < 20 and crossover(k, d)
stoShort = k > 80 and d > 80 and crossunder(k, d)

// Supertrend 1: Settings: ATR Period = 12, Multiplier = 3
Periods1 = input(title="Long ATR Period", type=input.integer, defval=12)
src3 = input(hl2, title="ATR Source")
Multiplier1 = input(title="Long ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change Long ATR Calculation Method ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods1)
atr1= changeATR ? atr(Periods1) : atr2
up=src3-(Multiplier1*atr1)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src3+(Multiplier1*atr1)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend1 = 1
trend1 := nz(trend1[1], trend1)
trend1 := trend1 == -1 and close > dn1 ? 1 : trend1 == 1 and close < up1 ? -1 : trend1

// Supertrend 2: Settings: ATR Period = 11, Multiplier = 2
Periods2 = input(title="Intermediate ATR Period", type=input.integer, defval=11)
Multiplier2 = input(title="Intermediate ATR Multiplier", type=input.float, step=0.1, defval=2.0)
atr4 = sma(tr, Periods2)
atr3= changeATR ? atr(Periods2) : atr4
up2=src3-(Multiplier2*atr3)
up3 = nz(up2[1],up2)
up2 := close[1] > up3 ? max(up2,up3) : up2
dn2=src3+(Multiplier2*atr3)
dn3 = nz(dn2[1], dn2)
dn2 := close[1] < dn3 ? min(dn2, dn3) : dn2
trend2 = 1
trend2 := nz(trend2[1], trend2)
trend2 := trend2 == -1 and close > dn3 ? 1 : trend2 == 1 and close < up3 ? -1 : trend2

// Supertrend 3: Settings: ATR Period = 10, Multiplier = 1
Periods3 = input(title="Short ATR Period", type=input.integer, defval=10)
Multiplier3 = input(title="Short ATR Multiplier", type=input.float, step=0.1, defval=1.0)
atr6 = sma(tr, Periods3)
atr5= changeATR ? atr(Periods3) : atr6
up4=src3-(Multiplier3*atr5)
up5 = nz(up4[1],up4)
up4 := close[1] > up5 ? max(up4,up5) : up4
dn4=src3+(Multiplier3*atr5)
dn5 = nz(dn4[1], dn4)
dn4 := close[1] < dn5 ? min(dn4, dn5) : dn4
trend3 = 1
trend3 := nz(trend3[1], trend3)
trend3 := trend3 == -1 and close > dn5 ? 1 : trend3 == 1 and close < up5 ? -1 : trend3

// Bullish (Long)
// Price > 200 EMA
// Stochastic < 20 (oversold) with K crossup
// Case 1: At least 2 supertrend lines below price (close), supertrend lines are upPlot, upPlot2, upPlot3
// Case 2: If only 1 supertrend line below price:
//         Wait until 2 supertrend lines below and enter, but only if Stochastic (k or d) < 50
// Stop loss at 2 supertrend lines below price

longPlot1 = trend1 == 1 ? up : na
longPlot2 = trend2 == 1 ? up2 : na
longPlot3 = trend3 == 1 ? up4 : na
longValid1 = not na(longPlot1) and close > longPlot1
longValid2 = not na(longPlot2) and close > longPlot2
longValid3 = not na(longPlot3) and close > longPlot3
longValidNum = 0
longValidNum += longValid1 ? 1 : 0
longValidNum += longValid2 ? 1 : 0
longValidNum += longValid3 ? 1 : 0

// Case 1: 1 supertrend line is below price
conditionallyValidLong = longValidNum == 1 and stoLong and emaLong

// Case 2: 2 supertrend lines are below price
superLong = (longValid1 and longValid2) or (longValid1 and longValid3) or (longValid2 and longValid3)
tempLong = emaLong and stoLong and superLong

// Case 1: EMA is valid, stochastic is not, but still less than 50 and there are now 2 supertrend lines
if emaLong and (not stoLong and (d < 50 or k < 50)) and (superLong and barssince(conditionallyValidLong) < 10)
    tempLong := true

long = tempLong ? 1 : 0

// Average True Range
length = input(title="ATR Length", defval=14, minval=1)
atrMultiplier = input(title="ATR Multiplier", type=input.float, defval=1, minval=0.1)
atr = atr(length)

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

var float longStopPrice = na
var float longExitPrice = na

// Compute stop loss and targets only if trade isn't open yet
if tempLong and strategy.opentrades == 0 and stopLossMethod == "Trend Lines"
    if longValidNum == 2
        if na(longPlot1)
            longStopPrice := min(longPlot2, longPlot3)
        else if na(longPlot2)
            longStopPrice := min(longPlot1, longPlot3)
        else
            longStopPrice := min(longPlot1, longPlot2)
    else
        longMin = min(longPlot1, min(longPlot2, longPlot3))
        longMax = max(longPlot1, max(longPlot2, longPlot3))
        longStopPrice := 2 * (longPlot1 + longPlot2 + longPlot3 - longMin - longMax)
        
    longExitPrice := ((close - longStopPrice) * risk_level) + close

else if stopLossMethod == "Percent %"
    // Calculating exact prices for stop loss and exit prices
    longExitPrice := strategy.position_avg_price * (1 + longProfitPercent)
    longStopPrice := strategy.position_avg_price * (1 - longLossPercent)

else if stopLossMethod == "ATR"
    // Profit & Loss via ATR
    longExitPrice := strategy.position_avg_price + atr * atrMultiplier
    longStopPrice := strategy.position_avg_price - atr * atrMultiplier

// Plotting profit / loss targets
plot(series = (strategy.position_size > 0) ? longExitPrice : na, color = color.green, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Long Target")
plot(series = (strategy.position_size > 0) ? longStopPrice : na, color = color.red, style = plot.style_linebr, transp = 0, 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

200 EMA + Stochastic + Triple Supertrend Long Strategy enters long trades when price trades above the 200 EMA, Stochastic RSI crosses up from oversold levels, and the Supertrends confirm the uptrend. The script plots the 200 EMA and Supertrend levels directly on the main price chart. Users can select stop-loss methods using Trend Lines, percentage bounds, or ATR multipliers, as well as set order expiration durations.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages, Volatility & bands

Markets

Any symbol

Timeframes

H4 and above

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
Stop Loss Method?stringTrend LinesstopLossMethod
Risk Levelfloat1.5risk_level
EMA Lengthint200len1
EMA Sourcesourceclosesrc1
EMA Offsetint0offset
Stochastic Kint3smoothK
Stochastic Dint3smoothD
RSI Lengthint14lengthRSI
Stochastic Lengthint14lengthStoch
RSI Sourcesourceclosesrc2
Show all 24 settings
SettingTypeDefaultVariable
Long ATR Periodint12Periods1
ATR Sourcesourcehl2src3
Long ATR Multiplierfloat3.0Multiplier1
Change Long ATR Calculation Method ?booltruechangeATR
Intermediate ATR Periodint11Periods2
Intermediate ATR Multiplierfloat2.0Multiplier2
Short ATR Periodint10Periods3
Short ATR Multiplierfloat1.0Multiplier3
ATR Lengthint14length
ATR Multiplierfloat1atrMultiplier
Long Take Profit (%)float10longProfitPercent
Long Stop Loss (%)float10longLossPercent
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

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

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL

CombinedBinHAndClucV6

by viktors1982
36 stars

CombinedBinHAndClucV6 is a trading strategy based on the popular BinHV45 and ClucMay72018 algorithms. It calculates dual Bollinger Bands, Exponential Moving Averages, Relative Strength Index, Average True Range, and volume metrics across primary and one-hour h

Strategy v4 Volatility & bandsOscillators & momentum Repaints
Updated 2 years ago · None stated GitHub repository of CombinedBinHAndClucV6

BB Swing

by benso87
24 stars

This strategy calculates Bollinger Bands, a configurable moving average slope, Stochastic RSI, ATR, and ADX directly on the price chart. It evaluates trend bias and momentum conditions to generate long and short swing entries using percent-of-equity sizing. Th

Strategy v5 Volatility & bandsOscillators & momentum
Updated 4 years ago · MPL-2.0 GitHub repository of BB Swing

This strategy trades long and short on the price chart using a multi-timeframe TradingLatino setup. It requires EMA 10 to cross or sit above or below EMA 55 on the one-hour, four-hour, and daily charts, together with a positive ADX slope, a directional monitor

Strategy v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ruckard ABCBitcoin TradingLatino A010

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