You have a strategy that enters when you want it to, and an exit that is either a fixed percentage or a take profit that never seems to fit the market it is running in. In a quiet week the fixed stop is too wide and gives back too much. In a volatile week it is too tight and gets hit by ordinary noise. The chandelier exit is a classic answer to that problem: a stop that hangs from the highest high of the recent past and sits a multiple of the average true range below it, so it widens when the market is jumpy and tightens when it calms down.
This guide builds it in Pine Script v6 from the formula up. You will get an indicator that plots both the long and short stop, a version that only ratchets in the favourable direction and flips side when price closes through it, a strategy that uses it as its exit, and a way to add it to a strategy you already have without disturbing the entries and alerts. Along the way we cover the mistakes that make a chandelier exit behave differently from the one you saw on a chart.
What the chandelier exit actually is
The name comes from the way the stop hangs from the ceiling of the recent trade, like a chandelier from a roof. The idea is usually credited to Chuck LeBeau. It is a trailing stop with one defining choice: the anchor is the highest high over a lookback window, not the entry price and not the current close.
For a long position the stop is the highest high of the last N bars minus a multiple of the ATR. The common defaults are 22 bars and a multiplier of 3, which comes from roughly one month of daily bars. For a short position it is mirrored: the lowest low of the last N bars plus the same multiple of the ATR. The ATR is the reason the stop adapts. If you want a refresher on how that number is built, the ATR guide walks through it, and the ATR stop loss calculator lets you try numbers without writing code.
Two properties matter when you code it. First, because the anchor is a rolling highest high, the stop rises as new highs print and does not fall just because price pulls back, as long as the old high is still inside the window. Second, once that old high drops out of the window, the raw value can fall. A trailing stop is normally expected never to move against you, so most implementations add a rule that holds the stop at its previous value while the position is open. That ratchet is the part people most often leave out, and we will add it deliberately.
The formula in Pine Script v6
Pine Script gives you everything needed in two built-ins. ta.highest(high, len) returns the highest value of the high series over the last len bars, and ta.atr(len) returns the average true range using RMA smoothing. If you want the details of the first, the ta.highest and ta.lowest guide covers its behaviour on the first bars of a chart and the series type it returns.
Here is the plain version, with no ratchet and no direction logic. It is the smallest script that draws the two raw stop lines.
//@version=6
indicator("Chandelier Exit (raw)", overlay = true)
len = input.int(22, "Lookback and ATR length", minval = 1)
mult = input.float(3.0, "ATR multiplier", minval = 0.1, step = 0.1)
atrVal = ta.atr(len)
longStop = ta.highest(high, len) - mult * atrVal
shortStop = ta.lowest(low, len) + mult * atrVal
plot(longStop, "Long stop", color = color.red, linewidth = 2)
plot(shortStop, "Short stop", color = color.teal, linewidth = 2)Load it and you will see two stepped lines. The red line trails below price in an uptrend and the teal line trails above price in a downtrend. In a trend, one of them hugs price and the other sits far away on the wrong side, which is why you rarely look at both at once. You will notice the red line sags in places even during a rally. That is the unratcheted raw value falling as an old high leaves the window, and it is exactly what the next section fixes.
Ratchet the stop and flip direction
A usable stop needs state. It should only move in the favourable direction while a trade is open, and it needs a way to say which side is currently active. The classic approach tracks a direction variable. The direction is long until price closes below the long stop, then short until price closes above the short stop.
//@version=6
indicator("Chandelier Exit", overlay = true)
len = input.int(22, "Lookback and ATR length", minval = 1)
mult = input.float(3.0, "ATR multiplier", minval = 0.1, step = 0.1)
atrVal = ta.atr(len)
rawLong = ta.highest(high, len) - mult * atrVal
rawShort = ta.lowest(low, len) + mult * atrVal
float longStop = na
float shortStop = na
int dir = 1
longPrev = nz(longStop[1], rawLong)
shortPrev = nz(shortStop[1], rawShort)
longStop := close[1] > longPrev ? math.max(rawLong, longPrev) : rawLong
shortStop := close[1] < shortPrev ? math.min(rawShort, shortPrev) : rawShort
dir := close > shortPrev ? 1 : close < longPrev ? -1 : nz(dir[1], 1)
buyFlip = dir == 1 and nz(dir[1], 1) == -1
sellFlip = dir == -1 and nz(dir[1], 1) == 1
plot(dir == 1 ? longStop : na, "Long stop", color = color.red, style = plot.style_linebr, linewidth = 2)
plot(dir == -1 ? shortStop : na, "Short stop", color = color.teal, style = plot.style_linebr, linewidth = 2)
plotshape(buyFlip, "Flip up", shape.triangleup, location.belowbar, color.teal, size = size.tiny)
plotshape(sellFlip, "Flip down", shape.triangledown, location.abovebar, color.red, size = size.tiny)
alertcondition(buyFlip, "Chandelier flip up", "Chandelier exit flipped to long side")
alertcondition(sellFlip, "Chandelier flip down", "Chandelier exit flipped to short side")The important lines are the two ratchet assignments. The long stop only keeps the larger of the new raw value and its previous value while the previous close is still above that previous stop. Once the close drops through, the ratchet resets to the raw value, which is what lets the stop re-anchor to a fresh high after a flip. The short side mirrors it with math.min.
The direction line compares the current close with the previous bar's stop values, not the current ones. That is deliberate. If you compared against the stop calculated on the same bar, the highest high would include the very bar you are testing, and the check would behave differently on a still-forming bar than on a closed one. Using the previous values keeps the flip stable once the bar closes. A flip is only final on a confirmed bar, so if you use the alerts, set them to fire once per bar close. The barstate.isconfirmed guide explains why an alert on an unconfirmed bar can fire and then vanish.
The plot.style_linebr style breaks the line where the value is na, which is what stops the two sides from being joined by a diagonal across the flip.
Use it as the exit in a strategy
An indicator only draws a line. To have the line close a position in the Strategy Tester you need strategy.exit with a stop price. The exit below pairs the chandelier stop with a placeholder entry, a simple EMA crossover, so that you can see the exit working. Swap the entry for your own.
//@version=6
strategy("EMA Cross with Chandelier Exit", overlay = true,
default_qty_type = strategy.percent_of_equity, default_qty_value = 10)
fastLen = input.int(50, "Fast EMA", minval = 1)
slowLen = input.int(100, "Slow EMA", minval = 1)
len = input.int(22, "Chandelier length", minval = 1)
mult = input.float(3.0, "Chandelier ATR multiplier", minval = 0.1, step = 0.1)
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
atrVal = ta.atr(len)
rawLong = ta.highest(high, len) - mult * atrVal
float longStop = na
longPrev = nz(longStop[1], rawLong)
longStop := close[1] > longPrev ? math.max(rawLong, longPrev) : rawLong
if ta.crossover(fast, slow)
strategy.entry("Long", strategy.long)
if strategy.position_size > 0
strategy.exit("Chandelier", "Long", stop = longStop)
plot(strategy.position_size > 0 ? longStop : na, "Chandelier stop", color = color.red, style = plot.style_linebr)
plot(fast, "Fast EMA", color = color.blue)
plot(slow, "Slow EMA", color = color.orange)There are two details worth understanding. The stop price is a series that changes every bar, and calling strategy.exit on every bar while the position is open simply updates the working order to the latest value. That is how a trailing level is expressed in Pine Script. And because the order is sent at the close of the bar and can only fill from the next bar onward, the stop you test against is the one you would really have had in place. The strategy.exit guide covers the stop, limit and trail arguments in more depth, and the trailing stop guide compares this approach with the built-in trail_points and trail_offset arguments.
One caveat on realism. The stop fills at the stop price or worse, and a gap through it fills at the gap. Commission and slippage settings change the result noticeably on short timeframes, so set them before you read anything into the numbers. The commission and slippage settings guide shows where those live.
Add it to a strategy you already have
Most readers do not want a new strategy. They have 200 lines of entries, filters, alerts and maybe a break-even rule, and they want the chandelier exit in place of the fixed stop. The risk in that edit is not the chandelier maths, which is six lines. The risk is touching the rest. A few rules keep it safe.
Keep the stop calculation in one place near the top of your calculations, and keep the exit call in one place near your order logic. If your script already calls strategy.exit with a fixed stop, replace its stop argument rather than adding a second exit with the same id, because two exits with the same id will fight over the same order. If you have several entries with different ids, give each its own exit call and the same stop series, or use a single strategy.exit per entry id with from_entry set.
If you also use a break-even rule or partial take profits, decide which one wins, because they all produce a stop price. The usual answer is the higher of the stops for a long position, with math.max. The break-even stop guide and the partial take profit guide show how those pieces are built, and combining them with math.max keeps the tightest protection live.
This is also the kind of edit where an AI coding workspace helps, as long as it changes only the lines involved. In PineScripter you can paste your strategy and ask for something like "replace the fixed 2 percent stop with a chandelier exit using a 22 bar lookback and ATR multiplier of 3, and leave the entries and alerts alone". It edits only the affected lines instead of rewriting the script, shows the change in the line-by-line Code Changes view so you can check that your entries did not move, and checks the result for compile errors the way TradingView does. You can then run the script on its chart over real crypto spot data and step through the bars with replay to watch when the stop moves. That is a way to see the logic, not a test of whether it makes money. For the trade statistics, use TradingView's Strategy Tester.
Choosing the length and multiplier
The two inputs do different jobs. The length controls how far back the anchor looks and also sets the ATR smoothing. A longer length means the highest high stays in the window longer, so the stop is slow to fall in its raw form and slow to rise in a new trend. The multiplier controls how much room you give price below that high. A multiplier of 3 means the stop sits three average ranges away, which keeps it out of the way of normal pullbacks but means a larger loss on each exit.
There is no setting that is right in general. On a 4 hour crypto chart, a multiplier of 3 on a 22 bar length covers a bit under four days of lookback, which is a very different horizon from 22 daily bars. If you change timeframe, you are changing what the inputs mean, so re-check them. A sensible habit is to vary one input at a time and look at the number of trades, the average loss and the maximum drawdown together, rather than picking the pair with the best headline figure. Picking the best-looking pair from a grid on one dataset is how a strategy gets fitted to history. The walk-forward testing guide shows a way to split the data so you test the chosen inputs on bars they were not tuned on.
A smaller multiplier such as 2 exits sooner and gives back less open profit on a reversal, but it also exits on ordinary pullbacks and then often needs a new entry. A larger multiplier such as 4 stays in longer trends and takes a larger hit when the trend finally ends. Neither is a promise of anything. They are trade-offs, and the choice depends on how the entry behaves.
Pitfalls that make it look different from the chart you copied
Most disagreement between your script and someone else's chandelier exit comes from a short list of causes.
The first is the ATR smoothing. ta.atr uses RMA, while some platforms use a simple average of the true range. The two give slightly different values, which shifts the stop. If you are matching another tool, check which one it uses. You can build the simple version with ta.sma(ta.tr, len) if you need it.
The second is the anchor. Some implementations use the highest close rather than the highest high. Using closes makes the stop a little tighter and ignores wicks. Neither is wrong, but they are different indicators, so name the choice in your input labels.
The third is the missing ratchet, described above. Without it the stop can sag mid-trend and the strategy exits at a lower price than the stop that was displayed earlier.
The fourth is evaluating on an unconfirmed bar. A stop calculated from the highest high of a bar still in progress changes with every tick. In a strategy that uses calc_on_every_tick, results can differ from the default close-of-bar behaviour, as the calc_on_every_tick guide explains. For an indicator that raises alerts, use bar-close alerts.
The fifth is the first bars of the chart. For the first len bars the highest high and the ATR are working with fewer bars or na, so ignore the opening stretch. The na values guide explains how those values propagate if one reaches a comparison.
The last is a stop that is too close to the entry. If the entry happens right after a spike, the highest high is the spike, and the ATR is large, so the stop can sit above the entry price, and the exit triggers on the next bar. Check for it with a quick look at the first trades on the chart rather than trusting the totals.
Chandelier exit versus Supertrend
The two get confused because both are ATR-based lines that flip. The difference is the anchor. Supertrend anchors to the midpoint of each bar's high and low and moves a fixed multiple of ATR away from it. The chandelier exit anchors to the highest high or lowest low of a window. So the chandelier stop responds to extremes, while Supertrend responds to the current bar. In a smooth trend they look alike. After a sharp spike the chandelier stop stays pinned beneath that spike until it leaves the window, while Supertrend relaxes much sooner. If you are choosing between them, the Supertrend guide shows its construction in the same style.
Where to go from here
You now have the formula, a ratcheting indicator with flip markers and alerts, a strategy exit, and a safe way to add the exit to an existing script. A practical next step is to load the indicator on two or three markets and timeframes and watch where the stop sits relative to the swings you would draw by eye. If it looks too tight or too loose everywhere, the multiplier is the first thing to change. Then add it to your strategy, set realistic commission and slippage, and read the results in the Strategy Tester.
If you would rather describe the change than write it, PineScripter is built for exactly that kind of edit to an existing script, and the code stays yours to copy anywhere. For the wider picture of exits, the stop loss and take profit guide is a good next read.
PineScripter is a coding tool, not a financial advisor. Nothing in this article is trading advice or a prediction, and no stop placement guarantees any outcome. Test any script on your own before using it, and consult a qualified professional for financial decisions.
Frequently asked questions
What are the default chandelier exit settings?
The common defaults are a 22 bar lookback and an ATR multiplier of 3. They are a starting point, not a recommendation, and they mean something different on each timeframe, so re-check them when you change it.
Why does my chandelier stop move down during an uptrend?
The raw value falls when an old high leaves the lookback window. Add the ratchet shown above, which holds the stop at its previous value while the previous close is still above it.
Is the chandelier exit the same as Supertrend?
No. Both use the ATR, but the chandelier exit anchors to the highest high or lowest low of a window, while Supertrend anchors to the midpoint of the current bar's high and low.
Does the chandelier exit repaint?
Not once the bar has closed. The direction check uses the previous bar's stop values, so a flip is final on a confirmed bar. Use bar-close alerts so a flip on a forming bar does not fire and then disappear.
How do I add a chandelier exit to a strategy I already have?
Replace the stop argument of your existing strategy.exit call with the chandelier series and leave the entries alone. If you also use break-even or partial exits, combine the stop prices with math.max for a long position.
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.