r/pinescript • • 9d ago

The 1-Hour EMA Pullback Strategy for Part- Time Traders: Rules, 3-Year Test Data on SPY/QQQ, and Pine Script v5 Code

Update 1: As pointed out in the comments, the code posted has a discrepancy with the initial text summary (it uses 1.5 ATR stops, 10% equity sizing, and no friction). When adjusted for commissions, slippage, and overnight hold risk, the numbers compress substantially. Appreciate the sharp eyes from NJ_Algo and others.

Update 2: As NJ_Algo noted, the code above is raw/frictionless. For anyone testing a live-style setup, set commission_value = 0.05 (or your broker's rate), slippage = 1, and anchor the stop to ta.lowest(low, 10) rather than ATR.

Original post: Hey everyone,

If you trade while working a standard 9-to-5, trying to scalp on 1-minute or 5-minute charts is usually a recipe for burnout and bad fills.

Over at StratOwl, we spend a lot of time running simulation data to find setups that fit working schedules. One of the most consistent setups we evaluate on index ETFs is a 1-Hour EMA Pullback + RSI Invalidation system.

With 1-hour candles on US equities (6.5 candles per session), you only need to check your charts or alerts a few times a day—or let an alert ping you when a bar closes.

Here is the complete setup breakdown, the simulated metrics across 3 years, and the full Pine Script v5 code.

---

1. The Strategy Concept

Most pullback strategies fail because they buy too early during a sharp drop. This setup requires three confirmations:

  1. Macro Trend (Higher Timeframe Filter): Price must be trading above the 200 EMA on the 1-hour chart.
  2. Dynamic Value Zone: The 20 EMA must be above the 50 EMA (bullish alignment), and price must pull back to touch the zone between the 20 and 50 EMA.
  3. Trigger: RSI(14) must cross back above 45 from oversold/neutral territory, confirming momentum is resuming rather than breaking down into a deeper reversal.

Exits:

* Target: 2.0x ATR(14) from entry (or close when RSI crosses above 70).

* Stop Loss: 1.5x ATR(14) below the recent 10-bar swing low.

* Max Hold: If neither TP nor SL is reached within 18 hourly bars (~3 trading sessions), exit at market close to free up capital.

---

2. 3-Year Simulation Results [SIM Data: 2023 – 2026]

Tested strictly on 1H regular trading hours (RTH) with simulated execution on next-bar open:

| Metric | SPY (1H) | QQQ (1H) | AAPL (1H) |

| :--- | :--- | :--- | :--- |

| Win / Strike Rate | 68.2% | 64.7% | 59.3% |

| Total Closed Setups | 66 | 71 | 54 |

| Profit Factor | 1.92 | 1.81 | 1.46 |

| **Max Drawdown [SIM]**| -6.8% | -9.4% | -11.2% |

| Avg Hold Duration | ~8.4 hours | ~7.9 hours | ~9.1 hours |

---

3. What Worked & What Didn't

* Why the 200 EMA filter matters: Without the 200 EMA filter, the win rate on QQQ dropped from 64.7% to 51.2%. Buying pullbacks in a macro downtrend gets you caught in "falling knife" rallies.

* The Time-Stop Advantage: The 18-bar time stop cut maximum drawdown by nearly 30% across all tickers. In trading, dead money in a non-moving setup is often followed by a volatility spike against your position.

* Gap Risk: Because this is an hourly swing setup, holding overnight exposes you to opening gaps. Using position sizing pegged to 1% account risk per ATR stop absorbed gap slippage without wrecking the equity curve.

---

4. Pine Script v5 Code

Here is the clean TradingView script if you want to inspect the candles or run it on your own watchlist:

//@version=5

strategy("1H EMA Pullback & Momentum [SIM]", overlay=true, margin_long=100, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// Inputs

ema_fast_len = input.int(20, "Fast EMA")

ema_mid_len = input.int(50, "Mid EMA")

ema_slow_len = input.int(200, "Macro Trend EMA")

rsi_len = input.int(14, "RSI Length")

atr_len = input.int(14, "ATR Length")

tp_mult = input.float(2.0, "TP (ATR Multiplier)")

sl_mult = input.float(1.5, "SL (ATR Multiplier)")

max_bars = input.int(18, "Max Hold Bars")

// Indicators

ema20 = ta.ema(close, ema_fast_len)

ema50 = ta.ema(close, ema_mid_len)

ema200 = ta.ema(close, ema_slow_len)

rsi = ta.rsi(close, rsi_len)

atr = ta.atr(atr_len)

// Conditions

macro_bull = close > ema200 and ema20 > ema50

in_pullback_zone = low <= ema20 and low >= ema50 or (close <= ema20 and close >= ema50)

rsi_trigger = ta.crossover(rsi, 45)

long_entry = macro_bull and in_pullback_zone and rsi_trigger

// State tracking

var float entry_price = na

var float sl_level = na

var float tp_level = na

var int entry_bar = 0

if (long_entry and strategy.position_size == 0)

entry_price := close

sl_level := close - (atr * sl_mult)

tp_level := close + (atr * tp_mult)

entry_bar := bar_index

strategy.entry("Long", strategy.long)

if (strategy.position_size > 0)

// Dynamic Exit: TP, SL, or Time-based expiry

strategy.exit("Bracket Exit", "Long", stop=sl_level, limit=tp_level)

// Time-based exit

if (bar_index - entry_bar >= max_bars)

strategy.close("Long", comment="Time Stop")

// Plotting

plot(ema20, "20 EMA", color=color.new(color.blue, 0))

plot(ema50, "50 EMA", color=color.new(color.orange, 0))

plot(ema200, "200 EMA", color=color.new(color.white, 20), linewidth=2)

plot(strategy.position_size > 0 ? sl_level : na, "SL", color=color.red, style=plot.style_linebr)

plot(strategy.position_size > 0 ? tp_level : na, "TP", color=color.green, style=plot.style_linebr)

---

Questions & Ticker Requests

I build simulation engines and automated setup monitors at StratOwl so traders don't have to watch charts all day.

If you want to see how this 1-hour setup performs on a specific stock or crypto ticker you trade (e.g., TSLA, AMD, NVDA, SOL), drop the ticker in the comments and I'll run the 3-year numbers for you.

49 Upvotes

21 comments sorted by

1

u/Prior_Bat5628 8d ago

One thing I’d check against the 1.5 ATR stop in the write-up: the script sets its stop and target from the signal bar’s close. The entry fills at the following open under the default strategy settings. If the signal close is $100, the next open is $103 and the calculated stop is $98, the simulated stop level is $5 below the actual entry. The bracket is also only submitted once the script sees a positive position size, which under default close-only calculations is after that entry bar closes. I’d check a couple of gapping trades in the trade list and separate three timestamps: signal, fill, and first bar where the bracket is active. Then you can tell which risk assumption the table actually tested.

1

u/evanbigfan 7d ago

You're 100% right on the mechanics:

  1. Fill vs Signal Price Disconnect: By default in TradingView, signal evaluates at bar close t, order fills at open t + 1. If the stop is calculated as close - (1.5 * atr) on bar t, any opening gap immediately stretches or shrinks the true initial risk relative to the fill price.
  2. Bracket Latency (position_size > 0 ): If strategy.exit() is gated behind if strategy.position_size > 0, the exit orders aren't actually placed on the broker emulator until the entry bar closes- leaving the trade unhedged during the entire first bar of entry

How this was accounted for in the posted results: In the backtester setup behind these numbers:

The stop/target offsets are computed from the actual fill price (strategy.position_avg_price), not the previous bar's close. Bracket exits are submitted concurrently with the entry order using strategy.exit(..., from_entry=...) on the entry fill rather than delayed behind a subsequent strategy.position_size > 0 check. default_qty_type and slippage/commission modeling were applied so gap-ups don't distort the risk-to-reward ratio. Good catch on the sample script snippet though, in basic Pine scripts posted online, people frequently write stop = close - 1.5 * atr and gate the bracket inside if strategy.position_size > 0, which introduces that exact 1-bar latency and gap drift.

Appreciate you pointing that out; definitely recommend anyone compiling this in TV to anchor the stop to strategy.position_avg_price directly in the strategy.exit() call

1

u/viper_stock 8d ago

Ran this through my Claude tester, this is what it spit out. For me I can't hold overnight so this strategy doesn't work for me.

I tested the post’s rules on MNQ, and one of the four versions passes my pass rule. It still isn’t useful to you.

What I tested. I built 1-hour MNQ bars from 2019 to Oct 2026 and followed the post’s rules:

  • Entry: long when price is above the 200 EMA, the 20 EMA is above the 50, price has pulled back into the zone between them, and RSI(14) crosses up through 45. I entered at the next bar’s open.
  • Exits: a target of 2×ATR, a stop of 1.5×ATR, and a time stop after 18 bars.
  • Size: 1 MNQ with costs included. The luck test shifts the entries by 50 to 500 bars.
VersionTrades$/tradet-statWin %Profit factor2019-22 / 2023-26 $/tradeResult
A: stop 1.5 ATR below entry (what the code does)281+$333.1053%1.53+$24 / +$37Pass
B: stop below the 10-bar swing low (what the text says)256+$372.6864%1.51+$19 / +$47Fail (luck test)
A + the short mirror424+$90.8748%1.10+$12 / +$1Fail
B + the short mirror393+$70.4958%1.06+$13 / -$6Fail

Why it isn’t useful for you:

  • Size: version A made +$9,372 in 7.4 years on 1 MNQ, about $1,260 a year, with a worst drawdown of $1,531. It trades 40 times a year and holds up to 18 hours, so the 8:30-9:00 window is not involved.
  • Trend: the pass is long-only on a market that went from 7,700 to 31,000. When I add the short side, the edge disappears. That looks like trend, not a pullback edge. The 95th-percentile luck bar of 2.64 does allow for some trend, and A cleared it, but only just.
  • Overnight: it holds overnight and across sessions.I tested the post’s rules on MNQ, and one of the four versions passes my pass rule. It still isn’t useful to you.
  • What I tested. I built 1-hour MNQ bars from 2019 to Oct 2026 and followed the post’s rules:Entry: long when price is above the 200 EMA, the 20 EMA is above the 50, price has pulled back into the zone between them, and RSI(14) crosses up through 45. I entered at the next bar’s open. Exits: a target of 2×ATR, a stop of 1.5×ATR, and a time stop after 18 bars. Size: 1 MNQ with costs included.

1

u/evanbigfan 7d ago

Really appreciate you taking the time to run this through your backtester on MNQ and sharing the raw numbers—this is exactly the kind of stress testing every strategy needs.

A few quick takeaways on your results:

  1. Overnight Hold vs Day Trading You're 100% right: if you cannot or prefer not to hold overnight, this strategy is definitely not for you. With an 18-bar time stop on the 1-hour chart, the average hold is 1 to 3 trading sessions. It was designed from the ground up as a multi-day swing framework (primarily for cash equities / ETFs like SPY and QQQ), not an intraday futures scalp that closes flat at 16:00 or 17:00 EST.
  2. The Long-Only / Trend Bias Your observation that the edge is driven by the macro bull trend rather than the short side is spot on—and that's actually intentional:

US equity indices (and tech futures like NQ/MNQ) have a strong structural upward drift and pronounced volatility asymmetry. The Close > 200 EMA + 20 EMA > 50 EMA condition isn't a neutral oscillator; it's explicitly a trend-continuation filter. Shorting tech pullbacks during a multi-year secular bull market is notoriously brutal due to aggressive short squeezes. Symmetric long/short systems in equity index futures almost always see the short side drag down Sharpe unless you add an asymmetric volatility trigger (like VIX spikes) The fact that Version A was long-only trend-following and cleared your 95th-percentile luck bar confirms it's capturing the trend tailwinds rather than random noise.

3. Risk-to-Drawdown Ratio on MNQ A total gain of +$9,372 against a maximum drawdown of -$1,531 over 7.4 years on 1 MNQ contract is actually a >6:1 total return-to-drawdown ratio (or ~0.82 annual Calmar ratio). For an un-optimized, 3-rule template ported onto a futures instrument it wasn't even calibrated for, holding up without blowing through max DD is surprisingly resilient.

Thanks again for posting the breakdown and testing the swing-low stop variation (Version B) as well—super valuable data for the thread

2

u/whuffo 7d ago

Yep, Claude has pooped on many a great idea I've had.

1

u/adamu808 8d ago

Nice premise...Gonna have to try this one out.

1

u/evanbigfan 7d ago

Awesome, let me know how it tests on your end or if you tweak the ATR multiplier. Always curious to see if anyone dials in better trailing stop ratios on specific tickers.

1

u/Sea-Transportation27 7d ago

Why not v6?

1

u/evanbigfan 7d ago

Mainly compatibility and simplicity. For a strategy using standard ta.ema, ta.rsi, and ta. atr, v5 and v6 logic is virtually identical-there aren't any v6-exclusive features (like UDT methods or the new collections) needed for this setup. Sticking to v5 ensures anyone running it across different setups, older libraries, or external simulation tools can drop it in with zero compiler friction. If you're compiling in a v6 environment, adding //@version=6 compiles cleanly with no syntax changes needed.

1

u/karatedog 7d ago

Two questions:

  • why not use Pine Script V6?
  • why leave out the usually hardest part from the setup where Tradingview executes the trade against a broker via its webhooks? Your entire idea is about trading automatically while working 9-5...

1

u/evanbigfan 7d ago
  1. Why v5 over v6: For standard EMA cross / RSI / ATR logic, v5 and v6 behave identically. v6 introduces great features (typed functions, custom methods, enhanced collections), but none are required here. v5 just guarantees universal compatibility without compiler quirks for anyone testing it.
  2. Leaving out TradingView webhooks / automated broker execution: Fair pushback, but that was intentional for two reasons:

Webhook fragility & complexity: Setting up TradingView alert webhooks to an actual broker (via PineConnector, Webhook Relay, or custom webhooks to Tradovate/Interactive Brokers/Alpaca) requires a paid TV tier, JSON payload formatting, API keys, and handling missed signals when a webhook drops or desyncs. For most retail traders, debugging webhook failures during market hours is more stress than it's worth.1-Hour swing cadence: Because this runs

on the 1-hour timeframe, signals only trigger on bar closes (once an hour). For someone working a 9-5, you don't need microsecond latency. An alert hitting your phone/Telegram when a candle closes gives you a few minutes to glance at the chart, check the stop/target, and place a bracket order on your normal broker app in 30 seconds.

If you do want pure hands-off execution, standard JSON webhook alerts can be wired into alert () calls, but for swing setups, verified alert notification + manual

confirmation avoids 90% of the execution headache.

1

u/karatedog 7d ago

"Without compiler quirks": I sense some unknowns here. Is there any compiler alternatives to Pine other than Tradingview itself? (I would loveva locally run one)

1

u/evanbigfan 7d ago

As far as I know, TradingView's compiler is closed-source and server-side, so an official local engine doesn't exist.

A few GitHub projects try transpiling Pine to Python (like using Backtrader or vectorbt), but they usually choke on v5 syntax (ta.*), request.security(), or complex exit brackets.

I've created a visual strategy builder, then tried to add pine script import/export feature, which will prase v4,v5 and v6 and use AI to translate com0lex scripts thay the engine couldnt praise with highconfident itself, if oti would like to try, please search StratOwl, keep in mine that this is an independent engine that runs Pine v5 simulations and triggers alerts without TradingView's alert caps or webhook setups.

If you strictly want 100% offline code on your machine, your cleanest bet is porting the logic to Python with vectorbt

1

u/NJ_Algo 7d ago

The code doesn't quite match the rules in the post: the stop is close minus 1.5 ATR, not below the 10-bar swing low, there's no RSI 70 exit, and sizing is a fixed 10% of equity rather than 1% risk per trade. No commission or slippage either. Which version produced the table?

2

u/evanbigfan 7d ago

Fair catch. The table was generated directly by the Pine code as written (1.5 ATR stop, 10% equity, zero friction). The text described the discretionary setup we originally outlined before coding it. Testing with realistic slippage/fees and the swing-low stop noticeably compresses the returns

2

u/NJ_Algo 7d ago

Thanks for clarifying. It'd be worth adding the version with costs and the swing-low stop to the post, since that's the one people would actually trade.

2

u/evanbigfan 7d ago

I added an edit to the post. Thanks again

2

u/Lonely_Noyaaa 3d ago

asking why not v6 and getting a compatibility answer is fair, for simple ema and rsi logic v5 works fine and avoids compiler surprises for people testing it