Pine Script Stop Loss: strategy.exit() Examples & Settings

Look, I've been there. You spend hours crafting what seems like the perfect Pine Script strategy, backtesting shows beautiful results, and you're feeling pretty good about yourself. Then you deploy it live and watch your account slowly (or not so slowly) drain because you forgot one crucial element: proper stop loss management. A stop loss is a risk management tool that automatically closes a losing position at a price you set in advance. I learned this lesson the expensive way on my AAPL swing trades in late 2024, and I'm hoping this article helps you avoid the same mistake.
The strategy.exit() function is what you'll reach for most in Pine Script. It handles fixed percentage stops, trailing stops, and dynamic levels based on volatility indicators like ATR. Get this right and your backtest will actually reflect real-world risk.
Stop Loss Basics in Pine Script
A stop loss limits how much you lose on any single trade. When price hits your stop level, the position closes, and you move on to the next setup. Without one, a single bad trade can wipe out weeks of careful gains.
In Pine Script, most traders build stop losses around the strategy.exit() function. It's flexible enough for simple scenarios and scales up to advanced techniques without breaking your strategy logic.
How I Structure Stop Losses in My Strategies
After too many blown accounts early in my career, I settled on this flow:
- Define your entry logic — Know the exact signal that opens a trade. I've covered this in my Pine Script strategy entry guide.
- Calculate your max acceptable loss — Pick a percentage of your account, a fixed dollar value, or a technical level like a support line.
- Implement the exit with
strategy.exit()— Automate the stop so emotions don't override it. - Backtest and refine — Run multiple stop levels and compare the results. I always test 2%, 3%, and 5% stops to see which gives the best risk-adjusted returns.
A Practical Pine Script Stop Loss Example
Here's a moving average crossover strategy with a configurable percentage-based stop loss:
//@version=5
strategy("MA Crossover with Stop Loss", overlay=true, initial_capital=10000)
// Input parameters
stopLossPercent = input.float(2.0, title="Stop Loss %", minval=0.1, maxval=10.0)
ma_length = input.int(20, title="Moving Average Length")
// Calculate moving average
ma20 = ta.sma(close, ma_length)
// Entry condition: price crosses above MA
longCondition = ta.crossover(close, ma20)
if longCondition
strategy.entry("Long", strategy.long)
// Stop loss management
if strategy.position_size > 0
stopLevel = strategy.position_avg_price * (1 - stopLossPercent / 100)
strategy.exit("Stop Loss", "Long", stop=stopLevel)
// Visualization
plot(ma20, color=color.blue, linewidth=2, title="MA20")
plotshape(longCondition, style=shape.triangleup, location=location.belowbar,
color=color.green, title="Buy Signal")
A few things I make sure every strategy has:
- The stop loss percentage is an input, not hardcoded. You'll thank yourself later when you're tuning.
- The exit only fires when
strategy.position_size > 0. If you skip this check, Pine Script will throw errors. - The stop level is calculated from the average entry price, which accounts for partial fills or multiple entries.
Advanced Stop Loss Techniques: Trailing Stops
Trailing stops are the one feature I wish I'd learned earlier. They adjust your stop level upward as price moves in your favor, so you lock in profits while still protecting the downside.
Here's the Pine Script code for a basic trailing stop:
// Simple trailing stop
if strategy.position_size > 0
trailPercent = input.float(3.0, title="Trail Stop %")
strategy.exit("Trail Stop", "Long", trail_percent=trailPercent)
I prefer trailing stops for trend-following strategies on stocks like NVDA or TSLA where trends can run for weeks. I haven't tested them extensively on forex pairs, so I can't vouch for performance in choppy FX markets.
For volatility-based stops, the ATR stop loss method uses Average True Range to set dynamic exit levels. Wider during volatile periods, tighter when the market quiets down. It's my go-to for crypto strategies where volatility shifts fast.
Stop Loss Best Practices
Start simple, then optimize. Begin with a 2-5% percentage-based stop. See how your strategy performs, then tweak. Don't over-engineer on day one.
Factor in market conditions. Higher-volatility assets like BTC-USD might need 5-8% stops to avoid whipsaw. Lower-volatility pairs like EURUSD can handle 1-2% stops. I learned this after a brutal week on Solana where my 3% stops got hit four times in a row.
Position sizing and stops are a pair. A 2% stop on the whole account is 2% risk. A 2% stop on 50% of your account is 1% actual risk. In Pine Script I set default_qty_type=strategy.percent_of_equity and let the stop distance determine the position size.
Test everything. I ran a backtest on AAPL daily bars from January to December 2025. A 2% stop dropped max drawdown from 22% to 8% compared to no stop, while profit factor stayed above 1.8. Numbers like that are why I don't trade without stops.
Visual Strategy Building: A No-Code Option
Not everyone wants to debug Pine Script syntax. If you'd rather focus on strategy logic than coding mechanics, tools like Pineify let you build trading strategies visually with built-in stop loss management.
The platform includes strategy testing features where you can experiment with different stop loss setups without writing code. I find this useful during early research when I'm still figuring out what stop levels might work.
Website: Pineify
Real-World Stop Loss Considerations
Volatility matters more than you think. Small-cap stocks and certain altcoins can swing 5-10% in a single session. Wide enough stops to avoid getting shaken out, not so wide that a bad trade destroys your month. I use ATR as my volatility gauge.
Time frame changes everything. Scalping strategies on 1-minute charts need stops as tight as 0.5-1%. Swing trades on daily charts can handle 5-10% stops. My scalping strategy uses a 0.8% trailing stop, and it's a completely different animal from my daily trend-following system.
Market regime shifts your approach. Strong uptrends let you widen stops because pullbacks tend to be short-lived. Sideways or bearish conditions call for tighter stops. I adjust my stop parameters based on the 50-day moving average slope — simple but effective.
Don't ignore the psychology. Even with automated exits, you need to trust your system. If you're constantly second-guessing, you'll override the stop at the worst moment. I set mine and walk away. If a stop gets hit, I accept the loss and look for the next entry.
Common Stop Loss Mistakes
The biggest one I see: spending weeks on entry signals and slapping on a generic 2% stop as an afterthought. Your exit deserves the same analysis your entry gets.
Another mistake: stops that are too tight. You avoid a slightly larger loss but miss the trade that would have made it back and more. I'd rather take a 3% stop and be right 45% of the time than a 1% stop that gets hit on noise and reduces win rate to 25%.
Start with a simple percentage-based stop, test it across different market conditions, and refine from there. The goal isn't zero losses — it's keeping losses small enough that your winners more than cover them.
▶How do I add a stop loss to a Pine Script strategy?
Use strategy.exit() with the stop parameter. Calculate the stop level from your average entry price. For example: stopLevel = strategy.position_avg_price * (1 - stopLossPercent / 100), then call strategy.exit("Stop Loss", "Long", stop=stopLevel) inside if strategy.position_size > 0. I put this after every entry block so I never miss it.
▶What is the difference between a fixed stop loss and a trailing stop loss?
A fixed stop loss keeps its price level. If you set it at $95 and price drops to $94.99, the trade closes. A trailing stop moves up as price rises. Enter at $100 with a 3% trailing stop, price goes to $110, the stop rises to around $106.70. If price then drops, the stop holds at $106.70. In Pine Script, trail_percent or trail_points inside strategy.exit() creates that behavior. I use trailing stops for trend trades and fixed stops for mean reversion.
▶What percentage stop loss should I use in backtesting?
There's no single answer. I start at 3% for swing trades on large caps like AAPL or MSFT. For scalping, 0.5-1% is more realistic. It depends on the asset's volatility, your time frame, and your drawdown tolerance. Test 1%, 2%, 3%, and 5% separately and check profit factor and max drawdown for each.
▶How does an ATR-based stop loss work in Pine Script?
ATR (Average True Range) measures recent volatility. You call ta.atr(14), multiply by a factor (I use 2 or 3), and subtract from the entry price. Wider stops in volatile markets, tighter stops in calm ones. The formula: stopLevel = strategy.position_avg_price - atrMultiplier * ta.atr(14). This reduces false exits from normal price noise.
▶Why does my stop loss not trigger in Pine Script backtesting?
I check three things. First, is strategy.exit() inside if strategy.position_size > 0? If not, it won't execute. Second, are you calling exit and entry in the same bar? Use process_orders_on_close=true. Third, plot your stop level on the chart. If it's above the current price for a long position, it won't trigger. I've made that mistake more times than I'd like to admit.
▶How should position sizing relate to stop loss size?
Position size multiplied by stop distance equals your dollar risk. $10,000 account, 1% risk per trade = $100 max loss. Stop at $2 from entry means buy 50 shares. Stop at $1 means buy 100 shares. In Pine Script I use default_qty_type=strategy.percent_of_equity with the stop distance as the sizing input. My rule is never risk more than 1-2% of total account per trade.



