You write a strategy with a clean entry, add strategy.exit underneath it, and the Strategy Tester shows trades that close at prices you never asked for, or never close at all, or close on the bar after you expected. Nothing errors. The exit just does not do what the line reads like it should do. Most of that confusion comes from a handful of rules about how strategy.exit places orders, and once you know them, a single call can handle a stop, a target and a trailing stop at the same time.
This guide covers what the function really does, which arguments take ticks and which take prices, how the trailing arguments work, and why an exit that is placed once is not the same as one that is kept up to date. Every script below is complete Pine Script v6 and shows the level it is using on the chart, so you can check the behavior yourself instead of trusting the description.
What strategy.exit actually does
strategy.exit does not close anything on its own. It places an exit order that waits. If you call it with a stop price and a limit price, you have placed two linked orders: a stop that sits below a long position and a limit that sits above it. Whichever one the market reaches first fills, and the other is cancelled. TradingView describes these as orders in an OCA group, which is the same idea as a bracket order at a broker.
The orders are tied to an entry through the from_entry argument, which takes the id of the entry you gave to strategy.entry. If you leave from_entry out, the exit applies to every open entry in the position, which is convenient for a simple script and ambiguous the moment you add a second entry. Naming the entry is the safer habit, and it makes the script readable to someone who did not write it.
The first argument is the exit's own id. It matters more than it looks. If you call strategy.exit again with the same id, the existing order is modified, not duplicated. That is the mechanism behind every trailing and dynamic exit in Pine Script, and we will come back to it.
There is also a difference between strategy.exit and strategy.close. The close functions send a market order that fills at the next opportunity. strategy.exit sends orders that fill only when price reaches the level. If you want a rule such as "get out when the fast average crosses back under the slow one", that is a market close. If you want "get out at this price or that price", that is strategy.exit.
Ticks or prices: the pairs that trip people up
The function has two ways to describe the same level, and mixing them up is the most common source of a stop at the wrong place.
The price arguments are stop and limit. You pass an actual price, such as entryPrice - 2 * atr. The distance arguments are loss and profit. You pass a distance measured in ticks from the entry price, where a tick is the instrument's minimum price move, available as syminfo.mintick. On an instrument with a tick of 0.01, loss = 400 means a stop 4.00 away from the entry.
If you give both members of a pair, the price version wins. Passing stop and loss together means loss is ignored, and the same goes for limit and profit. That is useful to know when you are debugging, because a leftover loss argument will not do anything, and you may waste an hour wondering why changing it has no effect.
The tick unit catches people who think in price terms. If you want a stop that is 1.5 times the average true range away, you either compute the price yourself, or convert the distance with atr / syminfo.mintick. We use the price form in the examples because it reads closer to how you reason about a chart, and because it is easy to plot.
One more rule: the level has to be on the correct side of the market. A long stop must be below the current price and a long limit above it. If you place a long stop above where price already is, the order is immediately marketable and fills on the next bar's open, so the trade appears to close for no reason.
A bracket exit sized by volatility
Here is the smallest useful version, a moving average cross entry with a stop and a target a fixed multiple of the average true range away. For background on that indicator, the ATR guide covers how it is calculated.
//@version=6
strategy("ATR bracket exit", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)
atrLen = input.int(14, "ATR length", minval = 1)
stopMult = input.float(1.5, "Stop distance in ATRs", minval = 0.1, step = 0.1)
targetMult = input.float(3.0, "Target distance in ATRs", minval = 0.1, step = 0.1)
fast = ta.ema(close, 20)
slow = ta.ema(close, 50)
atr = ta.atr(atrLen)
var float stopPx = na
var float targetPx = na
longTrigger = ta.crossover(fast, slow) and strategy.position_size == 0
if longTrigger
stopPx := close - stopMult * atr
targetPx := close + targetMult * atr
strategy.entry("Long", strategy.long)
if longTrigger or strategy.position_size > 0
strategy.exit("Exit Long", from_entry = "Long", stop = stopPx, limit = targetPx)
plot(strategy.position_size > 0 ? stopPx : na, "Stop", color.red, style = plot.style_linebr)
plot(strategy.position_size > 0 ? targetPx : na, "Target", color.green, style = plot.style_linebr)Three details in that script are doing real work. The levels are saved in var variables when the trigger happens, so they stay put for the whole trade instead of drifting every time the average true range changes. The exit is called on the trigger bar as well as on every bar while the position is open. And the two plot lines draw the stop and target only while a position exists, so you can see on the chart exactly where the orders sit.
The trigger-bar call deserves an explanation, because it is the most commonly missed rule. A market entry placed on the close of bar N fills at the open of bar N+1. At the close of bar N the position size is still zero. If your exit sits behind if strategy.position_size > 0, it is first placed at the close of bar N+1, which means the fill bar had no stop or target working at all. Placing the exit on the trigger bar means the orders are already waiting when the entry fills. If you want the longer treatment of how fills are timed, the process_orders_on_close guide walks through the alternative.
Why calling it on every bar matters
When you place an exit once and never touch it, it keeps the same levels until it fills. That is fine for a fixed bracket. It is wrong the moment you want the levels to change, because only a new call with the same id can change them.
This is also why the same script behaves differently if you wrap the call in a condition that is true for only one bar. A common mistake is writing if ta.crossover(fast, slow) and putting both the entry and the exit inside it. That works for a fixed bracket, but if you later add a break-even move or a trailing level and keep the call inside the same block, the update never runs.
The reverse mistake is calling strategy.exit with a moving level while flat. If there is no open position and no pending entry, the call has nothing to attach to and does nothing, so it is harmless, but it makes the script harder to read. The pattern in the example, trigger bar or in position, keeps the intent obvious.
If your strategy sits flat and you cannot tell why, the strategy not taking trades checklist covers the entry side of the same problem.
Trailing stops: trail_points and trail_offset
A trailing stop in strategy.exit needs two numbers, and both are measured in ticks. trail_points is how far in profit the trade has to get before the trailing stop switches on. trail_offset is how far behind the best price the stop then follows. Once the trade has moved trail_points ticks in your favor, the stop sits trail_offset ticks behind the highest price reached for a long, and it only ever moves in your favor.
There is also trail_price, which sets the activation as a price level instead of a distance. If you pass both trail_price and trail_points, the price version is used.
The effect of the two numbers is easy to see if you picture a 2,000 tick activation and a 1,000 tick offset. Until price is 2,000 ticks above the entry, the trailing stop does nothing and only your regular stop protects the trade. After that, the stop is placed 1,000 ticks behind the highest price, so it starts out 1,000 ticks above the entry and climbs from there. That is why a trailing stop with an activation larger than its offset locks in a gain the moment it switches on, whereas an offset larger than the activation can start out below the entry.
Here is the same strategy with a trailing stop added, still sized from the average true range at the trigger bar.
//@version=6
strategy("ATR trailing exit", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)
atrLen = input.int(14, "ATR length", minval = 1)
stopMult = input.float(2.0, "Initial stop in ATRs", minval = 0.1, step = 0.1)
startMult = input.float(2.0, "Trail starts after ATRs of gain", minval = 0.1, step = 0.1)
offsetMult = input.float(1.0, "Trail distance in ATRs", minval = 0.1, step = 0.1)
fast = ta.ema(close, 20)
slow = ta.ema(close, 50)
atr = ta.atr(atrLen)
var float stopPx = na
var float trailStart = na
var float trailDist = na
longTrigger = ta.crossover(fast, slow) and strategy.position_size == 0
if longTrigger
stopPx := close - stopMult * atr
trailStart := startMult * atr / syminfo.mintick
trailDist := offsetMult * atr / syminfo.mintick
strategy.entry("Long", strategy.long)
if longTrigger or strategy.position_size > 0
strategy.exit("Trail Long", from_entry = "Long", stop = stopPx, trail_points = trailStart, trail_offset = trailDist)
plot(strategy.position_size > 0 ? stopPx : na, "Initial stop", color.red, style = plot.style_linebr)The initial stop and the trailing stop work side by side. Before the trail activates, stop is the only protection. After it activates, whichever of the two is closer to the market is the one that can fill. Because the trail is held inside the order, you do not see it as a plotted line unless you reconstruct it yourself. The trailing stop guide shows how to calculate and plot a trailing level manually, which is worth doing once so you know what the built-in version is computing.
Same-bar conflicts and what the tester assumes
Because a stop and a limit are both live at once, a wide bar can touch both. The Strategy Tester only has the open, high, low and close of that bar, so it cannot know which level was reached first. It applies an assumption about the likely price path, and with a tight bracket on a volatile bar the assumption can decide whether a trade counts as a loser or a winner.
There are two ways to deal with that. The first is to be aware of it: if an exit result looks odd on one specific bar, look at that bar's range against both levels. The second is the bar magnifier, which tests the bar against smaller timeframe data and so resolves most of those cases. The bar magnifier guide explains what it changes.
A related point is the fill price. Stop orders fill at the stop price unless the bar opens beyond it, in which case they fill at the open. A gap through your stop gives a worse fill than the level you coded. That is realistic behavior and it is not a bug in the script, so do not "fix" it by adjusting the stop.
Exits that depend on more than price
A single strategy.exit cannot express every rule. A time-based exit, a signal-based exit, and an exit when a higher timeframe flips are all conditions that need a market order, which means strategy.close or strategy.close_all under an if. You can use both together: leave the bracket in place as protection and add a conditional close on top. When the close fires, the pending exit orders for that entry are cancelled along with the position.
For scaling out, qty_percent lets one exit close only part of the entry. You can place two exits with different ids against the same entry, one that takes half off at a nearer target and one that holds the rest. The partial take profit guide builds that out in full, and the break-even stop guide shows how to move the stop to the entry price after the trade has moved enough, which relies on exactly the re-call-with-the-same-id behavior described above.
For the broader picture of sizing and placing stops, see the stop loss and take profit guide.
A debugging checklist for exits that misbehave
When an exit does something unexpected, work through these in order, because they account for almost every case.
First, check the arguments. Are you passing ticks where you meant a price, or the reverse? Is a leftover loss or profit being silently overridden by a stop or limit? Second, check the timing. Is the exit being called on the trigger bar, or only once the position exists? Third, check the side. Is a long stop above the market, or a short limit below it? Fourth, check the id. Two exits that share an id replace each other, and two exits with different ids against the same entry can both be active, which is occasionally what you want and often not. Fifth, check what else is closing the trade. A reversing entry in the opposite direction, a strategy.close call, or a margin call can all end a position before your exit reaches its level.
Plotting the levels, as in the scripts above, answers the first three questions at a glance. If the plotted stop is where you expected and the trade still closed somewhere else, the cause is one of the last two.
Check your exits inside PineScripter
Exit bugs are hard to see in a table of trades and easy to see on a chart. If you paste a strategy into PineScripter, you can run it on real crypto market data and see the plotted stop and target levels before taking it anywhere else. Bar replay then steps through the run one bar at a time, so you can stop on the bar where the exit should have triggered and ask the AI why it did or did not.
If the exit logic is wrong, the AI code editor edits only the lines that need to change, so adding a trailing stop or moving the exit call to the trigger bar does not rewrite the entry logic you already trust. PineScripter does not simulate trades or report returns, so for the final numbers use TradingView's Strategy Tester, which is where a script like the ones above ends up anyway.
Putting it together
strategy.exit is a small function with a few strict rules. It places waiting orders, not market closes. Prices and tick distances are different arguments, and the price version wins when you give both. The call has to be made on the trigger bar so that the orders exist when the entry fills, and it has to be repeated on later bars if the levels are meant to move. A trailing stop needs both an activation distance and a follow distance. Plot the levels while you build, and most exit problems become visible in seconds.
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.
Frequently asked questions
What is the difference between strategy.exit and strategy.close in Pine Script?
strategy.close sends a market order that fills at the next opportunity. strategy.exit places waiting stop, limit or trailing orders that fill only when price reaches their levels.
Do loss and profit use ticks or prices in strategy.exit?
Ticks. loss and profit are distances from the entry price measured in ticks (syminfo.mintick). The price arguments are stop and limit, and if you pass both of a pair, the price version is used.
Why does my strategy.exit not apply on the first bar of a trade?
If the call sits behind strategy.position_size > 0, it is first placed after the entry fills, so the fill bar has no exit working. Call it on the trigger bar as well as while in position.
How do I make a trailing stop with strategy.exit?
Pass trail_points, the gain in ticks at which the trail switches on, and trail_offset, the distance in ticks the stop stays behind the best price. trail_price sets the activation as a price instead.
How do I change a stop after the trade is open?
Call strategy.exit again with the same id and the new level on each bar. Calling with an existing id modifies the order instead of adding a second one.
Describe your indicator in plain English and get Pine Script that compiles →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.