Strategy · Pine Script v6 · On the chart

Bot Builder Template - EMA Pullback

by jeremynahim99

A Pine Script strategy template for an Exponential Moving Average pullback trading model with risk management controls.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code76
Settings12inputs
LicenceMIT
Last update10 days ago14 Nov 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

76 lines of Pine Script v6 from pine/bot_strategy_template.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

bot_strategy_template.pine
//@version=6
// BOT BUILDER - TradingView strategy template (Artillery Trades)
// Textbook EMA trend-pullback example for learning. Not financial advice.
// Alerts: create the alert with "Order fills only" and message {{strategy.order.alert_message}}.
// Edit the inputs, or paste your Bot Spec into Claude/ChatGPT and ask it to rewrite the ENTRY RULES section.
strategy("Bot Builder Template - EMA Pullback", overlay = true,
     initial_capital = 50000, default_qty_type = strategy.fixed, default_qty_value = 1,  // order size is set by the "Contracts per trade" input below
     commission_type = strategy.commission.cash_per_contract, commission_value = 2.5,
     slippage = 2, process_orders_on_close = true, max_bars_back = 500)

// ---------- INPUTS ----------
grpS = "Signal"
fastLen  = input.int(20, "Fast EMA", group = grpS)
slowLen  = input.int(50, "Slow EMA", group = grpS)
grpR = "Risk"
atrLen   = input.int(14, "ATR length", group = grpR)
stopATR  = input.float(1.0, "Stop = ATR x", step = 0.1, group = grpR)
targetR  = input.float(2.0, "Target (R)", step = 0.25, group = grpR)
maxTrades = input.int(2, "Max trades per day", group = grpR)
dailyStopR = input.float(2.0, "Daily stop (R lost)", step = 0.5, group = grpR, tooltip = "No new trades once the day is down this many R")
grpT = "Time"
tz       = input.string("America/New_York", "Time zone for the windows", group = grpT)
sess     = input.session("0945-1530", "Entry window", group = grpT)
flatSess = input.session("1555-1600", "Flatten window", group = grpT)
grpA = "Alerts / webhook"
ticker   = input.string("MNQ1!", "Ticker sent in alerts", group = grpA)
qty      = input.int(1, "Contracts per trade", minval = 1, group = grpA)

// ---------- INDICATORS ----------
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
atr  = ta.atr(atrLen)
plot(fast, "Fast EMA", color.new(color.teal, 0), 2)
plot(slow, "Slow EMA", color.new(color.orange, 0), 2)

// ---------- DAY TRACKING (trades + daily stop in R) ----------
var int   tradesToday = 0
var float dayStartEq  = na
var float lastRisk    = na
newDay = ta.change(time("D")) != 0
if newDay
    tradesToday := 0
    dayStartEq  := strategy.equity
riskCash = nz(lastRisk, atr * stopATR) * syminfo.pointvalue * qty
dayLocked = riskCash > 0 and (strategy.equity - nz(dayStartEq, strategy.equity)) <= -dailyStopR * riskCash

inWindow = not na(time(timeframe.period, sess, tz))
flatNow  = not na(time(timeframe.period, flatSess, tz))

// ---------- ENTRY RULES (edit these) ----------
longSig  = fast > slow and low <= fast and close > fast
shortSig = fast < slow and high >= fast and close < fast

canTrade = inWindow and strategy.position_size == 0 and tradesToday < maxTrades and not dayLocked and atr > 0
risk = atr * stopATR
longSL  = math.round_to_mintick(close - risk)
longTP  = math.round_to_mintick(close + targetR * risk)
shortSL = math.round_to_mintick(close + risk)
shortTP = math.round_to_mintick(close - targetR * risk)

if canTrade and longSig
    lastRisk := risk
    strategy.entry("Long", strategy.long, qty = qty, alert_message = '{"ticker":"' + ticker + '","action":"buy","quantity":' + str.tostring(qty) + ',"stopLoss":' + str.tostring(longSL) + ',"takeProfit":' + str.tostring(longTP) + '}')
    strategy.exit("Long exit", "Long", stop = longSL, limit = longTP, alert_message = '{"ticker":"' + ticker + '","action":"exit"}')
    tradesToday += 1
else if canTrade and shortSig
    lastRisk := risk
    strategy.entry("Short", strategy.short, qty = qty, alert_message = '{"ticker":"' + ticker + '","action":"sell","quantity":' + str.tostring(qty) + ',"stopLoss":' + str.tostring(shortSL) + ',"takeProfit":' + str.tostring(shortTP) + '}')
    strategy.exit("Short exit", "Short", stop = shortSL, limit = shortTP, alert_message = '{"ticker":"' + ticker + '","action":"exit"}')
    tradesToday += 1

// ---------- FLAT BEFORE THE CLOSE ----------
if flatNow and strategy.position_size != 0
    strategy.close_all(comment = "EOD flat", alert_message = '{"ticker":"' + ticker + '","action":"exit"}')

bgcolor(dayLocked ? color.new(color.red, 90) : na, title = "Daily stop hit")

Overview

Bot Builder Template - EMA Pullback identifies entries when a fast EMA is aligned with a slow EMA and price pulls back to touch the fast EMA within a specified session window. The script applies ATR-based stop losses, fixed R-multiple take profits, daily trade limits, maximum daily R loss guards, and end-of-day position flattening. It draws EMAs on the main price chart and formats order alert messages into JSON strings for automated execution.

Details

Published by

jeremynahim99 on GitHub

Draws

On the price chart

Markets

Indices

Timeframes

M1-M5, M15-H1

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

aialgorithmic-tradingbacktestingchatgptclaudefuturesmetatrader5ninjatraderpine-scriptprompt-engineeringtrading-bottradingview

Settings

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

SettingTypeDefaultVariable
Fast EMAint20fastLen
Slow EMAint50slowLen
ATR lengthint14atrLen
Stop = ATR xfloat1.0stopATR
Target (R)float2.0targetR
Max trades per dayint2maxTrades
Daily stop (R lost)float2.0dailyStopR
Time zone for the windowsstringAmerica/New_Yorktz
Entry windowsession0945-1530sess
Flatten windowsession1555-1600flatSess
Ticker sent in alertsstringMNQ1!ticker
Contracts per tradeint1qty
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

257 stars

Donald - Test Logic Futures is an overlay strategy designed for intraday futures trading. It combines kernel regression functions with exponential moving averages to evaluate price retracements and entry timing. Trades are filtered by session execution windows

Strategy v5 TrendMoving averages Repaints
Updated 2 months ago · None stated GitHub repository of Donald - Test Logic Futures

Andean Scalping

by hasnocool
106 stars

Andean Scalping is a Pine Script v5 strategy template designed for backtesting trading signals. It features session and date-range filtering, directional trade toggles for long and short entries, and optional trend filtering tools including higher-timeframe EM

Strategy v5 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of Andean Scalping

This strategy plots a 90-period simple moving average from the daily and four-hour charts plus a daily session VWAP on the price chart. It enters long when VWAP is above the daily average and the four-hour VWAP crosses above its average, and short in the oppos

Strategy v5 TrendMoving averages Repaints
Updated 3 years ago · MIT GitHub repository of 1D Bullish Buy 4H Bearish Sell Session
5 stars

This strategy executes trades on 5-minute index futures using Exponential Moving Averages, RSI, ADX, and volume filters across multiple timeframes. It supports trend pullback and VWAP reversion regimes with entry confirmation on breakout of prior high or low p

Strategy v6 TrendMean reversion
Updated 2 weeks ago · None stated GitHub repository of Lucid 100K Prop Bot (MES 5m)

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers