TradingView Risk Management: Stop Loss Types in Pine Script
TradingView Risk Management: Stop Loss Types in Pine Script

TradingView Risk Management: Stop Loss Types in Pine Script

Introduction

TradingView risk management is one of the most important skills for traders who want to protect their capital and trade consistently. By mastering stop loss types in Pine Script, you can limit risk, size your positions properly, and execute with confidence. In this guide, you’ll learn all major stop loss methods—static, ATR, trailing, structural, and time-based—along with risk-based position sizing and a composite strategy you can apply in TradingView.

TradingView executes orders with strategy.entry() and manages exits with strategy.exit(). Understanding how these functions work is critical before using them in live testing. Each example below is copy-paste ready.

Static Percent Stop Loss

This is the simplest type of stop loss where the stop is placed at a fixed percentage below the entry price.

//@version=5
strategy("Static Percent Stop Example", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

risk_pct = input.float(2.0, "Static Stop Loss (%)", step=0.1) / 100
take_pct = input.float(4.0, "Take Profit (%)", step=0.1) / 100

longSignal = ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
if (longSignal)
    strategy.entry("LongStatic", strategy.long)

if strategy.position_size > 0
    entry_price = strategy.position_avg_price
    stop_price  = entry_price * (1 - risk_pct)
    limit_price = entry_price * (1 + take_pct)
    strategy.exit("ExitStatic", from_entry="LongStatic", stop=stop_price, limit=limit_price)

Use this when you want a predictable and simple stop. Be aware it does not adapt to volatility.

Structural Stop Loss

This stop is placed just below the most recent swing low or above the most recent swing high. It aligns the stop with market structure.

//@version=5
strategy("Structural Stop Example", overlay=true)

swing_lookback = input.int(20, "Swing Lookback")
buffer = input.float(0.0, "Buffer", step=0.1)

longSignal = ta.crossover(ta.sma(close, 10), ta.sma(close, 40))
if (longSignal)
    strategy.entry("LongSwing", strategy.long)

swingLow = ta.lowest(low, swing_lookback)

if strategy.position_size > 0
    stop_price = swingLow - buffer
    strategy.exit("ExitSwing", from_entry="LongSwing", stop=stop_price)
    plot(strategy.position_size>0 ? stop_price : na, title="Swing Stop", style=plot.style_linebr)

Choose the lookback carefully based on timeframe and trading style.

ATR Based Stop Loss

The Average True Range measures volatility and can be used to set stops that adjust dynamically.

//@version=5
strategy("ATR Stop Example", overlay=true)

atrLen = input.int(14, "ATR Length")
atrMult = input.float(1.5, "ATR Multiplier")
takeATRmult = input.float(3.0, "Take Profit ATR Multiplier")

atr = ta.atr(atrLen)

longSignal = ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
if (longSignal)
    strategy.entry("LongATR", strategy.long)

if strategy.position_size > 0
    stop_price = strategy.position_avg_price - atr * atrMult
    limit_price = strategy.position_avg_price + atr * takeATRmult
    strategy.exit("ExitATR", from_entry="LongATR", stop=stop_price, limit=limit_price)
    plot(strategy.position_size > 0 ? stop_price : na, title="ATR Stop")

ATR stops are robust because they move with market conditions.

Trailing Stop Loss

A trailing stop moves up as price moves in your favor. It never moves down.

//@version=5
strategy("Trailing Stop Example", overlay=true)

trail_offset_pct = input.float(2.0, "Trailing Stop Offset (%)", step=0.1) / 100

if ta.crossover(ta.sma(close,14), ta.sma(close,50))
    strategy.entry("LongTrail", strategy.long)

if strategy.position_size > 0
    trail_offset = strategy.position_avg_price * trail_offset_pct
    strategy.exit("ExitTrail", from_entry="LongTrail", trail_offset = trail_offset)

This is effective for capturing extended trends.

ATR Based Trailing Stop

This combines ATR volatility adjustment with trailing functionality.

//@version=5
strategy("ATR Trailing Stop", overlay=true)

atrLen = input.int(14, "ATR Length")
atrTrailMult = input.float(1.0, "ATR Trail Multiplier")
atr = ta.atr(atrLen)

if ta.crossover(ta.sma(close,10), ta.sma(close,30))
    strategy.entry("LongATRTrail", strategy.long)

if strategy.position_size > 0
    trail_offset = atr * atrTrailMult
    strategy.exit("ExitATRTrail", from_entry="LongATRTrail", trail_offset=trail_offset)
    plot(strategy.position_size>0 ? strategy.position_avg_price - trail_offset : na, "ATR Trail Level")

This keeps the stop wide in volatile periods and tight in calmer ones.

Time Based Stop

You can also exit based on time held in a trade.

//@version=5
strategy("Time Stop Example", overlay=true)

maxBarsHold = input.int(48, "Max Bars to Hold")

if ta.crossover(ta.sma(close,9), ta.sma(close,21))
    strategy.entry("LongTime", strategy.long)

var int entry_bar_index = na
if strategy.opentrades == 0
    entry_bar_index := na

if strategy.opentrades > 0 and na(entry_bar_index)
    entry_bar_index := bar_index

bars_held = strategy.opentrades > 0 ? (bar_index - entry_bar_index) : 0
if strategy.position_size > 0 and bars_held >= maxBarsHold
    strategy.close("LongTime")

Time stops are useful if your edge works only within certain holding periods.

Position Sizing by Risk Percentage

Correct position sizing ensures each trade risks only a set portion of account equity.

//@version=5
strategy("Position Sizing Example", overlay=true, default_qty_type=strategy.fixed)

account_risk_pct = input.float(1.0, "Risk per Trade (%)", step=0.1) / 100
fixed_entry = input.float(na, "Demo entry price", step=0.01)
fixed_stop = input.float(na, "Demo stop price", step=0.01)

entry_price = na(fixed_entry) ? close : fixed_entry
stop_price  = na(fixed_stop) ? entry_price * (1 - 0.01) : fixed_stop

equity = strategy.equity
risk_amount = equity * account_risk_pct
risk_per_unit = math.abs(entry_price - stop_price)
position_size = risk_per_unit > 0 ? risk_amount / risk_per_unit : 0

qty = math.max(0, math.round(position_size))
if ta.crossover(ta.sma(close,8), ta.sma(close,21))
    strategy.entry("SizedLong", strategy.long, qty = qty)

if strategy.position_size > 0
    strategy.exit("ExitSized", from_entry="SizedLong", stop=stop_price)

Adjustments may be needed for futures and forex where contract sizes differ.

Composite Strategy Example

This lets you choose which stop type to apply from the settings panel.

//@version=5
strategy("Composite Stops Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=5)

maFast = input.int(12, "Fast MA")
maSlow = input.int(26, "Slow MA")

whichStop = input.string(title="Stop Type", defval="ATR", options=["Static %","ATR","Swing","Trailing"])
staticPct = input.float(2.0, "Static Stop (%)", step=0.1) / 100
atrLen = input.int(14, "ATR Length")
atrMult = input.float(1.5, "ATR Multiplier")
swingLook = input.int(20, "Swing Lookback")
trailOffsetPct = input.float(2.0, "Trailing Offset (%)", step=0.1) / 100

longEntry = ta.crossover(ta.sma(close, maFast), ta.sma(close, maSlow))
if longEntry
    strategy.entry("CompositeLong", strategy.long)

var float chosen_stop = na
if strategy.position_size > 0
    entry_price = strategy.position_avg_price
    if whichStop == "Static %"
        chosen_stop := entry_price * (1 - staticPct)
    else if whichStop == "ATR"
        chosen_stop := entry_price - ta.atr(atrLen) * atrMult
    else if whichStop == "Swing"
        chosen_stop := ta.lowest(low, swingLook) - syminfo.mintick
    else
        chosen_stop := na

    if whichStop == "Trailing"
        trail_offset = entry_price * trailOffsetPct
        strategy.exit("ExitCompositeTrail", from_entry="CompositeLong", trail_offset = trail_offset)
    else
        strategy.exit("ExitComposite", from_entry="CompositeLong", stop = chosen_stop)

plot(strategy.position_size > 0 and not na(chosen_stop) ? chosen_stop : na, title="Chosen Stop")

This is a flexible way to test different stop methodologies with the same entry logic.

Best Practices

  1. Always backtest across multiple instruments and timeframes.
  2. Include slippage and commission in your strategy settings.
  3. Be aware of gaps and overnight risks.
  4. For futures and forex, confirm the contract multiplier and tick value before applying risk based sizing.
  5. Use a combination of stop types when needed, for example a structural stop plus an ATR trailing stop.

Conclusion

This guide presented practical examples for all major types of stop loss and risk management in Pine Script version 5. You now have a ready to use reference for static stops, structural stops, ATR based stops, trailing stops, time based exits, position sizing, and composite strategies.

  • If you want to automate your TradingView strategy you can use PickMyTrade.

You May also Like:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *