TradingView Indicators & Pine Script v6

TradingView TP/SL Indicators: Lines, Simulated Exits, and Broker Orders

A TradingView TP/SL indicator draws take-profit and stop-loss levels around a chosen entry reference. Those lines are calculations, not working orders. A Pine Script strategy can simulate exits with strategy.exit(); actual broker brackets require a separate supported order workflow. Before using a script, check its entry reference, distance units, update rule, and whether a touch means an alert, a simulated fill, or a broker execution.

Build TP/SL Rules with AI

Choose between a chart indicator, a strategy, and broker brackets

Search TradingView Indicators for take profit stop loss or TP SL, then read the script description and source if available. There is no single TP/SL formula shared by every community script. A useful indicator identifies where its entry comes from and when it replaces or removes a bracket. TradingView documents strategy automation and broker bracket support separately; adding a strategy to a chart does not connect its orders to a brokerage account.

  • A webhook is a notification sent to an endpoint. A receiver must separately interpret it and submit an order; delivery or a chart alert is not proof of a broker fill.
  • For supported brokers, TradingView offers TP and SL controls on the chart. These order controls are separate from lines drawn by a Pine indicator.
ToolWhat it producesWhat to verify
IndicatorPlots, drawings, and configured alert events.Entry reference, frozen or moving levels, touch rule, and reset rule. No built-in Strategy Tester trades.
Pine strategyOrders and fills in the broker emulator, with a Strategy Tester report.Calculation timing, order units, costs, gaps, and historical fill assumptions.
Broker bracketsActual exit orders submitted through a supported broker workflow.Broker support, quantity, order status, cancellation linkage, and execution terms.

Define the entry reference and units before calculating levels

Let E be the chosen entry reference and D a positive price distance. For a long setup, SL = E - D and TP = E + R × D. For a short setup, reverse the signs. R is the target distance divided by the stop distance. Round order prices to the instrument tick size and reject zero or inverted distances.

  • Freeze the entry and ATR sample when the setup starts if the goal is a fixed bracket. Recalculating around each new close produces a moving reference.
  • For a strategy percentage exit based on the fill, use strategy.position_avg_price after it is available. With default calculations, waiting for it can delay bracket submission until the entry bar closes.
  • A fill recalculation can make the average price available earlier, but changes backtest behavior. calc_on_order_fills is not a guarantee of realistic historical execution.
InputConversion or ruleCommon mistake
PercentD = E × percent / 100. A 1% distance at E = 100 is 1 price unit.Treating a 1% price stop as 1% account risk.
TicksD = ticks × syminfo.mintick. With a 0.25 tick, 20 ticks span 5 price units.Using points, pips, and ticks interchangeably.
ATRD = ATR × multiplier, with ATR sampled at an explicitly chosen time.Recomputing ATR each bar while describing the stop as fixed.
Confirmed swingFor a long, D = E - (confirmed swing low - buffer). Require D > 0.Treating a rolling lowest low as a confirmed pivot, or ignoring pivot confirmation delay.

A complete TP/SL indicator with frozen levels

This example starts a hypothetical long setup at a confirmed 9/21 EMA crossover close and holds that reference fixed. Choose an ATR or percentage stop and a reward multiple. It ignores new signals while active, begins touch checks on the following bar, and ends the setup after either boundary is touched. If both are touched on one bar, the alert reports unknown order instead of choosing a winner.

  • ATR and moving averages are calculated on every bar. Only setup state and touch decisions are committed at bar close.
  • Touch alerts use the completed bar high and low. A wick touch remains a touch even if the close retreats; waiting for the close delays notification.
  • Add the script in Pine Editor, then create an alert using Any alert() function call. Alerts fire on realtime bars only; recreate them after relevant code or input changes.
  • The entry marker is a hypothetical reference. This indicator does not track broker positions or generate a performance report.
Pine Script v6: one active hypothetical long bracket, no broker orderspinescript
//@version=6
indicator("TP/SL reference levels", overlay = true)

string mode = input.string("ATR", "Stop method", options = ["ATR", "Percent"])
int atrLength = input.int(14, "ATR length", minval = 1)
float atrMultiple = input.float(1.5, "ATR multiple", minval = 0.1)
float stopPercent = input.float(1.0, "Stop distance (%)", minval = 0.01, maxval = 99)
float rewardMultiple = input.float(2.0, "Reward / risk", minval = 0.1)

float fast = ta.ema(close, 9)
float slow = ta.ema(close, 21)
float atrValue = ta.atr(atrLength)
bool entrySignal = ta.crossover(fast, slow)
var bool active = false
var float entry = na
var float stopLevel = na
var float targetLevel = na
var int entryBar = na
bool started = false
bool touchedStop = false
bool touchedTarget = false

if barstate.isconfirmed
    if active
        if bar_index > entryBar
            touchedStop := low <= stopLevel
            touchedTarget := high >= targetLevel
            if touchedStop or touchedTarget
                string message = touchedStop and touchedTarget ? "Both levels touched; order unknown" : touchedStop ? "SL level touched" : "TP level touched"
                alert(message, alert.freq_once_per_bar_close)
                active := false
    else
        entry := na
        stopLevel := na
        targetLevel := na
        float distance = mode == "ATR" ? atrValue * atrMultiple : close * stopPercent / 100
        if entrySignal and not na(distance) and distance >= syminfo.mintick
            float proposedStop = math.round_to_mintick(close - distance)
            float proposedTarget = math.round_to_mintick(close + distance * rewardMultiple)
            if proposedStop > 0 and proposedStop < close and proposedTarget > close
                entry := close
                stopLevel := proposedStop
                targetLevel := proposedTarget
                entryBar := bar_index
                active := true
                started := true

