Tutorial

Pine Script Partial Take Profit: Scale Out Positions

Close part of a position at a first target and let the rest run. Build a two-target strategy.exit scale-out in Pine Script v6, with a break-even stop.

•12 min read

You have a strategy that enters well enough, and a single take profit that feels wrong. Set it close and you cut every winner short. Set it far and you watch trades reach halfway, turn around, and hit the stop. A partial take profit is the usual answer: close part of the position at a first target, leave the rest to run to a second one. In Pine Script that takes two strategy.exit calls instead of one, and a few details decide whether it behaves the way you expect.

This guide builds a scale-out from scratch in Pine Script v6. You will see how qty_percent works, why the two exits need different ids, the trap that makes a second exit close your whole position by accident, how to move the stop to the entry price after the first target fills, and how to read the trade list to confirm what happened. The code is a coding exercise about order handling, not a claim about what any exit rule earns.

How a scale-out works in Pine Script

A normal exit has one order: strategy.exit("Exit", from_entry="Long", limit=target, stop=stopLoss) closes the whole entry when price touches either level. A scale-out splits that into several exit orders attached to the same entry, each responsible for a slice of the position. The first slice has a nearer target. The last slice has a farther one. Every slice usually shares the same protective stop, so a losing trade still ends in one stop-out for the full size.

Pine does this with the qty_percent argument of strategy.exit. It takes a number from 0 to 100 and sizes the exit as that percentage of the entry's position. With qty_percent = 50, the order closes half of what the entry opened. The second call takes the other 50. Together they add up to the whole position, so there is nothing left over when the trade is finished.

The two calls must have different exit ids, for example "TP1" and "TP2". The id is the name of the exit order. If you reuse the same id, the later call simply replaces the earlier order and you are back to one exit. Different ids are what let two orders for the same entry coexist.

There is also a quantity form, qty, that takes an absolute amount in contracts, lots, or units. It is exact but ties your exit to a hardcoded size, which breaks the moment your position sizing changes. Percent of the position keeps working however large the entry was, which is why most scale-out code uses qty_percent.

The levels: choosing targets from ATR

You need three prices: a stop, a first target, and a second target. Fixed percentages work, but a distance based on volatility adapts when the market gets quieter or wilder. The ATR is the standard measure, and the ATR calculator lets you check the number by hand.

A common shape is a stop at 1.5 ATR below the entry, a first target at 1.5 ATR above it, and a second target at 3 ATR above it. The first target then pays about what the stop risks, and the second pays about twice that. These multipliers are inputs, not recommendations. The point of making them inputs is that you can test other values and see how the trade list changes.

One decision matters more than it looks: when do you compute the levels? An ATR value changes on every bar. If you recompute the stop and targets on every bar from the current ATR, they drift while the trade is open, and the exit orders move with them. Most traders want levels fixed at entry. The clean way is to store them in var variables the first bar the position exists, then leave them alone. The var and varip article covers why var keeps a value across bars.

The entry price itself is not known when the signal fires. A market order from strategy.entry fills at the next bar's open, so close on the signal bar is only a guess. Once the position is open, strategy.position_avg_price holds the real fill price, and that is what the levels should hang from.

A complete two-target strategy

This script enters long when a fast EMA crosses above a slow one, then scales out at two ATR-based targets with a shared stop. The entry rule is deliberately plain. It is a placeholder so the exit logic is the only thing under study.

pine
//@version=6
strategy("Scale-Out Two Targets", overlay = true,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 50)

fastLen   = input.int(20, "Fast EMA length", minval = 1)
slowLen   = input.int(50, "Slow EMA length", minval = 2)
atrLen    = input.int(14, "ATR length", minval = 1)
stopMult  = input.float(1.5, "Stop distance (ATR)", minval = 0.1, step = 0.1)
tp1Mult   = input.float(1.5, "Target 1 distance (ATR)", minval = 0.1, step = 0.1)
tp2Mult   = input.float(3.0, "Target 2 distance (ATR)", minval = 0.1, step = 0.1)
tp1Pct    = input.float(50, "Percent closed at target 1", minval = 1, maxval = 99)

fastEma = ta.ema(close, fastLen)
slowEma = ta.ema(close, slowLen)
atrVal  = ta.atr(atrLen)

longSignal = ta.crossover(fastEma, slowEma)

var float stopPx    = na
var float tp1Px     = na
var float tp2Px     = na
var float startQty  = na

if strategy.position_size == 0
    stopPx   := na
    tp1Px    := na
    tp2Px    := na
    startQty := na
else if na(stopPx)
    entryPx  = strategy.position_avg_price
    stopPx   := entryPx - atrVal * stopMult
    tp1Px    := entryPx + atrVal * tp1Mult
    tp2Px    := entryPx + atrVal * tp2Mult
    startQty := strategy.position_size

if longSignal and strategy.position_size == 0
    strategy.entry("Long", strategy.long)

tp1Filled = strategy.position_size > 0 and strategy.position_size < startQty

if strategy.position_size > 0
    if not tp1Filled
        strategy.exit("TP1", from_entry = "Long", qty_percent = tp1Pct,
             limit = tp1Px, stop = stopPx)
    strategy.exit("TP2", from_entry = "Long", qty_percent = 100 - tp1Pct,
         limit = tp2Px, stop = stopPx)

plot(fastEma, "Fast EMA", color = color.new(color.teal, 0))
plot(slowEma, "Slow EMA", color = color.new(color.orange, 0))
plot(stopPx, "Stop", color = color.red, style = plot.style_linebr)
plot(tp1Px, "Target 1", color = color.green, style = plot.style_linebr)
plot(tp2Px, "Target 2", color = color.lime, style = plot.style_linebr)

Walk through it in the order the bar runs. While flat, the level variables are cleared. On the first bar the position exists, na(stopPx) is still true, so the script reads the real fill price and sets all three levels plus startQty, the size the position opened with. After that the else if branch never fires again, so the levels stay put.

The exits are called on every bar while the position is open. Calling strategy.exit again with the same id and unchanged levels just keeps the same order, and it lets the script adjust a level later, as the next section does. The orders stay active until they fill or the position closes. Both calls share stopPx, so if price falls to the stop before the first target, both slices close there and the trade ends as one loss. If price rises to target 1, the "TP1" order closes its share at the limit price and the "TP2" order carries on with the remainder.

The trap: re-issuing the first exit after it fills

Look at the if not tp1Filled guard. It is the line people leave out, and the result confuses them for an hour.

After "TP1" fills, the position is smaller, but the script still runs on the next bar with strategy.position_size > 0. Without the guard it would call strategy.exit("TP1", ...) again. The order that filled is gone, so this call creates a fresh order with the same id for the same entry. Its limit is the first target, which price has already passed. A limit order to sell at a price below the current market fills straight away at the next bar's open. The script has just closed another slice of the position without anyone asking, and in the worst case the whole thing is gone before the second target is ever in play.

The tell is in the trade list. You will see "TP1" appear twice for one entry, or a "TP2" exit at a price far below its target. The cure is to know when the first slice has filled and stop placing its exit. Here that is tp1Filled, true when the open size is below the size the position started with. You could track it with a var bool instead; the size comparison just avoids a second state variable.

If exits seem to do nothing at all, the cause is usually elsewhere, for example a level that is na or on the wrong side of the entry. The guide on strategies that never take trades lists the common causes of missing orders.

Move the stop to break-even after target 1

Once half the position is banked, many traders want the remaining half to risk nothing. That means raising the stop to the entry price after target 1 fills. Since you already detect the fill, the change is small: the "TP2" exit chooses its stop based on tp1Filled.

pine
//@version=6
strategy("Scale-Out With Break-Even", overlay = true,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 50)

fastLen   = input.int(20, "Fast EMA length", minval = 1)
slowLen   = input.int(50, "Slow EMA length", minval = 2)
atrLen    = input.int(14, "ATR length", minval = 1)
stopMult  = input.float(1.5, "Stop distance (ATR)", minval = 0.1, step = 0.1)
tp1Mult   = input.float(1.5, "Target 1 distance (ATR)", minval = 0.1, step = 0.1)
tp2Mult   = input.float(3.0, "Target 2 distance (ATR)", minval = 0.1, step = 0.1)
tp1Pct    = input.float(50, "Percent closed at target 1", minval = 1, maxval = 99)
useBE     = input.bool(true, "Move stop to entry after target 1")

fastEma = ta.ema(close, fastLen)
slowEma = ta.ema(close, slowLen)
atrVal  = ta.atr(atrLen)

longSignal = ta.crossover(fastEma, slowEma)

var float entryPx  = na
var float stopPx   = na
var float tp1Px    = na
var float tp2Px    = na
var float startQty = na

if strategy.position_size == 0
    entryPx  := na
    stopPx   := na
    tp1Px    := na
    tp2Px    := na
    startQty := na
else if na(stopPx)
    entryPx  := strategy.position_avg_price
    stopPx   := entryPx - atrVal * stopMult
    tp1Px    := entryPx + atrVal * tp1Mult
    tp2Px    := entryPx + atrVal * tp2Mult
    startQty := strategy.position_size

if longSignal and strategy.position_size == 0
    strategy.entry("Long", strategy.long)

tp1Filled = strategy.position_size > 0 and strategy.position_size < startQty
runnerStop = useBE and tp1Filled ? entryPx : stopPx

if strategy.position_size > 0
    if not tp1Filled
        strategy.exit("TP1", from_entry = "Long", qty_percent = tp1Pct,
             limit = tp1Px, stop = stopPx)
    strategy.exit("TP2", from_entry = "Long", qty_percent = 100 - tp1Pct,
         limit = tp2Px, stop = runnerStop)

plot(runnerStop, "Active stop", color = color.red, style = plot.style_linebr)
plot(tp1Px, "Target 1", color = color.green, style = plot.style_linebr)
plot(tp2Px, "Target 2", color = color.lime, style = plot.style_linebr)

