The best Pine Script strategy is not an over-tuned 500-line community indicator showing an inflated historical win rate. It is a clear, non-repainting (signals stay fixed once a bar closes) Pine Script v6 template combining one trend filter, one pullback (a short move against the main trend) or breakout trigger, dynamic Average True Range (ATR, a measure of average price movement per bar) stop-loss exits, and realistic commission and slippage (an order filling at a different, usually worse, price than the one you set) settings inside TradingView’s Strategy Tester.
This guide shows how leaving brokerage fees and slippage out turns a losing rule into a paper winner, provides a complete Pine Script v6 trend-pullback template with costs and stops built in, explains four TradingView Strategy Tester limits, and gives a five-step check before risking real money.
Why leaving fees and slippage out makes a Pine Script strategy look better
Per TradingView’s official Pine Script Strategies documentation, if you do not specify commission and slippage arguments, a strategy applies zero commission and zero slippage by default while TradingView’s broker emulator simulates cost-free fills on historical chart bars. The table below models an illustrative intraday strategy placing 400 round-trip trades (opening and closing a position) a year on 1.00 standard lot EUR/USD (a standard lot is 100,000 currency units; on this EUR/USD lot one pip, a small unit of change in a currency price, is worth $10.00) that makes +$3,200 (+0.8 pips per trade) before trading costs.
| Cost Scenario | Round-Trip Cost | Before Costs | Total Costs | Net Result |
|---|---|---|---|---|
| No fees set ($0) | 0.0 pips | +$3,200 | -$0 | +$3,200 |
| Commission only ($7) | 0.7 pips | +$3,200 | -$2,800 | +$400 |
| Raw + spread & slippage ($11) | 1.1 pips | +$3,200 | -$4,400 | -$1,200 |
| Standard + slippage ($16) | 1.6 pips | +$3,200 | -$6,400 | -$3,200 |
An unconfigured Pine test displays a +$3,200 result. Adding a raw-spread broker commission alone ($7 per lot = 0.7 pips) cuts the year’s profit by 87.5% to +$400; adding realistic raw spread plus slippage (1.1 pips = $11 per lot) flips the year to -$1,200; and running on a standard spread account with slippage (1.6 pips = $16 per lot) produces a -$3,200 net loss. Per TradingView Support’s Strategy Properties guide, set realistic commission and slippage either inside the strategy() header or in the script’s Settings/Properties menu before tuning any indicator inputs (compare real execution costs in the slippage in trading guide and lowest spread forex brokers guide). The chart below compares the annual net result across all four trading-cost levels.

