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.
At a Glance
Section titled “At a Glance”| Difficulty | Intermediate |
| Time to implement | 15-20 min |
| Category | Risk Management |
Quick Actions
Section titled “Quick Actions”Quick Start
Section titled “Quick Start”//@version=5strategy("Weekly loss guard", overlay=true, initial_capital=25_000)
maxWeeklyLoss = input.float(-1_500, "Max weekly loss ($)")
var float equityBaseline = nanewWeek = ta.change(time("W"))
if newWeek equityBaseline := strategy.equity[1]if na(equityBaseline) equityBaseline := strategy.equity[1]
weeklyPnL = strategy.equity - equityBaselinecanTrade = weeklyPnL > maxWeeklyLossWhy It Matters
Section titled “Why It Matters”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.
What You’ll Learn
Section titled “What You’ll Learn”- 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.
Quick Reference
Section titled “Quick Reference”| Call | Purpose |
|---|---|
time("W") | Weekly timestamp; changes when a new week begins. |
strategy.equity | Current 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. |
Implementation Blueprint
Section titled “Implementation Blueprint”-
Refresh the weekly baseline
Detect the first bar of a new week and capture equity from the previous bar.var float equityBaseline = nanewWeek = ta.change(time("W"))if newWeekequityBaseline := strategy.equity[1]if na(equityBaseline)equityBaseline := strategy.equity[1] // seed on first run -
Measure weekly P&L vs. the limit
Compare current equity to the stored baseline and flag whether trading is allowed.weeklyPnL = strategy.equity - equityBaselinemaxLoss = input.float(-1_500, "Max weekly loss", tooltip="Negative number (e.g. -1500)")canTrade = weeklyPnL > maxLoss -
Enforce the pause
Guard entries withcanTrade, cancel working orders, and exit open positions when the limit hits.if not canTradestrategy.cancel_all()if strategy.position_size != 0strategy.close_all(comment="Weekly loss cap")
Example Playbook
Section titled “Example Playbook”//@version=5strategy("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 = nanewWeek = ta.change(time("W"))
if newWeek or na(equityBaseline) equityBaseline := strategy.equity[1]
weeklyPnL = strategy.equity - equityBaselinecanTrade = 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 = naif 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()- 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.
Pro Tips & Pitfalls
Section titled “Pro Tips & Pitfalls”- 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., detectdayofweek == dayofweek.sunday). - Use
varto persist the baseline; resetting it every bar will invalidate the drawdown calculation. - Consider logging (
labelortable) the timestamp when trading pauses so you know exactly when the limit tripped.
Troubleshooting & FAQ
Section titled “Troubleshooting & FAQ”The baseline stays na
Section titled “The baseline stays na”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.
Trading never resumes
Section titled “Trading never resumes”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.
Loss calculation jumps wildly
Section titled “Loss calculation jumps wildly”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.
Key Takeaways
Section titled “Key Takeaways”- 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.
Keep Going
Section titled “Keep Going”- Open AI Editor to apply the pattern with guided assistance
- Browse Strategy Examples for ready-to-run templates
- Connect to Live Trading when you are ready to automate
Adapted from tradingcode.net, optimised for Algo Trade Analytics users.