Strategy · Pine Script v5 · On the chart

ema-strategy-algotrade

by akash-yellgetti· code credited to akash5792bts

A minimal strategy-type script for the price chart that draws a fast and a slow moving average, exponential or simple according to a toggle, and colours the lines and the area between them by the direction of the gap.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code125
Settings4inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago15 Jul 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

125 lines of Pine Script v5 from src/pinescript/ema-strategy-algotrade.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

ema-strategy-algotrade.pine

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © akash5792bts

//@version=5
strategy("ema-strategy-algotrade", overlay=true)



// --------------------------------------------------------------------------
// Madrid Trend Spotter
// --------------------------------------------------------------------------
src = input(close, title="Source")
fastLen = input.int(5,  title="Fast Length", minval=1)
slowLen = input.int(10, title="Slow Length", minval=1)
ema = input.bool(true, title="Exponential Moving Average")

maColor(fma, sma) =>
    fma > sma and ta.change(fma - sma, 3) > 0 ? color.new(color.lime, 0) : fma < sma and ta.change(fma - sma, 3) < 0 ? color.new(color.red, 0) : color.new(color.yellow, 0)

fastMA = ema ? ta.ema(src, fastLen) : ta.sma(src, fastLen)
slowMA = ema ? ta.ema(src, slowLen) : ta.sma(src, slowLen)

fastMAP = plot(fastMA, color=maColor(fastMA, slowMA), linewidth=3, title="fastTrend")
slowMAP = plot(slowMA, color=maColor(fastMA, slowMA), linewidth=3, title="slowTrend")
fill(fastMAP, slowMAP, color=maColor(fastMA, slowMA), transp=70, title="Area")
upCrossover = ta.crossover(fastMA, slowMA)
plotshape(series=upCrossover,  color=#44ce1b, text = 'B', textcolor = #ffffff, style=shape.labelup, size=size.tiny, location=location.belowbar)
// if(upCrossover)
//     alert("Fast crossed above Slow MA 5", alert.freq_once_per_bar_close)
downCrossunder = ta.crossunder(fastMA, slowMA)
plotshape(series=downCrossunder,  color=#f30000, text = 'S', textcolor = #ffffff, style=shape.labeldown, size=size.tiny, location=location.abovebar)
// if(downCrossunder)
//     alert("Fast crossed below Slow MA 5", alert.freq_once_per_bar_close)

//-----------------------------------------------------------------------------}
// AlgoTrade
//-----------------------------------------------------------------------------{

// Define intraday time range (e.g., 09:30 AM to 03:30 PM)
intradayStartTime = timestamp(year, month, dayofmonth, 09, 30)
// Equity Market Time
// intradayEndTime = timestamp(year, month, dayofmonth, 15, 15)
// Commodities Market Time
intradayEndTime = timestamp(year, month, dayofmonth, 23, 30)
// Define exit time (e.g., 03:15 PM)
// exitTime = timestamp(year, month, dayofmonth, 14, 45)
// exitTime = timestamp(year, month, dayofmonth, 15, 12)
// Commodities Market Exit Time
exitTime = timestamp(year, month, dayofmonth, 23, 00)
// exitTime = timestamp(year, month, dayofmonth, 15, 12)
// Entry conditions within the intraday time range
inIntradayTimeRange = (time >= intradayStartTime) and (time <= intradayEndTime)
// Exit condition at 03:15 PM
exitCondition = time >= exitTime
// Quatity
positionSize = 25

// STEP 2:
// Determine trail stop loss prices
longStopPrice = 0.0
shortStopPrice = 0.0

longStopPrice := if strategy.position_size > 0
    stopValue = fastMA
    math.max(stopValue, longStopPrice[1])
else
    0

shortStopPrice := if strategy.position_size < 0
    stopValue = fastMA
    math.min(stopValue, shortStopPrice[1])
else
    999999


// IsLong() returns 'true' when the strategy has an open long
// position. Returns 'false' when the script is short or flat.
IsLong() =>
    strategy.position_size > 0

// IsShort() returns 'true' when the strategy has an open short
// position. Returns 'false' when the script is long or flat.
IsShort() =>
    strategy.position_size < 0

// Define strategy parameters
longSignal = upos > upos[1] and inIntradayTimeRange
shortSignal = dnos > dnos[1] and inIntradayTimeRange

// Buy Entry and exit
// if longSignal
//     strategy.close_all('Enter New Buy')
//     strategy.close('Enter New Buy', "Close Existing Trade", qty_percent = 100)
//     strategy.exit("Exit Buy", from_entry="Enter Buy", stop=fastMA)
//     strategy.entry("Enter Buy", strategy.long, positionSize)
    
// // Sell Entry and exit
// if shortSignal
//     strategy.close_all('Enter New Sell')
//     strategy.close('Enter New Sell', "Close Existing Trade", qty_percent = 100)
//     strategy.exit("Exit Sell", from_entry="Enter Sell", stop=fastMA)
//     strategy.entry("Enter Sell", strategy.short, positionSize)

if upCrossover and inIntradayTimeRange
    strategy.close_all('ALL Trades')
    strategy.entry("LE", strategy.long, positionSize, stop=fastMA)

if downCrossunder and inIntradayTimeRange
    strategy.close_all('ALL Trades')
    strategy.entry("SE", strategy.short, positionSize, stop=fastMA)


// Exit conditions (simple exit at crossover or crossunder and exit at 03:15 PM)
if exitCondition
    strategy.close_all('Closing All orders')

// Submit exit orders for trail stop loss price
if strategy.position_size > 0
    strategy.exit("XL TRL STP", stop=longStopPrice)

if strategy.position_size < 0
    strategy.exit("XS TRL STP", stop=shortStopPrice)

//-----------------------------------------------------------------------------}

Overview

Inputs set the source, the fast length at five bars and the slow length at ten bars. Crossovers can be used as buy and sell cues. The supplied code shows no stop loss, take profit or position sizing logic.

Details

Published by

akash-yellgetti on GitHub

Code credit

akash5792bts, as written in the script's header

Type

Strategy, Pine Script v5

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
Sourcesourceclosesrc
Fast Lengthint5fastLen
Slow Lengthint10slowLen
Exponential Moving Averagebooltrueema
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 yesterday · 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