Donchian Channel: TradingView (Pine Script) to MT5 (MQL5)

Short answer

Donchian is the highest high and lowest low of the last length bars, with a basis halfway between. MetaTrader 5 has no built-in, so scan the window in OnCalculate; with no smoothing state, the Pine and MQL5 versions are identical on every bar where both are defined.

The Donchian Channel draws the highest high and the lowest low of the last length bars, plus a basis line halfway between them. TradingView computes it with ta.highest and ta.lowest; MetaTrader 5 has no built-in Donchian indicator, so the MQL5 version below scans the window itself inside OnCalculate. Because the indicator carries no smoothing state, the two versions produce identical values on every bar where both are defined.

How the Donchian Channel is calculated

With length = 20 (the usual default) on bar t:

  • Upper = max(high[t], high[t-1], …, high[t-19])
  • Lower = min(low[t], low[t-1], …, low[t-19])
  • Basis = (Upper + Lower) / 2

The window includes the current bar. That matters for breakout logic: close > upper can never be true when the current high is part of the window, so breakout scripts usually compare against upper[1] or compute the channel on high[1]. The channel is undefined for the first length - 1 bars because the window is not yet full; Pine returns na there and the MQL5 version writes EMPTY_VALUE.

Pine Script v6 version

An original implementation. The basis plot is switched off by plotting na rather than by hiding the plot, which keeps the plot count fixed; the fill between the two bands is a separate fill() call.

//@version=6
indicator("Donchian Channel", shorttitle="DC", overlay=true)

length    = input.int(20, "Length", minval=1)
showBasis = input.bool(true, "Show basis")

upper = ta.highest(high, length)
lower = ta.lowest(low, length)
basis = math.avg(upper, lower)

pUp = plot(upper, "Upper", color=color.teal)
pLo = plot(lower, "Lower", color=color.teal)
plot(showBasis ? basis : na, "Basis", color=color.orange)
fill(pUp, pLo, color=color.new(color.teal, 92), title="Channel")

MQL5 version

Three buffers, three plots, no includes. The OnCalculate arrays arrive oldest-first (index 0 is the first bar in history), so the window for bar i is i - length + 1 … i and the inner loop walks backwards from i. ArrayMaximum(high, i - InpLength + 1, InpLength) would do the same job and return the index of the maximum; the explicit loop is kept here so the comparison with the Pine version is line for line.

//+------------------------------------------------------------------+
//| Donchian Channel: highest high / lowest low over Length bars      |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   3
#property indicator_label1  "Upper"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrTeal
#property indicator_label2  "Lower"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrTeal
#property indicator_label3  "Basis"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrOrange
#property indicator_style3  STYLE_DOT

input int  InpLength    = 20;    // Length
input bool InpShowBasis = true;  // Show basis

double UpperBuf[], LowerBuf[], BasisBuf[];

int OnInit()
  {
   if(InpLength < 1)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, UpperBuf, INDICATOR_DATA);
   SetIndexBuffer(1, LowerBuf, INDICATOR_DATA);
   SetIndexBuffer(2, BasisBuf, INDICATOR_DATA);
   for(int p = 0; p < 3; p++)
     {
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
      PlotIndexSetInteger(p, PLOT_DRAW_BEGIN, InpLength - 1);
     }
   if(!InpShowBasis)
      PlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_NONE);
   IndicatorSetString(INDICATOR_SHORTNAME, "DC(" + IntegerToString(InpLength) + ")");
   return INIT_SUCCEEDED;
  }

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[])
  {
   // Arrays are oldest-first: index 0 is the first bar in history,
   // rates_total - 1 is the forming bar. Recalculate only that bar on later ticks.
   int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)            // Pine: na until the window is full
        {
         UpperBuf[i] = EMPTY_VALUE;
         LowerBuf[i] = EMPTY_VALUE;
         BasisBuf[i] = EMPTY_VALUE;
         continue;
        }
      double hh = high[i], ll = low[i];
      for(int k = 1; k < InpLength; k++)   // this bar and the Length-1 before it
        {
         if(high[i - k] > hh) hh = high[i - k];
         if(low[i - k]  < ll) ll = low[i - k];
        }
      UpperBuf[i] = hh;
      LowerBuf[i] = ll;
      BasisBuf[i] = (hh + ll) / 2.0;
     }
   return rates_total;
  }

