Strategy · Pine Script v6 · On the chart

Strategy Template

by Jahanzaib211

A strategy template that enters long when a fast EMA crosses above a slow EMA while price is above a higher-timeframe EMA, and short on the opposite setup, optionally limited to a session window.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code92
Settings8inputs
LicenceMIT
Last updateyesterday28 Oct 2026

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

92 lines of Pine Script v6 from skills/public/pine-script/templates/strategy.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

strategy.pine
//@version=6
// Strategy template — realistic backtest defaults, no look-ahead, manual metrics.
// Replace the entry logic; keep the risk, cost, and metric scaffolding.
strategy("Strategy Template", overlay = true,
     initial_capital         = 10000,
     default_qty_type        = strategy.fixed,
     default_qty_value       = 1,
     commission_type         = strategy.commission.cash_per_contract,
     commission_value        = 0.5,
     slippage                = 2,
     pyramiding              = 0,
     process_orders_on_close = false,
     calc_on_every_tick      = false)

// ── Inputs ──────────────────────────────────────────────────────────────────
fastLen   = input.int(9,    "Fast EMA",       minval = 1)
slowLen   = input.int(21,   "Slow EMA",       minval = 1)
atrLen    = input.int(14,   "ATR length",     minval = 1)
atrMult   = input.float(1.5, "Stop (ATR x)",  minval = 0.1, step = 0.1)
rr        = input.float(2.0, "Reward:Risk",   minval = 0.1, step = 0.1)
htfTf     = input.timeframe("60", "Trend timeframe")

useSession = input.bool(true, "Session filter", group = "Filters")
sessSpec   = input.session("0700-1600", "Session (exchange tz)", group = "Filters")

// ── Higher-timeframe bias ───────────────────────────────────────────────────
// lookahead_off is mandatory: without it this returns values that were not
// knowable at the time, and the backtest becomes untradeable fiction.
htfEma = request.security(syminfo.tickerid, htfTf, ta.ema(close, slowLen),
     lookahead = barmerge.lookahead_off,
     gaps      = barmerge.gaps_off)

// ── Indicators ──────────────────────────────────────────────────────────────
fastEma = ta.ema(close, fastLen)
slowEma = ta.ema(close, slowLen)
atr     = ta.atr(atrLen)

inSession = not useSession or not na(time(timeframe.period, sessSpec))

// ── Entry logic (replace this) ──────────────────────────────────────────────
longSignal  = ta.crossover(fastEma, slowEma)  and close > htfEma and inSession
shortSignal = ta.crossunder(fastEma, slowEma) and close < htfEma and inSession

// Only act on a closed bar — acting on a forming bar makes live signals
// flicker and diverge from the backtest.
canTrade = barstate.isconfirmed and strategy.position_size == 0

if longSignal and canTrade
    stopPx   = close - atr * atrMult
    targetPx = close + atr * atrMult * rr
    strategy.entry("Long", strategy.long)
    strategy.exit("Long Exit", "Long", stop = stopPx, limit = targetPx)

if shortSignal and canTrade
    stopPx   = close + atr * atrMult
    targetPx = close - atr * atrMult * rr
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", stop = stopPx, limit = targetPx)

// ── Metrics ─────────────────────────────────────────────────────────────────
// strategy.profit_factor / avg_winning_trade / avg_losing_trade are Strategy
// Tester UI metrics and are NOT readable here. Compute them, guarding every
// division — grossloss is 0 until the first loss and na propagates silently.
profitFactor = strategy.grossloss    != 0 ? math.abs(strategy.grossprofit / strategy.grossloss) : na
avgWin       = strategy.wintrades     > 0 ? strategy.grossprofit / strategy.wintrades           : na
avgLoss      = strategy.losstrades    > 0 ? strategy.grossloss   / strategy.losstrades          : na
winRate      = strategy.closedtrades  > 0 ? strategy.wintrades   / strategy.closedtrades * 100  : na
expectancy   = strategy.closedtrades  > 0 ? strategy.netprofit   / strategy.closedtrades        : na

var float peakEquity = 0.0
peakEquity := math.max(peakEquity, strategy.equity)
drawdown = peakEquity - strategy.equity

// ── Plots ───────────────────────────────────────────────────────────────────
plot(fastEma, "Fast EMA", color.new(color.aqua,   0))
plot(slowEma, "Slow EMA", color.new(color.orange, 0))
plot(htfEma,  "HTF EMA",  color.new(color.gray,  40))

if barstate.islast
    var table stats = table.new(position.top_right, 2, 6, border_width = 1)
    table.cell(stats, 0, 0, "Net profit",    text_color = color.white)
    table.cell(stats, 1, 0, str.tostring(strategy.netprofit, "#.##"), text_color = color.white)
    table.cell(stats, 0, 1, "Trades",        text_color = color.white)
    table.cell(stats, 1, 1, str.tostring(strategy.closedtrades),      text_color = color.white)
    table.cell(stats, 0, 2, "Win rate %",    text_color = color.white)
    table.cell(stats, 1, 2, str.tostring(winRate, "#.#"),             text_color = color.white)
    table.cell(stats, 0, 3, "Profit factor", text_color = color.white)
    table.cell(stats, 1, 3, str.tostring(profitFactor, "#.##"),       text_color = color.white)
    table.cell(stats, 0, 4, "Expectancy",    text_color = color.white)
    table.cell(stats, 1, 4, str.tostring(expectancy, "#.##"),         text_color = color.white)
    table.cell(stats, 0, 5, "Max DD",        text_color = color.white)
    table.cell(stats, 1, 5, str.tostring(drawdown, "#.##"),           text_color = color.white)

Overview

Entries happen only on a confirmed bar with no open position. Each trade gets an ATR-based stop and a target from a reward-to-risk ratio. The template sets commission and slippage, uses one position at a time, and requests higher-timeframe data without lookahead.

Details

Published by

Jahanzaib211 on GitHub

Type

Strategy, Pine Script v6

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.

Topics

agentaideveloper-toolsfastapilanggraphnextjsopen-sourcepythonsandbox

Settings

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

SettingTypeDefaultVariable
Fast EMAint9fastLen
Slow EMAint21slowLen
ATR lengthint14atrLen
Stop (ATR x)float1.5atrMult
Reward:Riskfloat2.0rr
Trend timeframetimeframe60htfTf
Session filterbooltrueuseSession
Session (exchange tz)session0700-1600sessSpec
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