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.
//@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.
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
Fast EMA
int
9
fastLen
Slow EMA
int
21
slowLen
ATR length
int
14
atrLen
Stop (ATR x)
float
1.5
atrMult
Reward:Risk
float
2.0
rr
Trend timeframe
timeframe
60
htfTf
Session filter
bool
true
useSession
Session (exchange tz)
session
0700-1600
sessSpec
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.
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
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
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
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
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
This educational strategy demonstrates how to configure and handle user input parameters in Pine Script. It calculates two Simple Moving Averages (SMAs) for fast and slow periods, plotting both directly on the price chart. The strategy initiates a long positio