After target 1 fills, the active stop jumps from the ATR-based level up to the entry price. If price then falls back, the remaining slice exits at the entry price, or near it. Near it, not exactly at it, because a stop order that price gaps through fills at the next available price, and costs apply on every fill. The break-even stop guide goes through those edge cases, and the trailing stop guide shows the alternative of letting the stop follow price instead of jumping once.

Notice what the break-even toggle does to a trade's outcome range. A trade that reaches target 1 and then reverses can no longer lose money on its runner, but it also gives up trades that would have dipped to the entry, then continued to target 2. Moving the stop early trades some winners for lower variance. Whether that is the right trade-off depends on your instrument and timeframe, which is exactly why it is a toggle you can switch while you compare the two runs.

Checking that it did what you intended

A scale-out has more moving parts than a single exit, so verify it before you trust any summary number. Open the List of Trades tab in TradingView's Strategy Tester. Every entry should be followed by exits in this shape: either one stop-out covering the full size, or a "TP1" row for the first slice followed by a "TP2" row, or a stop row, for the rest. A single entry with two "TP1" rows, or exit sizes that do not add up to the entry size, means the guard from the previous section is missing or qty_percent values do not sum to 100.

Then look at prices. A target fill should match your limit within the bar's range. A stop fill below its level means the bar gapped through it. Plot the stop and target levels as in the scripts above so you can compare each trade to the lines drawn on the chart.

The order of fills inside one bar is also worth understanding. When a single candle's range covers both a target and the stop, TradingView has to guess which was touched first, because it only has the open, high, low, and close. By default it assumes a path through the bar. The Bar Magnifier uses lower-timeframe data to resolve the order more precisely, and it matters most for tight scale-outs on wide candles. Related fill-timing settings are covered in the process_orders_on_close article.

Finally, remember that tighter targets mean more trades closing in a single bar and more fills that costs apply to. Each slice is a separate fill, so a scale-out pays commission and slippage on two exits instead of one. If your results change a lot when you add commission and slippage, that is information about the rule, not a bug in the code.

Where scale-outs go wrong

A few mistakes come up often enough to name. The first is percentages that do not sum to 100. With 50 and 40, ten percent of the position is never covered by a target and only the stop can close it. The script above derives the second slice as 100 - tp1Pct so the two can never drift apart.

The second is tiny slices. If your position is a handful of units and a market has a minimum order size, a 25 percent slice may round to zero or to an amount the broker emulator cannot fill. Check the sizes in the trade list. The position size guide shows how to size the entry so the slices stay sensible.

The third is reading a scale-out as a free improvement. Splitting a position changes the shape of outcomes: smaller average winner on the first slice, a runner that sometimes gives back its gains, fewer trades that end at a loss from a full-size position. It does not by itself make a rule work, and a backtest can fit these levels to the past very closely. Treat any change in the summary numbers as a prompt to look at the drawdown and the trade list, not as a conclusion.

The fourth is a short side that mirrors the long incorrectly. For shorts, the stop is above the entry, the targets are below it, and the sign of every distance flips. Using strategy.short with the same arithmetic reversed, and a separate from_entry = "Short" on each exit, keeps the two sides from interfering.

Changing the scale-out without rewriting the strategy

The code above is short enough to edit by hand. Real strategies are not. Once yours has several filters, session rules, and an existing exit, bolting a second target onto it means touching code you wrote weeks ago, and it is easy to break the entry while editing the exit.

In PineScripter you can describe the change in plain English, for example "close 40 percent at 1.5 ATR, move the stop to entry, and leave the rest for 3 ATR", and the AI edits only the lines that change on top of the script you already have. The Code Changes view shows each edit line by line, so you can see that the entry logic was left alone. Every script is checked for compile errors the way TradingView checks it before you paste it in, and the chart runs your script on real crypto market data so you can look at the plotted stop and target lines. Replay steps through the run one bar at a time, which is a good way to watch the moment the first target fills and the stop moves. For strategy results themselves, use TradingView's Strategy Tester. See pricing for plans.

PineScripter is a coding tool, not a financial advisor. The scripts in this article are examples of order handling, not trading advice, and nothing here predicts or promises any result. Past performance of any rule does not indicate future results. Test any script on your own data and understand it before relying on it.

Frequently asked questions

How do I take partial profit in Pine Script?

Place two strategy.exit calls for the same entry with different ids, each with its own qty_percent and limit price. For example, 50 percent at a first target and the other 50 percent at a second, both sharing one stop.

What does qty_percent do in strategy.exit?

It sizes the exit order as a percentage, from 0 to 100, of the entry's position. Using qty_percent instead of an absolute qty keeps the exit correct whatever size the entry opened with.

Why does my second take profit close the whole position?

Usually the first exit is called again after it fills. Its limit is already behind price, so the new order fills at once. Guard the first exit so it is only placed until its slice has filled.

How do I move the stop to break-even after the first target?

Detect that the open size is below the size the position started with, then pass the entry price as the stop of the remaining exit. The second script in this guide does exactly that.

Do partial exits pay commission twice?

Each slice is a separate fill, so commission and slippage settings apply to every exit. Check the result with realistic costs set in the strategy declaration.

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.