Skip to content

How to stop a TradingView strategy based on weekly loss?

How to stop a TradingView strategy based on weekly loss?

Section titled “How to stop a TradingView strategy based on weekly loss?”

TL;DR
Capture last week’s closing equity, compare it to current equity throughout the week, and block new orders (plus flatten open trades) once the drawdown crosses your maximum weekly loss.

DifficultyIntermediate
Time to implement15-20 min
CategoryRisk Management
//@version=5
strategy("Weekly loss guard", overlay=true, initial_capital=25_000)
maxWeeklyLoss = input.float(-1_500, "Max weekly loss ($)")
var float equityBaseline = na
newWeek = ta.change(time("W"))
if newWeek
equityBaseline := strategy.equity[1]
if na(equityBaseline)
equityBaseline := strategy.equity[1]
weeklyPnL = strategy.equity - equityBaseline
canTrade = weeklyPnL > maxWeeklyLoss
Tip. Store the baseline in a `var` so it survives bar-to-bar, and update it only when a new weekly session begins (`ta.change(time("W"))`).

Weekly loss limits keep automated systems from digging a deeper hole when the market climate changes. By pausing trading as soon as the drawdown exceeds your threshold, you preserve capital for the following week and avoid emotional overrides. Pine gives you full control: from defining the loss ceiling to cancelling orders the moment it’s reached.

  • Establish a weekly equity baseline and refresh it at the start of each week.
  • Measure current equity against that baseline to compute running profit or loss.
  • Block entry conditions (and cancel pending orders) when losses exceed the configured limit.
  • Close any active positions so the strategy truly stands down until the next reset.
CallPurpose
time("W")Weekly timestamp; changes when a new week begins.
strategy.equityCurrent account equity including open profit/loss.
strategy.entry(...)Entry function you’ll guard with the weekly-loss flag.
strategy.cancel_all()Removes unfilled orders once trading is halted.
strategy.close_all()Immediately exits open positions when the cap is breached.
  1. Refresh the weekly baseline
    Detect the first bar of a new week and capture equity from the previous bar.

    var float equityBaseline = na
    newWeek = ta.change(time("W"))
    if newWeek
    equityBaseline := strategy.equity[1]
    if na(equityBaseline)
    equityBaseline := strategy.equity[1] // seed on first run
  2. Measure weekly P&L vs. the limit
    Compare current equity to the stored baseline and flag whether trading is allowed.

    weeklyPnL = strategy.equity - equityBaseline
    maxLoss = input.float(-1_500, "Max weekly loss", tooltip="Negative number (e.g. -1500)")
    canTrade = weeklyPnL > maxLoss
  3. Enforce the pause
    Guard entries with canTrade, cancel working orders, and exit open positions when the limit hits.

    if not canTrade
    strategy.cancel_all()
    if strategy.position_size != 0
    strategy.close_all(comment="Weekly loss cap")
//@version=5
strategy("Weekly loss circuit breaker", overlay=true, pyramiding=0, initial_capital=50_000)
length = input.int(20, "Breakout lookback", minval=2)
maxWeeklyLoss = input.float(-2_000, "Max weekly loss ($)", tooltip="Set as a negative number")
reentryWeek = input.bool(true, "Resume trading next week automatically")
var float equityBaseline = na
newWeek = ta.change(time("W"))
if newWeek or na(equityBaseline)
equityBaseline := strategy.equity[1]
weeklyPnL = strategy.equity - equityBaseline
canTrade = weeklyPnL > maxWeeklyLoss
highestHigh = ta.highest(high, length)
lowestLow = ta.lowest(low, length)
longSignal = ta.crossover(high, highestHigh)
shortSignal = ta.crossunder(low, lowestLow)
if canTrade and longSignal
strategy.entry("Long", strategy.long)
if canTrade and shortSignal
strategy.entry("Short", strategy.short)
if not canTrade
strategy.cancel_all()
if strategy.position_size != 0
strategy.close_all(comment="Weekly loss stop")
plot(weeklyPnL, "Weekly P&L", color=color.new(color.blue, 0), display=display.bottom)
hline(0, "Break-even", color=color.new(color.gray, 60))
hline(maxWeeklyLoss, "Loss cap", color=color.new(color.red, 40))
var label status = na
if barstate.islast
if not na(status)
label.delete(status)
statusText = "Weekly P&L: " + str.tostring(weeklyPnL, "##,###.00") +
"\nCap: " + str.tostring(maxWeeklyLoss, "##,###.00") +
"\nTrading: " + (canTrade ? "ON" : "PAUSED")
status = label.new(bar_index, close, statusText, style=label.style_label_left, textcolor=color.white, bgcolor=color.new(canTrade ? color.green : color.red, 70))
if not canTrade and reentryWeek and newWeek
strategy.cancel_all()
Why this works.
  • The baseline updates once per week, so the drawdown calculation is stable for every bar that follows.
  • Entry conditions respect `canTrade`, guaranteeing no new positions slip through when the limit is hit.
  • Open positions are closed immediately, and pending orders are cleared, so the strategy truly stands down.
  • Configure the input as a negative number to keep comparisons intuitive (e.g., -1,500). You can also express it as a percentage of initial capital if preferred.
  • If your trading week starts on Sunday, replace time("W") with a manual day-of-week check (e.g., detect dayofweek == dayofweek.sunday).
  • Use var to persist the baseline; resetting it every bar will invalidate the drawdown calculation.
  • Consider logging (label or table) the timestamp when trading pauses so you know exactly when the limit tripped.

Make sure you seed it when the script first runs (if na(equityBaseline) …). Without that guard, the first week won’t have a reference point.

If you require manual reactivation, keep canTrade false until you change the input or reload the strategy. Otherwise, capture newWeek and reset the baseline so trading restarts automatically each Monday.

strategy.equity includes open P&L. If you only want closed-trade results, track strategy.closedtrades.profit(strategy.closedtrades - 1) instead and accumulate weekly totals manually.

  • Weekly loss caps are easy to enforce by comparing current equity against last week’s baseline.
  • Guarding entries with a boolean flag prevents the strategy from placing fresh orders once the cap is hit.
  • Combine automated cancellations and forced exits to guarantee your strategy actually stops trading.
  • Refresh the baseline at the start of each week so the system resumes with a clean slate.

Adapted from tradingcode.net, optimised for Algo Trade Analytics users.