Strategy · Pine Script v4 · On the chart

50 EMA + 200 EMA Short Strategy (Not Good)

by krosenfeld7

This strategy tests a short-only trend-following system based on 50-period and 200-period exponential moving averages.

View on GitHub

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

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

50_EMA+200_EMA_Short_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("50 EMA + 200 EMA Short Strategy (Not Good)", 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)
useAtr = input(title="Use ATR?", type=input.bool, defval=false)

// Algorithm / Strategy Goes here
// Set long / short variables to execute positions below

// Creating 50 period and 200 period EMAs
len1 = input(50, minval=1, title="Short EMA Length")
src1 = input(close, title="Short EMA Source")
ema50 = ema(src1, len1)
plot(ema50, title="Short EMA", color=color.blue, linewidth=3)
len2 = input(200, minval=1, title="Long EMA Length")
src2 = input(close, title="Long EMA Source")
ema200 = ema(src2, len2)
plot(ema200, title="Long EMA", color=color.white, linewidth=3)

// Number of preceding candles to use in algorithm
lookback = input(title="Lookback", type=input.integer, defval=3, minval=1)

longCondition = (barssince(crossover(close, ema50)) <= lookback) and (close > ema50 and close > open) and ema50 > ema200
shortCondition = (barssince(crossunder(close, ema50)) <= lookback) and (close < ema50 and close < open) and ema50 < ema200

search_preceding_candles(_cond, _length) =>
    _found = false
    for i = 1 to _length
        if _cond[i]
            _found := true
            break
    _found

long = (longCondition and not search_preceding_candles(longCondition, lookback)) ? 1 : 0
short = (shortCondition and not search_preceding_candles(longCondition, lookback)) ? 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)

shortProfitPercent = input(title = "Profit %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100
shortLossPercent = input(title = "Loss %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100

// Calculating exact prices for stop loss and exit prices
shortExitPercentPrice = strategy.position_avg_price * (1 - shortProfitPercent)
shortStopPercentPrice = strategy.position_avg_price * (1 + shortLossPercent)

// Profit & Loss via ATR
shortExitPrice = useAtr ? strategy.position_avg_price - atr * atrMultiplier : shortExitPercentPrice
shortStopPrice = useAtr ? strategy.position_avg_price + atr * atrMultiplier : shortStopPercentPrice

// Plotting profit / loss targets
plot(series = (strategy.position_size < 0) ? shortExitPrice : na, color = #33b802, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Short Target")
plot(series = (strategy.position_size < 0) ? shortStopPrice : na, color = #ff0900, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Short Stop Loss")

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

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

Overview

50 EMA + 200 EMA Short Strategy (Not Good) enters short when the fast EMA is below the slow EMA, the close crosses below the fast EMA within a defined lookback period, and a bearish candle forms below the fast EMA. Exits are handled through configurable percentage-based or ATR-based stop-loss and take-profit orders. Main settings include EMA lengths, ATR multiplier, lookback window, and profit or loss thresholds. Plots both EMAs and active exit levels directly on the price chart.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Moving averages, Trend

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
Use ATR?boolfalseuseAtr
Short EMA Lengthint50len1
Short EMA Sourcesourceclosesrc1
Long EMA Lengthint200len2
Long EMA Sourcesourceclosesrc2
Lookbackint3lookback
ATR Lengthint14length
ATR Multiplierfloat1atrMultiplier
Profit %float10shortProfitPercent
Loss %float10shortLossPercent
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