plot(entry, "Reference entry", color.blue, style = plot.style_linebr)
plot(stopLevel, "SL level", color.red, style = plot.style_linebr)
plot(targetLevel, "TP level", color.green, style = plot.style_linebr)
plotshape(started, "New reference", shape.triangleup, location.belowbar, color.blue, text = "REF", size = size.tiny)
plotshape(touchedStop, "SL touched", shape.xcross, location.belowbar, color.red, text = "SL", size = size.tiny)
plotshape(touchedTarget, "TP touched", shape.xcross, location.abovebar, color.green, text = "TP", size = size.tiny)

Use strategy.exit() with the correct units

For price-based exits, stop and limit accept absolute prices. For entry-relative exits, loss and profit accept tick distances. This example submits a tick-based bracket with the entry order, so it does not need to wait for the average fill price. The EMA signal is only a demonstration; the fixed tick inputs are not recommended trading settings.

  • Default market orders fill on the next available tick, usually the next bar open in a historical test. The signal close is not the fill price.
  • Commission is set to 0.1% and slippage to one tick as illustrative assumptions. Replace them with the costs relevant to the test. One unit may be unaffordable for some contracts.
  • These plots reflect position state when the script executes. An entry and exit completed within one bar may leave no visible bracket plot; inspect the trade list.
ParameterUnitMeaning
stop / limitAbsolute priceStop-loss / take-profit levels, such as 98 and 104.
loss / profitTicks from entryDistances, such as 20 and 40 ticks. Not percentages.
trail_price / trail_pointsAbsolute price / ticks from entryAlternative ways to define trailing-stop activation.
trail_offsetTicksDistance behind the favorable extreme after activation; also needs an activation parameter.
Pine Script v6: a simulated long entry with a fixed tick bracketpinescript
//@version=6
strategy("TP/SL tick bracket demo", overlay = true, pyramiding = 0,
     initial_capital = 100000, default_qty_type = strategy.fixed,
     default_qty_value = 1, margin_long = 100,
     commission_type = strategy.commission.percent, commission_value = 0.1,
     slippage = 1)

int stopTicks = input.int(20, "Stop distance (ticks)", minval = 1)
int targetTicks = input.int(40, "Target distance (ticks)", minval = 1)
float fast = ta.ema(close, 9)
float slow = ta.ema(close, 21)
bool longSignal = ta.crossover(fast, slow)

if longSignal and strategy.position_size == 0
    strategy.entry("Long", strategy.long)
    strategy.exit("Bracket", from_entry = "Long", loss = stopTicks, profit = targetTicks)

bool inLong = strategy.position_size > 0
float averageEntry = inLong ? strategy.position_avg_price : na
plot(averageEntry, "Simulated entry", color.blue, style = plot.style_linebr)
plot(inLong ? averageEntry - stopTicks * syminfo.mintick : na, "SL", color.red, style = plot.style_linebr)
plot(inLong ? averageEntry + targetTicks * syminfo.mintick : na, "TP", color.green, style = plot.style_linebr)

Specify trailing stops, partial exits, and fill assumptions

A fixed ATR bracket and a trailing stop are different rules. For a custom long trailing stop, store its previous value and allow only increases; a fresh entry-minus-ATR calculation can otherwise loosen it. Define activation, update timing, and reset behavior. A stop moved to the entry price can still produce a net loss after costs or an adverse fill.

  • Built-in trailing exits need trail_offset plus trail_price or trail_points. Converting an ATR price distance to ticks requires division by syminfo.mintick and an explicit rounding rule.
  • Separate strategy.exit calls reserve portions of a position. Give each partial exit an appropriate stop and quantity; do not assume a later call covers quantities already reserved by earlier calls.
  • A historical bar touching both boundaries does not reveal which came first. The emulator uses fill assumptions; Bar Magnifier can use lower-timeframe data where available, not a guarantee of live execution.
  • Price gaps can fill stops beyond their requested levels. A real limit order may remain unfilled because price touching the limit does not establish available liquidity.

Check planned risk separately from price distance

For a linear instrument, an estimate of planned cash risk is quantity × stop price distance × point value, before costs and any currency conversion. Position size, contract terms, and account currency matter. A 1% price stop does not mean a 1% account loss, and a stop order does not guarantee a maximum loss.

  • A 2:1 target-to-stop distance has a theoretical break-even win rate of one third only if every win is exactly 2R, every loss exactly 1R, and costs are zero. Realized trade outcomes determine expectancy.
  • Review the symbol tick size, entry and exit timestamps, gap fills, same-bar exits, and costs in the trade list. Compare standard candles with any synthetic chart before trusting results.
  • Check the indicator on bars that touch only TP, only SL, and both. Confirm that new signals do not overwrite an active setup. These are reproducible inspection steps, not claimed test results.
  • Keep a separate test period when comparing stop parameters. No performance study or live execution test is provided here.
Where Pineify fits

Pine Script AI Coding Agent

Describe the entry reference, stop units, target formula, and reset rule to draft a TP/SL indicator or strategy. Review the generated source and test its order behavior in TradingView.

Also useful: Visual Pine Script Editor. Use the visual editor to configure supported indicator and strategy rules, then inspect the generated Pine Script.

Build TP/SL Rules with AI

Frequently asked questions

Educational examples, not investment advice. Code validation does not establish profitability or live execution reliability. Actual losses can exceed planned risk because of gaps, costs, liquidity, or execution failures.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.