Tutorial

Pine Script Daily Loss Limit: Stop Trading After a Bad Day

Code a daily loss limit in Pine Script v6: store day-start equity, halt entries and close positions when the day's loss hits your threshold.

•10 min read

You have a strategy that behaves itself most days. Then one session goes wrong: three entries in a row get stopped out, the fourth is a revenge entry the logic should never have taken, and the Strategy Tester shows a single day that eats a week of results. If you are reading a backtest, that day is a line in the trade list. If you are running the script live through alerts, it is the day you wish the strategy had simply stopped.

A daily loss limit is the rule that does exactly that. Once the day's loss reaches a threshold you chose in advance, the script closes what it holds and takes no new entries until the next day starts. It is one of the few risk rules that is easy to state in a sentence and surprisingly easy to get wrong in code. This guide builds it step by step in Pine Script v6, explains the three decisions hiding inside it (what counts as "the day", what counts as "the loss", and when the exit actually fills), and shows how to bolt it onto a strategy you already have without rewriting the entry logic.

What a daily loss limit does, and what it does not

The rule has three parts. It remembers your equity at the start of each trading day. It compares current equity to that starting figure on every bar. When the drop exceeds the limit, it flattens the position and blocks new entries until the next day begins.

That is all it does. It does not make a strategy better, it does not predict anything about tomorrow, and it does not guarantee that a loss stays at your threshold. A gap, a thin market, or a fill that arrives one bar late can all take the realized loss past the line. Think of it as a circuit breaker in your code: useful for containing a bad session in a backtest and for making a live alert setup behave in a way you can reason about, but not a promise about outcomes.

It also changes what your backtest means. A strategy with a daily limit trades fewer bars than the same strategy without one, so compare the two runs side by side instead of replacing the old results. The Strategy Tester metrics guide covers how to read the differences in drawdown and trade count.

Decision one: what counts as the day

Pine Script gives you timeframe.change("D"), which returns true on the first bar of each new day on the chart's symbol, measured in the exchange's time zone. For a crypto spot market that is usually a clean UTC midnight. For a stock listed on an exchange with a regular session, the day starts at the session open in the exchange's zone.

Two traps are worth knowing before you write a line. First, timeframe.change("D") only makes sense on a chart timeframe below a day. On a daily chart every bar is a new day, so the limit would reset on every bar and never trigger. Second, if you trade a market that runs around the clock, "the day" is a convention you chose, not something the market defines. If you would rather reset at a different hour, compare the hour of time in a time zone you name, as covered in the session and time filter guide. The related post on detecting a new day, week or session with ta.change shows the alternatives side by side.

Decision two: what counts as the loss

There are two reasonable definitions, and they behave differently.

The first is equity based. You compare strategy.equity now to strategy.equity at the start of the day. Equity includes the unrealized profit or loss of any open trade, so a position that is deep underwater counts against the limit before you have closed it. This is the cautious version, and it is what most people mean by a daily loss limit.

The second is realized only. You compare strategy.netprofit now to strategy.netprofit at the start of the day. Open trades do not count until they close. This version triggers later, because a losing trade has to actually be closed, usually by its own stop, before the limit can notice it. It suits strategies that hold positions across the day boundary and do not want a temporary drawdown to end the day early.

The script below lets you switch between the two with an input, so you can see how different the results are on your own symbol.

Decision three: when does the exit fill

When the limit is hit, the script calls strategy.close_all(). By default, Pine strategies evaluate on the close of a bar and fill orders on the next bar's open. So the loss you measured at the close of bar N is not the loss you realize: the close order fills at the open of bar N+1, which can be a different price. In a quiet market the difference is small. In a fast one, it is the whole reason a "2 percent" limit sometimes shows up as 2.6 percent in the trade list.

Setting process_orders_on_close=true in the strategy() declaration makes orders fill at the close of the bar on which they were issued. That removes the one-bar gap in a backtest, but note that on a live chart the bar close and your ability to act on it are not the same instant, so treat the backtest as the optimistic case. The process_orders_on_close guide explains the exact fill rules.

The full script

Here is a complete strategy. The entry logic is a plain EMA cross, chosen only because it is short and easy to replace. The part to read is the block between newDay and the entries.

pine
//@version=6
strategy("Daily Loss Limit Demo", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, process_orders_on_close=true)

maxDailyLossPct = input.float(2.0, "Max daily loss (% of day-start equity)", minval=0.1, step=0.1)
includeOpenPnl  = input.bool(true, "Count open trade profit and loss")
fastLen         = input.int(10, "Fast EMA length", minval=1)
slowLen         = input.int(30, "Slow EMA length", minval=2)

newDay = timeframe.change("D")

var float dayStartEquity = strategy.initial_capital
var float dayStartNet    = 0.0
var bool  haltedToday    = false

if newDay
    dayStartEquity := strategy.equity
    dayStartNet    := strategy.netprofit
    haltedToday    := false

dayPnl    = includeOpenPnl ? strategy.equity - dayStartEquity : strategy.netprofit - dayStartNet
lossLimit = -dayStartEquity * maxDailyLossPct / 100

if not haltedToday and dayPnl <= lossLimit
    haltedToday := true
    strategy.close_all(comment="Daily loss limit")

fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)

if not haltedToday
    if ta.crossover(fast, slow)
        strategy.entry("Long", strategy.long)
    if ta.crossunder(fast, slow)
        strategy.entry("Short", strategy.short)

plot(fast, "Fast EMA", color.new(color.teal, 0))
plot(slow, "Slow EMA", color.new(color.orange, 0))
bgcolor(haltedToday ? color.new(color.red, 88) : na, title="Halted for the day")

