Chandelier Exit: TradingView (Pine Script) to MT5 (MQL5)
Short answer
The long stop hangs mult × ATR(n) below the highest high of the last n bars, and the short stop the same distance above the lowest low. A ratchet stops each from loosening, and a close through the opposite stop switches the regime. With the same recurrence, Pine and MQL5 agree once the ATR has warmed up.
The Chandelier Exit hangs a stop below the highest high of the last n bars (for longs) and above the lowest low (for shorts), at a distance of mult × ATR(n). A ratchet keeps each stop from loosening while price stays on its side, and a close through the opposite stop switches the regime. Written in Pine Script v6 and MQL5 with the same recurrence, the two versions agree once the ATR has warmed up.
How the Chandelier Exit is calculated
Defaults: length 22 for both the ATR and the lookback, multiplier 3.0, extremes from highs and lows (an option switches to closes).
band = mult × ATR(len), with Wilder's ATR asta.atrcomputes it: true range smoothed byta.rma, seeded with the simple average of the firstlentrue ranges.- Raw stops:
longRaw = highest(high, len) - band,shortRaw = lowest(low, len) + band. - Ratchet: if the previous close was above the previous long stop,
longStop = max(longRaw, longStop[1]), otherwiselongRaw. Mirror for the short stop withmin. - Regime:
dir = 1(long) after a close above the previous short stop,-1after a close below the previous long stop, otherwise unchanged; it starts at 1. - Drawn: the long stop while
dir = 1, the short stop whiledir = -1, and a marker on the bar where the regime changes.
The regime test uses the previous bar's stops, while the ratchet compares the previous close with the previous stop. Both are deliberate: they make the indicator depend only on completed information except for the current close.
Pine Script v6 version
The two ta.highest and two ta.lowest calls sit inside ternaries selected by the useClose input; since the input is constant for a run, the same branch is taken on every bar. The stops self-reference through [1], so they are declared and then reassigned.
//@version=6
indicator("Chandelier Exit, written out", "CE", overlay = true)
len = input.int(22, "ATR and lookback length", minval = 1)
mult = input.float(3.0, "ATR multiplier", minval = 0.1, step = 0.1)
useClose = input.bool(false, "Extremes from closes instead of highs/lows")
float band = mult * ta.atr(len)
float hh = useClose ? ta.highest(close, len) : ta.highest(high, len)
float ll = useClose ? ta.lowest(close, len) : ta.lowest(low, len)
float longRaw = hh - band // exit for longs: below the highest point
float shortRaw = ll + band // exit for shorts: above the lowest point
// Ratchet: while the previous close stays on the right side, the stop never
// loosens. Once price closes through it, the stop restarts from the raw value.
float longStop = longRaw
float shortStop = shortRaw
longStop := not na(longStop[1]) and close[1] > longStop[1] ? math.max(longRaw, longStop[1]) : longRaw
shortStop := not na(shortStop[1]) and close[1] < shortStop[1] ? math.min(shortRaw, shortStop[1]) : shortRaw
// 1 = long regime, -1 = short regime; a close beyond the opposite stop flips it
var int dir = 1
dir := close > shortStop[1] ? 1 : close < longStop[1] ? -1 : nz(dir[1], 1)
bool turnLong = dir == 1 and dir[1] == -1
bool turnShort = dir == -1 and dir[1] == 1
plot(dir == 1 ? longStop : na, "Long stop", color.green, 2, plot.style_linebr)
plot(dir == -1 ? shortStop : na, "Short stop", color.red, 2, plot.style_linebr)
plotshape(turnLong, "Buy", shape.labelup, location.belowbar, color.green, text = "Buy", textcolor = color.white, size = size.small)
plotshape(turnShort, "Sell", shape.labeldown, location.abovebar, color.red, text = "Sell", textcolor = color.white, size = size.small)
alertcondition(turnLong, "Chandelier long", "Chandelier Exit switched to long")
alertcondition(turnShort, "Chandelier short", "Chandelier Exit switched to short")nz(dir[1], 1) supplies the starting regime on the first bar, where there is no history.
MQL5 version
State lives in calculation buffers (Atr, Tr, LongStop, ShortStop, Dir) and the loop reads only bar i - 1, so the realtime bar can be recomputed on every tick. Highest() and Lowest() scan len bars backwards over the oldest-first arrays. The warm-up test is on the ATR, which is the last component to become available.
//+------------------------------------------------------------------+
//| ChandelierExit_TV.mq5 - highest high - ATR*mult / lowest low + |
//| ATR*mult with a ratchet and a long/short regime |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 9
#property indicator_plots 4
#property indicator_label1 "Long stop"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_width1 2
#property indicator_label2 "Short stop"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_width2 2
#property indicator_label3 "Buy"
#property indicator_type3 DRAW_ARROW
#property indicator_color3 clrGreen
#property indicator_width3 2
#property indicator_label4 "Sell"
#property indicator_type4 DRAW_ARROW
#property indicator_color4 clrRed
#property indicator_width4 2
input int InpLen = 22; // ATR and lookback length
input double InpMult = 3.0; // ATR multiplier
input bool InpUseClose = false; // Extremes from closes instead of highs/lows
double LongLine[], ShortLine[], BuyArrow[], SellArrow[]; // drawn
double Tr[], Atr[], LongStop[], ShortStop[], Dir[]; // per-bar state
int OnInit()
{
if(InpLen < 1 || InpMult <= 0.0)
return INIT_PARAMETERS_INCORRECT;
SetIndexBuffer(0, LongLine, INDICATOR_DATA);
SetIndexBuffer(1, ShortLine, INDICATOR_DATA);
SetIndexBuffer(2, BuyArrow, INDICATOR_DATA);
SetIndexBuffer(3, SellArrow, INDICATOR_DATA);
SetIndexBuffer(4, Tr, INDICATOR_CALCULATIONS);
SetIndexBuffer(5, Atr, INDICATOR_CALCULATIONS);
SetIndexBuffer(6, LongStop, INDICATOR_CALCULATIONS);
SetIndexBuffer(7, ShortStop, INDICATOR_CALCULATIONS);
SetIndexBuffer(8, Dir, INDICATOR_CALCULATIONS);
for(int p = 0; p < 4; p++)
PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(2, PLOT_ARROW, 233);
PlotIndexSetInteger(3, PLOT_ARROW, 234);
IndicatorSetString(INDICATOR_SHORTNAME, "Chandelier(" + (string)InpLen + "," + DoubleToString(InpMult, 1) + ")");
return INIT_SUCCEEDED;
}
double Highest(const double &a[], const int i, const int len)
{
double best = a[i];
for(int k = 1; k < len; k++) if(a[i - k] > best) best = a[i - k];
return best;
}
double Lowest(const double &a[], const int i, const int len)
{
double best = a[i];
for(int k = 1; k < len; k++) if(a[i - k] < best) best = a[i - k];
return best;
}
int OnCalculate(const int rates_total, const int prev_calculated,
const datetime &time[], const double &open[], const double &high[],
const double &low[], const double &close[], const long &tick_volume[],
const long &volume[], const int &spread[])
{
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// Wilder ATR seeded with a simple average (ta.atr)
Tr[i] = (i == 0) ? high[i] - low[i]
: MathMax(high[i] - low[i], MathMax(MathAbs(high[i] - close[i - 1]), MathAbs(low[i] - close[i - 1])));
if(i < InpLen - 1)
Atr[i] = EMPTY_VALUE;
else if(i == InpLen - 1)
{
double sum = 0.0;
for(int k = 0; k < InpLen; k++) sum += Tr[i - k];
Atr[i] = sum / InpLen;
}
else
Atr[i] = (Atr[i - 1] * (InpLen - 1) + Tr[i]) / InpLen;
LongLine[i] = EMPTY_VALUE; ShortLine[i] = EMPTY_VALUE;
BuyArrow[i] = EMPTY_VALUE; SellArrow[i] = EMPTY_VALUE;
if(Atr[i] == EMPTY_VALUE)
{
LongStop[i] = EMPTY_VALUE; ShortStop[i] = EMPTY_VALUE; Dir[i] = 1;
continue;
}
double band = InpMult * Atr[i];
double longRaw = (InpUseClose ? Highest(close, i, InpLen) : Highest(high, i, InpLen)) - band;
double shortRaw = (InpUseClose ? Lowest(close, i, InpLen) : Lowest(low, i, InpLen)) + band;
// Ratchet: never loosen while the previous close is on the right side
bool havePrev = (i > 0 && LongStop[i - 1] != EMPTY_VALUE);
LongStop[i] = (havePrev && close[i - 1] > LongStop[i - 1]) ? MathMax(longRaw, LongStop[i - 1]) : longRaw;
ShortStop[i] = (havePrev && close[i - 1] < ShortStop[i - 1]) ? MathMin(shortRaw, ShortStop[i - 1]) : shortRaw;
// Regime: 1 long, -1 short; a close beyond the opposite stop flips it
if(havePrev && close[i] > ShortStop[i - 1]) Dir[i] = 1;
else if(havePrev && close[i] < LongStop[i - 1]) Dir[i] = -1;
else Dir[i] = (i > 0) ? Dir[i - 1] : 1;
if(Dir[i] == 1) LongLine[i] = LongStop[i]; else ShortLine[i] = ShortStop[i];
if(havePrev && Dir[i] == 1 && Dir[i - 1] == -1) BuyArrow[i] = low[i];
if(havePrev && Dir[i] == -1 && Dir[i - 1] == 1) SellArrow[i] = high[i];
}
return rates_total;
}havePrev is false on the first bar that has an ATR; on that bar both stops take their raw values and the regime stays at its previous value (1), which is exactly what the Pine conditions produce when longStop[1] and shortStop[1] are na.
Differences you will see on the chart
| Topic | TradingView | MetaTrader 5 |
|---|---|---|
| Warm-up | Nothing drawn for the first len - 1 bars; the long stop appears on bar len - 1. | Same bars are EMPTY_VALUE; the first line is the long stop on bar len - 1. |
| Early values | The highest/lowest part is exact immediately, but the ATR carries a seed from the first bars of each platform's history, and the ratchet and regime are path dependent. Expect the first flips to differ; after the seed has decayed (several hundred bars at len = 22) the lines and flips coincide. | |
| Markers | plotshape labels with "Buy"/"Sell" text. | Arrow buffers at the bar's low and high (Wingdings 233/234), no text. |
| Gaps between regimes | plot.style_linebr leaves a break where the line switches. | EMPTY_VALUE in a DRAW_LINE buffer leaves the same break. |
| Realtime bar | A regime flip can appear and disappear within the bar. | Same; read the last closed bar from an EA. |
Closed bars do not repaint on either platform.
What the Stratlate converter does with this script
Converted with the Stratlate engine, the Pine script above is graded CLEAN. ta.atr becomes pine_atr_hlc (true range plus Wilder smoothing seeded by a simple average). Because each ta.highest and ta.lowest call sits inside a ternary, the engine gives every call site its own history buffer (pine_put/pine_cpos) rather than reading the price arrays directly, so a call that is only reached on some bars still sees a correct window; here the branch is constant, so the result is the same as pine_highest(high, ...). The self-referencing stops and the var int dir become per-bar arrays read with pine_hist, nz(dir[1], 1) becomes pine_nz(..., 1), the plots become DRAW_LINE buffers and the plotshape calls DRAW_ARROW buffers with their text drawn as chart objects. The report carries informational PM221 notes about input options such as step. Compile and backtest the output before relying on it.
Using it in MetaTrader 5
- Save as
ChandelierExit_TV.mq5inMQL5\Indicators, compile (F7, no warnings) and attach it with length 22 and multiplier 3.0. - Turn on Extremes from closes only if the TradingView script you are matching uses closes; the default on TradingView scripts varies, and the choice changes every stop level.
- From an EA,
iCustom(_Symbol, _Period, "ChandelierExit_TV", 22, 3.0, false). Buffer 0 is the long stop (only while long), buffer 1 the short stop, buffers 2 and 3 the flip arrows, buffer 8 the regime (1 or -1). To trail a long position's stop-loss, copy buffer 0 on the last closed bar and move the stop up when the value rises. - For an alert, call
Alert()whenBuyArroworSellArrowonrates_total - 1becomes non-empty, guarded so it fires once per bar.
Pitfalls
- Using
iATRoriHighestshortcuts.iHighestreturns an index, not a value, and MetaTrader's ATR does not smooth the true range liketa.rma. Compute both as shown. - Dropping the ratchet. Without it the long stop falls whenever volatility rises, and the regime flips far more often than TradingView shows.
- Testing the regime against the current stops. Pine compares
closewithshortStop[1]andlongStop[1]. Using the current bar's stops flips one bar early on some bars. - Static variables for the stops. On the realtime bar each tick would ratchet again. Keep the state per bar in buffers.
- Reading bar 0 from an EA. The arrow on the open bar can vanish before the close; act on bar 1.
FAQ
Why does the Chandelier Exit flip on a different bar than TradingView early in the chart?
The ATR seed is built from the first bars each platform loaded, so the band width differs slightly at first. One borderline close then flips the regime on one platform and not the other, and the ratchet keeps the two versions apart until the next clear move. Recent bars agree.
Can I use the stop line directly as a stop-loss?
Yes. Read the long stop (buffer 0) or short stop (buffer 1) on the last closed bar and place the stop there; the ratchet guarantees it only moves in the trade's favour until the regime flips.
Does the highest/lowest window need warm-up like the ATR?
Only for the first len - 1 bars, after which it is exact: a window over raw highs and lows has no seed. The ATR is the only part that carries history forward.
Convert your own version
Have a variant of this indicator, or any other TradingView script? Paste it and get MQL5 that is checked against the original on the same price history, with every construct that could not be carried over reported.
Open the converter