More info: 400-trade cost model assumptions
Illustrative example assuming 400 round-trip trades per year on 1.00 standard lot EUR/USD ($10.00 per pip) earning +0.8 pips (+$3,200) before trading costs, tested at $0, $7, $11, and $16 all-in round-trip cost per trade. Not a forecast.
A simple Pine Script v6 trend-pullback template with fees and stops built in
A clear swing strategy—such as a 4-hour or daily trend-pullback system for major forex pairs or liquid stock indices during directional moves—fits into one short code block with explicit costs and no repainting or look-ahead leaks (pulling future candle data into earlier bars; review basic syntax first in the What Is Pine Script guide):
//@version=6
strategy("Clean Trend Pullback Template", overlay=true,
initial_capital=10000, default_qty_type=strategy.fixed, default_qty_value=100000,
margin_long=3.33, margin_short=3.33, slippage=2, calc_on_every_tick=false,
commission_type=strategy.commission.cash_per_order, commission_value=3.5)
// 1. Non-overlapping indicators & unconditional crossover (v6 lazy-and safe)
emaTrend = ta.ema(close, 50)
rsiVal = ta.rsi(close, 14)
atrVal = ta.atr(14)
rsiCrossUp = ta.crossover(rsiVal, 45)
// 2. Confirmed bar-close entry trigger (zero intra-bar repainting)
longCond = close > emaTrend and rsiCrossUp and barstate.isconfirmed
// 3. Risk-calibrated stop & fixed 2:1 structural exit latched at entry
var float entryStopDist = na
if longCond and strategy.position_size == 0
entryStopDist := atrVal * 1.5
strategy.entry("Long", strategy.long)
if strategy.position_size > 0 and not na(entryStopDist)
strategy.exit("LongExit", "Long", stop=strategy.position_avg_price - entryStopDist, limit=strategy.position_avg_price + entryStopDist * 2.0)
In plain words, the template buys when a bar closes above the 50-period exponential moving average (EMA, an average that gives recent prices more weight) and the 14-period Relative Strength Index (RSI, a momentum reading) crosses up through 45, with a stop 1.5 ATR below the entry and a target 3 ATR above it. Six design choices are built into this template based on TradingView’s Pine Script v6 documentation: //@version=6 syntax; fixed-unit sizing (100000 units = 1.00 EUR/USD standard lot) with margin_long=3.33 and margin_short=3.33 (30:1 forex margin—where margin is the deposit held to open a leveraged trade—overriding v6’s 100% default margin per TradingView’s v6 migration guide); commission_value=3.5 ($7.00 round-trip) and slippage=2; computing ta.crossover() unconditionally at the top level of the script (global scope, preventing Pine v6 lazy-and warning CW10003 per TradingView’s CW10003 error documentation); calc_on_every_tick=false paired with barstate.isconfirmed (per TradingView’s execution-model guide) so signals trigger only at bar close; and three non-overlapping indicators—50-period Exponential Moving Average (EMA) trend, 14-period Relative Strength Index (RSI) pullback, and 14-period ATR stop—with a fixed 2:1 exit bracket (targeting twice the stop distance; review higher-timeframe 2:1 swing rules in the beginner forex strategy guide). To test both directions without long-only bias, compute rsiCrossDn = ta.crossunder(rsiVal, 55) unconditionally at the top level of the script first, then mirror short entries via close < emaTrend and rsiCrossDn and barstate.isconfirmed with a 1.5 * ATR stop above entry and 3.0 * ATR downside target. Trend-pullback rules tend to suit sustained directional trends and struggle during flat sideways ranges.
Four TradingView Strategy Tester limits to keep in mind
Even with realistic fees, slippage, and bar-close entries configured, TradingView’s Strategy Tester broker emulator makes four historical simulation assumptions (documented across TradingView’s Pine Script Strategies and Support pages) that can overstate real-world returns unless you account for them:
- When a Stop-Loss and Take-Profit Fall Within One Bar: Per TradingView’s Strategies documentation, the broker emulator fills historical orders using only each candle’s available open, high, low, and close (OHLC) data and executes them after the bar closes. When both a stop-loss and a take-profit sit inside one historical bar, the candle does not show which level was touched first, so the test can get the order wrong; TradingView Support says Bar Magnifier mode, available on eligible plans per TradingView Pricing, can make these historical fills more realistic.
- Overnight Swap and Rollover Costs: TradingView’s Strategy Tester lets you model commission and slippage, so check separately whether broker overnight forex swap rates (financing charges on positions held past rollover, the daily overnight cutoff), weekly triple-swap rollovers, or stock short-borrow fees on multi-day trades are reflected—for example, by exporting trades to a spreadsheet.
- Synthetic Heikin Ashi Charts & Same-Close Fills: Assuming you can observe a bar’s close and fill immediately at that same closing price can inflate simulated returns. Per TradingView Support’s non-standard chart and broker-emulator guides, testing a strategy on Heikin Ashi candles (which plot mathematically averaged synthetic prices rather than actual market quotes) can execute simulated orders at those averaged prices and typically produces unrealistic results unless you test on regular candlesticks or enable
fill_orders_on_standard_ohlc = true. - Constant Slippage vs Live Spread Spikes: Per TradingView’s Strategies documentation, a strategy applies a constant slippage setting across every fill, so it does not capture sudden bid-ask spread (the gap between buying and selling price) widening during daily rollover or major economic announcements; adding a session-hour filter in Pine Script can keep simulated results closer to real brokerage statements.
Five steps to check a Pine Script strategy before using real money
Using TradingView’s Strategy Tester as a stress test—rather than tweaking inputs until past charts look spotless—can help separate steady systems from curve-fitted (over-tuned to past noise) rules that may break down live (align full validation steps with the strategy backtesting guide):
- Test Across Both Trending and Sideways Periods: A small handful of trades proves little; review a meaningful trade sample spanning trending and flat sideways market phases.
- Check Profit Factor, Max Drawdown, and Losing Streaks: Look past headline net profit—check post-cost Profit Factor (gross profit from winning trades divided by gross loss from losing trades), peak-to-trough drawdown (the largest drop from an account peak), and whether worst losing streaks fit your risk limit (check odds with the risk of ruin calculator).
- Nudge Key Inputs to Test Stability: Shift main settings slightly (for example, EMA 45/50/55 and ATR stop 1.25/1.5/1.75); a durable rule tends to degrade smoothly across neighboring values rather than collapsing off one exact number.
- Hold Back an Untouched Out-of-Sample Window: Use a date filter to build rules on earlier years only, then check performance on a later untouched slice of history (out-of-sample data) without changing code.
- Forward-Test Alerts on Paper Before Going Live: TradingView’s Strategy FAQs state that Pine Script strategies cannot directly place orders on exchanges. Attach webhook alerts (automated web messages to an external app, per TradingView’s webhooks guide) to confirmed bar closes, log paper fills alongside live broker spreads, and check lot sizing via the position size calculator—or port tested rules into a MetaTrader 5 Expert Advisor (automated trading program) or Python broker API (direct software link to a broker; MetaQuotes offers Python integration for MetaTrader 5).
A short Pine Script v6 swing template showing steady post-cost results across out-of-sample trades after commissions, slippage, and manual swap checks is generally more useful than a sprawling zero-cost script. Keep code compact, verify any higher-timeframe call reads prior closed bars consistently (using a prior-bar shifted expression paired with barmerge.lookahead_on per TradingView’s repainting guide), export the Strategy Tester trade list as a CSV file (a standard TradingView option) to inspect worst streaks independently, and keep live risk under 1% of account equity per trade (IG Academy’s risk-control guide notes keeping the risk amount per individual trade idea to less than 1%).
Sources: TradingView (Pine Script documentation: Strategies, Migration to Pine v6, Error CW10003, Execution Model, Repainting, and Strategy FAQs; Support articles on Strategy Properties, Broker Emulator, Bar Magnifier backtesting mode, Non-standard chart types, and Webhooks; Pricing), MetaQuotes (MetaTrader 5 Python Integration), and IG Academy (Controlling risk).
Frequently asked questions about Pine Script trading strategies
Is there one single best Pine Script strategy that works across all markets?
No single Pine Script strategy is likely to work across all markets and volatility phases. Trend-pullback rules like the template above tend to suit sustained directional trends and can struggle in sideways markets.
How do I add brokerage commissions and slippage to a Pine Script strategy?
Set commission and slippage either in the script’s strategy() header arguments or inside the script’s Settings/Properties dialog (per TradingView Support’s Strategy Properties guide) so simulated trades deduct realistic trading costs before you judge net return.
Why does my Pine Script strategy look great on Heikin Ashi charts but lose on regular candles?
Because Heikin Ashi candles plot mathematically averaged synthetic prices rather than real market transaction quotes. Per TradingView Support’s broker-emulator and non-standard chart guides, executing simulated orders at those averaged prices can produce unrealistic results that disappear on standard candlesticks.
How does TradingView’s broker emulator simulate fills on historical bars?
On historical bars, TradingView’s broker emulator reads only each candle’s open, high, low, and close rather than replaying every live tick, so it assumes orders execute after a bar closes. When a stop-loss and profit target both fall inside one bar, higher-detail intrabar testing (Bar Magnifier mode on eligible plans) improves fill ordering, while fill_orders_on_standard_ohlc = true keeps Heikin Ashi tests anchored to real candle prices.
Can I automate my Pine Script strategy directly on a forex broker?
No—TradingView states that Pine Script strategies cannot directly place orders on exchanges. To automate a tested Pine strategy, traders route confirmed-bar webhook alerts through an external connector or port the rules into a MetaTrader 5 Expert Advisor or Python broker API script.