Read it from the top. The three var declarations hold state that survives from bar to bar: the equity and net profit at the start of the day, and a flag that says whether today is already halted. Without var, those values would reset on every bar and the limit would compare equity to itself.

On the first bar of each new day, the script stores a fresh starting figure and clears the flag. On every bar after that, it computes the day's profit or loss in the way you selected and compares it to the negative of the limit. The first time the comparison is true, it sets the flag and closes everything. Because the entries are wrapped in if not haltedToday, nothing new opens until the next day clears the flag.

The red background is not decoration. When you scroll back through a backtest, it tells you at a glance which days the rule fired, and how many bars each halted day skipped.

Pitfalls that break the rule quietly

The flag is set but a pending order still fills. strategy.close_all() closes open positions, but an entry order placed on the same bar and not yet filled can still go through. If your entry logic uses stop or limit orders, add strategy.cancel_all() next to the close so nothing is left waiting.

The limit uses today's starting equity, not initial capital. After a long run of wins or losses, the two numbers are far apart. A limit written against strategy.initial_capital will be too loose after a winning stretch and too tight after a losing one. Measuring from the day-start equity keeps the percentage meaning the same thing every day.

The first day of the chart is partial. The script starts its first "day" at whatever bar the chart history begins on, so the first day can be a few hours long. That rarely matters, but it is why the first halted flag in a backtest sometimes looks early.

Intrabar moves are invisible. The script checks the loss once per bar. A bar that spikes through your limit and recovers before it closes does not trigger the halt, and a bar that closes beyond it triggers it at the close. If you need finer resolution, the Bar Magnifier guide explains what it changes for fills inside a bar.

Add the rule to a strategy you already have

You do not need to restructure an existing strategy. The pattern is three pieces: the day-start state, the check that sets the flag, and a guard around every strategy.entry() call.

Copy the newDay block, the var state, and the if not haltedToday and dayPnl <= lossLimit block above your entry logic. Then add not haltedToday to each entry condition, for example if longCondition and not haltedToday. Leave exits alone: the stop loss and take profit you already have should keep working on a halted day, because they only close positions. If you want the exit logic too, the stop loss and take profit guide and the break-even stop post show how to keep it consistent.

If you work in the PineScripter editor, this is a natural follow-up request, and the editor changes only the lines that need to change instead of regenerating the whole script. Something like "Add a daily loss limit of 2 percent of day-start equity to this strategy, using equity, and shade the bars on halted days" is enough, and the Code Changes view lists exactly which lines were added. You then run it on the chart to see the shaded days before you paste it into TradingView. PineScripter does not simulate trades itself, so the numbers that matter come from TradingView's Strategy Tester.

Check that the limit really fires

Do not trust the rule because it compiles. Test it with a small number.

Set maxDailyLossPct to something absurdly tight, such as 0.2, and run the strategy on a lower timeframe where trades are frequent. You should see red shading on many days, and on each shaded day the trade list should show exactly one close with the comment "Daily loss limit", followed by no new entries until the next day. Then set the input back to a realistic value.

Next, toggle includeOpenPnl and compare. With open profit and loss counted, the halt arrives earlier, often while a trade is still open. With realized only, it arrives after a losing trade closes. If both settings give identical results on your symbol, your strategy probably closes trades quickly and rarely holds across the check, which is useful to know.

Finally, look at the day with the largest loss in the trade list. If it is well beyond your limit, look at how the exit filled. A gap through the limit and a close that waited for the next open are the usual causes, and the slippage and commission post shows how much those costs move the final numbers. For a wider view of how the strategy behaves across a whole run, the maximum drawdown guide and the equity curve post are the next things to read.

Variations worth knowing

A fixed currency limit is a one-line change. Replace the percentage with an input in account currency and compare dayPnl to the negative of that amount. This is useful when you size every trade the same way and think about risk in dollars.

A trade-count limit stops the day after a fixed number of losing trades, regardless of size. Track it with strategy.closedtrades at the start of the day and compare to the count now. It pairs well with a percentage limit, because many small losses can be as damaging to a day as one large one.

A weekly limit works the same way with timeframe.change("W"). Use a separate flag and a separate starting value, and block entries if either flag is set.

A cooldown instead of a full halt blocks entries for a number of bars after the limit, rather than until the next day. That fits strategies that you want to resume within the same session. Store the bar index when the limit fires and compare to bar_index.

Each variation is a small edit to the same skeleton: keep some state that survives the bar, test a condition, set a flag, and guard the entries.

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.

Frequently asked questions

Does a daily loss limit guarantee my loss stays under the threshold?

No. The script checks once per bar and closes through an order, so a gap, a fast move, or a fill on the next bar's open can take the realized loss past the line. It is a way to contain a bad session in code, not a guarantee.

Should I use equity or net profit to measure the daily loss?

Equity counts the open trade's unrealized result, so it halts earlier and is the cautious choice. Net profit counts only closed trades, so it fires later and suits strategies that hold positions across the day boundary. The script has an input so you can compare both.

Why does the limit never trigger on my daily chart?

timeframe.change("D") is true on every bar of a daily chart, so the day-start values reset each bar and the loss is always zero. Run the rule on a timeframe below one day.

Does the limit stop my stop loss and take profit from working?

Not if you guard only the entries. The halt flag blocks strategy.entry() calls, while exits you already have keep closing positions on a halted day.

Can I use a different day boundary than the exchange day?

Yes. Compare the hour of time in a time zone you name, and reset your day-start values when it crosses the hour you choose.

Can PineScripter add this to my existing strategy?

You can ask for it in plain English in the editor, and it edits only the lines that change, with a line-by-line view of the edit. You then check the result in TradingView's Strategy Tester, since PineScripter does not simulate trades.

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.