Strategy · Pine Script v4 · Own pane

EMA Difference Mapping with Trades

by hasnocool

This strategy plots a mapped EMA-and-standard-deviation difference in a separate pane and trades moving-average crossovers filtered by that line.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code64
Settings4inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

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

64 lines of Pine Script v4 from Ahsan Tufail Precise MA Crossover Filter for Reliable Signals.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Ahsan Tufail Precise MA Crossover Filter for Reliable Signals.pine
//@version=4
strategy(title="EMA Difference Mapping with Trades", shorttitle="EMA Diff Map", overlay=false)
// Inputs
emaLength = input(20, "EMA Length")
stdDevLength = input(2, "Standard Deviation Length")
priceSource = close
takeProfitPoints = input(1000, title="Take Profit (in Points)")
stopLossPoints = input(2500, title="Stop Loss (in Points)")
// Calculate EMA
ema = ema(priceSource, emaLength)
// Calculate Standard Deviation
stdDev = stdev(priceSource, stdDevLength)
// Calculate differences
diff1 = (ema + stdDev) - ema
diff2 = ema - (ema - stdDev)
// Calculate min and max differences from last year
lookbackPeriod = 504 // Number of trading days in a year
minDiff1 = lowest(diff1, lookbackPeriod)
maxDiff1 = highest(diff1, lookbackPeriod)
minDiff2 = lowest(diff2, lookbackPeriod)
maxDiff2 = highest(diff2, lookbackPeriod)
// Map differences based on requirements
mappedDiff1 = 50 + 50 * ((diff1 - minDiff1) / (maxDiff1 - minDiff1))
mappedDiff2 = 50 - 50 * ((diff2 - minDiff2) / (maxDiff2 - minDiff2))
// Combine mapped differences into a single line
mappedLine = if close > ema
    mappedDiff1
else
    mappedDiff2
// Plot 'mappedLine' in the main chart area conditionally
plot(mappedLine, title="EMA Difference Mapping", color=(close > ema ? color.blue : na), style=plot.style_line, linewidth=2)
// Calculate the 50EMA and 200SMA
ema50 = ema(close, 50)
sma200 = sma(close, 200)
// Plot the 50EMA and 200SMA on the main chart
plot(ema50, color=color.blue, title="50 SMA", linewidth=2)
plot(sma200, color=color.red, title="200 SMA", linewidth=2)
// Initialize trade variables
var bool waitingForBuy = na
var bool waitingForSell = na
var bool buyConditionMet = false
var bool sellConditionMet = false
if not sellConditionMet and crossunder(ema50, sma200)
    sellConditionMet := true
    waitingForBuy := false
if sellConditionMet 
    waitingForSell := true
    sellConditionMet := false
if waitingForSell and close < sma200 and mappedLine > 75
    strategy.entry("Sell", strategy.short)
    strategy.exit("Sell Exit", "Sell", profit=takeProfitPoints, loss=stopLossPoints)
    waitingForSell := false
// Define the strategy conditions and execute trades
if not buyConditionMet  and crossover(ema50, sma200)
    buyConditionMet := true
    waitingForSell := false
if buyConditionMet 
    waitingForBuy := true
    buyConditionMet := false
if waitingForBuy and close > sma200 and mappedLine < 25
    strategy.entry("Buy", strategy.long)
    strategy.exit("Buy Exit", "Buy", profit=takeProfitPoints, loss=stopLossPoints)
    waitingForBuy := false
Expand (81 lines)

Overview

After the 50-period EMA crosses the 200-period SMA, it waits for price to stay on the crossover side and for the mapped line to pass 75 for shorts or 25 for longs. Entries use strategy.entry, and exits use point-based take profit and stop loss. Inputs change the EMA length, standard-deviation length, and both exit distances. The 50 EMA and 200 SMA are drawn in the same pane as the mapped line.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v4

Draws

Separate pane below the chart

Category

Trend, Moving averages, 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.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
EMA Lengthint20emaLength
Standard Deviation Lengthint2stdDevLength
Take Profit (in Points)int1000takeProfitPoints
Stop Loss (in Points)int2500stopLossPoints
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

EMA Ribbon MACD

by iamrichardD
57 stars

This strategy combines an EMA ribbon with MACD confirmation and plots in a separate pane. It enters when ribbon alignment, optional MACD zero or signal crosses, volume, smart-money, and multi-timeframe filters agree, then exits with percentage stop loss and ta

Strategy v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon MACD

Kenny's Strategy

by jerryinyang
5 stars

Kenny's Strategy combines multiple exponential moving averages to identify trend changes and generate entry signals. It calculates short, medium, and long EMAs from a user-selected source and checks for alignment within specific zones. A long-term EMA filter r

Strategy v4 TrendMoving averages
Updated 2 years ago · None stated GitHub repository of Kenny's Strategy

WaveTrend with Crosses [LazyBear]

by avatar-lavventura
2 stars

This strategy combines multiple technical indicator systems into a composite trading setup. It computes an Ichimoku Cloud, an ATR-based trailing stop system (nKRAL) with optional Heikin Ashi smoothing, Bollinger Bands, Parabolic SAR, and higher-timeframe Super

Strategy v4 TrendVolatility & bands
Updated 7 months ago · None stated GitHub repository of WaveTrend with Crosses [LazyBear]

ETHBTC MTPI

by Mikelkulla
1 stars

ETHBTC MTPI is a multi-indicator trend-following strategy designed for crypto pairs to determine relative market strength. It combines up to five toggleable components: Liquidity-Weighted Supertrend, dual exponential moving averages, DEMA Supertrend, DEMA AFR,

Strategy v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of ETHBTC MTPI

Sentiment 2

by ggamer5555
1 stars

Sentiment 2 is a trend-following strategy that calculates a normalized composite market sentiment score ranging between 0 and 1. It combines exponential and Hull moving average slopes, high/low midpoints, Supertrend distances, and Parabolic SAR metrics. Plotte

Strategy v6 TrendMoving averages
Updated 5 months ago · None stated GitHub repository of Sentiment 2

Strategy Template

by MoDarK-MK
1 stars

This strategy template provides a modular foundation for building TradingView v6 backtests. It uses a placeholder Exponential Moving Average crossover signal combined with customizable filters for higher-timeframe trend alignment, volatility regime thresholds,

Strategy v6 TrendMoving averages
Updated 7 weeks ago · MPL-2.0 GitHub repository of Strategy Template

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