The start logic is the standard MT5 pattern: on the first call prev_calculated is 0 and every bar is computed; afterwards only the forming bar (prev_calculated - 1) is recomputed on each tick, which is the MQL5 way of expressing Pine's realtime-bar recalculation.

Differences you will see on the chart

TradingViewMetaTrader 5
First length - 1 barsna, nothing drawnEMPTY_VALUE, nothing drawn; PLOT_DRAW_BEGIN also tells the terminal where the line starts
Channel fillfill(pUp, pLo)Not in the hand-written version. MT5 needs a separate DRAW_FILLING plot with two buffers of its own that mirror Upper and Lower
Hiding the basisPlot naPlotIndexSetInteger(2, PLOT_DRAW_TYPE, DRAW_NONE); the buffer is still filled, so an EA reading buffer 2 with CopyBuffer gets values
Realtime barRecalculated on every tick; Upper rises as the bar makes new highsSame: bar rates_total - 1 is recomputed on each tick
RepaintingNone on closed barsNone on closed bars

Values on closed bars match exactly: the only operations are comparisons and one average, so there is no seeding or floating-point drift to speak of.

Using it in MetaTrader 5

Save the code as Donchian.mq5 under MQL5\Indicators in the data folder (File → Open Data Folder in MetaTrader), open it in MetaEditor and press F7. The compiled .ex5 appears in the Navigator under Indicators; drag it onto a chart and set Length in the Inputs tab. To read the bands from an Expert Advisor, create a handle with iCustom(_Symbol, _Period, "Donchian", 20, true) and copy buffer 0 (Upper), 1 (Lower) or 2 (Basis) with CopyBuffer; remember that CopyBuffer indexes newest-first, so index 1 is the last closed bar.

For a breakout alert, compare close[i] with UpperBuf[i - 1] in OnCalculate and call Alert() only when i == rates_total - 1 and the bar has just closed, or the alert fires on every tick of the forming bar.

What the Stratlate converter emits

Converting the Pine version above through the Stratlate engine reports the file as CLEAN. ta.highest and ta.lowest become per-bar window helpers, pine_highest(high, bar, length) and pine_lowest(low, bar, length) from the bundled PineRuntime.mqh, which return na until the window is full and whenever a value inside it is na, exactly as Pine does. math.avg becomes an inline average, each plot() becomes a DRAW_LINE buffer with TradingView's RGB colours set in OnInit, and fill() becomes a DRAW_FILLING plot with two extra buffers copied from the Upper and Lower buffers. The only note is informational: minval=1 on the length input has no MQL5 equivalent and is dropped, so the converted indicator accepts a length of 0 unless you add the check in OnInit. Compile the output and run it against the TradingView chart before trading on it.

Pitfalls

  • Using ArraySetAsSeries on the input arrays and keeping the oldest-first loop. The window then points at the wrong bars and the channel appears shifted by length bars. Pick one indexing direction for the whole indicator.
  • Computing from i - InpLength instead of i - InpLength + 1. The window becomes length + 1 bars wide and Upper is occasionally higher than TradingView's.
  • Not writing EMPTY_VALUE on the warm-up bars. Buffer memory is not guaranteed to be zeroed; stale values draw a spike towards 0 at the left edge of the chart.
  • Breakout tests against the current bar's channel. close > upper is never true because the current high is inside the window. Use upper[1] in Pine and UpperBuf[i - 1] in MQL5.
  • Returning 0 from OnCalculate on error paths. MT5 then recalculates the whole history on the next tick, which is slow and hides the real problem. Return rates_total once buffers are filled.

FAQ

Is there an iDonchian function in MQL5?

No. MetaTrader 5 ships no Donchian indicator, so you either write one as above or use iHighest/iLowest (which return bar indexes in newest-first terms) or ArrayMaximum/ArrayMinimum on the price arrays inside your own code.

Why does the channel start a few bars later in MT5 than on TradingView?

It should not. Both versions are undefined for exactly length - 1 bars. If the MT5 line starts later, check PLOT_DRAW_BEGIN and the warm-up condition; if it starts earlier, the MT5 version is averaging a partial window, which TradingView never does.

Can I add the channel fill in MQL5?

Yes. Add a plot of type DRAW_FILLING with two buffers, copy Upper into the first and Lower into the second on every bar, and set its two colours with PlotIndexSetInteger(plot, PLOT_LINE_COLOR, 0, clr) and index 1. This is what the Stratlate converter does for fill().

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

Related