Market Structure - By Leviathan in MQL5 — converted from Pine Script
The Market Structure - By Leviathan indicator by Leviathan, published on TradingView under the Mozilla Public License 2.0, converted to MetaTrader 5 by the Stratlate engine. The conversion was executed against the original on 500 synthetic bars and compared value by value: equivalent (fidelity 1.000).
Swing point generation inspired by @BacktestRookies
Inputs
| Input | Default |
|---|---|
| Swing Length | 20 |
| BOS Confirmation | 'Candle Close' |
| Show CHoCH | false |
| Show Swing Points | true |
| Show 0.5 Retracement Level | false |
| halfColor | color.rgb(41 |
| Line Style | 'Solid' |
| Width | 1 |
| bosColor | color.rgb(112 |
| Line Style | 'Dashed' |
| Width | 1 |
Converted MQL5
Save as market-structure.mq5 next to PineRuntime.mqh (included with every conversion), compile in MetaEditor, then review and backtest before trading. Output of the engine alone; the AI review available after sign-in may improve it further.
//+------------------------------------------------------------------+
//| pine-transpiler 0.6.46 (pinec) - generated code
//| source sha256: 833be96f259a status: CLEAN
//| notes: 0 unsupported, 0 warn, 15 info
//| Review, compile and backtest before trading.
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Market Structure - By Leviathan
//| Converted from Pine Script by pine-transpiler.
//| Review before trading: see the accompanying report for every
//| construct that was approximated or could not be converted.
//+------------------------------------------------------------------+
#property copyright "Converted by pine-transpiler"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots 0
#include "PineRuntime.mqh"
//--- plot buffers
// no plot() in source: nothing to bind (drawings only)
//--- script-level state
// The newest bar's index: `last_bar_index` and `barstate.islast`.
int __pineLastBar = 0;
// Series-valued names are arrays because their history is read;
// the rest stay scalars.
color CLEAR = clrNONE;
double pivHi = PINE_NA;
double pivLo = PINE_NA;
double prevHigh = PINE_NA;
double prevLow = PINE_NA;
double prevHighIndex = PINE_NA;
double prevLowIndex = PINE_NA;
bool highActive = false;
bool lowActive = false;
bool hh = false;
bool lh = false;
bool hl = false;
bool ll = false;
double prevSwing[];
bool highBroken = false;
bool lowBroken = false;
int prevBreakoutDir = 0;
double highSrc = PINE_NA;
double lowSrc = PINE_NA;
//--- live-tick rollback: the state each bar started from
color __sv_CLEAR;
color __si_CLEAR;
double __sv_pivHi;
double __si_pivHi;
double __sv_pivLo;
double __si_pivLo;
double __sv_prevHigh;
double __si_prevHigh;
double __sv_prevLow;
double __si_prevLow;
double __sv_prevHighIndex;
double __si_prevHighIndex;
double __sv_prevLowIndex;
double __si_prevLowIndex;
bool __sv_highActive;
bool __si_highActive;
bool __sv_lowActive;
bool __si_lowActive;
bool __sv_hh;
bool __si_hh;
bool __sv_lh;
bool __si_lh;
bool __sv_hl;
bool __si_hl;
bool __sv_ll;
bool __si_ll;
bool __sv_highBroken;
bool __si_highBroken;
bool __sv_lowBroken;
bool __si_lowBroken;
int __sv_prevBreakoutDir;
int __si_prevBreakoutDir;
double __sv_highSrc;
double __si_highSrc;
double __sv_lowSrc;
double __si_lowSrc;
int __pineSnapBar = -1;
void __pineSaveState()
{
__sv_CLEAR = CLEAR;
__sv_pivHi = pivHi;
__sv_pivLo = pivLo;
__sv_prevHigh = prevHigh;
__sv_prevLow = prevLow;
__sv_prevHighIndex = prevHighIndex;
__sv_prevLowIndex = prevLowIndex;
__sv_highActive = highActive;
__sv_lowActive = lowActive;
__sv_hh = hh;
__sv_lh = lh;
__sv_hl = hl;
__sv_ll = ll;
__sv_highBroken = highBroken;
__sv_lowBroken = lowBroken;
__sv_prevBreakoutDir = prevBreakoutDir;
__sv_highSrc = highSrc;
__sv_lowSrc = lowSrc;
pine_draw_mark();
__pineSaveGen++; // helpers' static arrays snapshot lazily
}
void __pineRestoreState()
{
CLEAR = __sv_CLEAR;
pivHi = __sv_pivHi;
pivLo = __sv_pivLo;
prevHigh = __sv_prevHigh;
prevLow = __sv_prevLow;
prevHighIndex = __sv_prevHighIndex;
prevLowIndex = __sv_prevLowIndex;
highActive = __sv_highActive;
lowActive = __sv_lowActive;
hh = __sv_hh;
lh = __sv_lh;
hl = __sv_hl;
ll = __sv_ll;
highBroken = __sv_highBroken;
lowBroken = __sv_lowBroken;
prevBreakoutDir = __sv_prevBreakoutDir;
highSrc = __sv_highSrc;
lowSrc = __sv_lowSrc;
pine_draw_rollback();
__pineRestoreGen++;
__pineRestoreSaveGen = __pineSaveGen;
}
void __pineSaveInitial()
{
__si_CLEAR = CLEAR;
__si_pivHi = pivHi;
__si_pivLo = pivLo;
__si_prevHigh = prevHigh;
__si_prevLow = prevLow;
__si_prevHighIndex = prevHighIndex;
__si_prevLowIndex = prevLowIndex;
__si_highActive = highActive;
__si_lowActive = lowActive;
__si_hh = hh;
__si_lh = lh;
__si_hl = hl;
__si_ll = ll;
__si_highBroken = highBroken;
__si_lowBroken = lowBroken;
__si_prevBreakoutDir = prevBreakoutDir;
__si_highSrc = highSrc;
__si_lowSrc = lowSrc;
pine_draw_save_initial();
}
void __pineRestoreInitial()
{
CLEAR = __si_CLEAR;
pivHi = __si_pivHi;
pivLo = __si_pivLo;
prevHigh = __si_prevHigh;
prevLow = __si_prevLow;
prevHighIndex = __si_prevHighIndex;
prevLowIndex = __si_prevLowIndex;
highActive = __si_highActive;
lowActive = __si_lowActive;
hh = __si_hh;
lh = __si_lh;
hl = __si_hl;
ll = __si_ll;
highBroken = __si_highBroken;
lowBroken = __si_lowBroken;
prevBreakoutDir = __si_prevBreakoutDir;
highSrc = __si_highSrc;
lowSrc = __si_lowSrc;
pine_draw_reset();
__pineInitGen++;
}
color halfColor = clrNONE; // input whose default is not a compile-time constant
color bosColor = clrNONE; // input whose default is not a compile-time constant
//--- inputs
input int swingSize = 20; // Swing Length
input string bosConfType = "Candle Close"; // BOS Confirmation
input bool choch = false; // Show CHoCH
input bool showSwing = true; // Show Swing Points
input bool showHalf = false; // Show 0.5 Retracement Level
input string halfStyle = "Solid"; // Line Style
input int halfWidth = 1; // Width
input string bosStyle = "Dashed"; // Line Style
input int bosWidth = 1; // Width
//--- user functions
double lineStyle(const string x, const int __pineBar)
{
if((x == "Solid"))
{
return STYLE_SOLID;
}
else
{
if((x == "Dashed"))
{
return STYLE_DASH;
}
else
{
if((x == "Dotted"))
{
return STYLE_DOT;
}
else
{
return PINE_NA;
}
}
}
return PINE_NA;
}
int OnInit()
{
if(halfWidth < 1) { Print("Width", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
if(bosWidth < 1) { Print("Width", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
__pineMaxLines = 500;
__pineMaxLabels = 500;
CLEAR = pine_color_rgb((int)(0), (int)(0), (int)(0));
IndicatorSetString(INDICATOR_SHORTNAME, "Market Structure - By Leviathan");
__pineSaveInitial();
return INIT_SUCCEEDED;
}
//--- one bar == one evaluation of the original Pine script
void PineBar(const int __pineBar,
const double &open[], const double &high[],
const double &low[], const double &close[],
const long &volume[],
const datetime &time[])
{
halfColor = pine_color_rgb((int)(41), (int)(39), (int)(176));
bosColor = pine_color_rgb((int)(112), (int)(114), (int)(119));
if(__pineBar == 0)
{
prevSwing[__pineBar] = 0;
}
if(__pineBar > 0)
{
prevSwing[__pineBar] = prevSwing[__pineBar - 1];
}
CLEAR = pine_color_rgb((int)(0), (int)(0), (int)(0));
pivHi = pine_pivothigh(high, __pineBar, (int)(swingSize), (int)(swingSize));
pivLo = pine_pivotlow(low, __pineBar, (int)(swingSize), (int)(swingSize));
hh = false;
lh = false;
hl = false;
ll = false;
if((!pine_na(pivHi)))
{
if((pivHi >= prevHigh))
{
hh = true;
prevSwing[__pineBar] = 2;
}
else
{
lh = true;
prevSwing[__pineBar] = 1;
}
prevHigh = pivHi;
highActive = true;
prevHighIndex = (__pineBar - swingSize);
}
if((!pine_na(pivLo)))
{
if((pivLo >= prevLow))
{
hl = true;
prevSwing[__pineBar] = (-1);
}
else
{
ll = true;
prevSwing[__pineBar] = (-2);
}
prevLow = pivLo;
lowActive = true;
prevLowIndex = (__pineBar - swingSize);
}
highBroken = false;
lowBroken = false;
highSrc = ((bosConfType == "Candle Close") ? close[__pineBar] : high[__pineBar]);
lowSrc = ((bosConfType == "Candle Close") ? close[__pineBar] : low[__pineBar]);
if(((((highSrc > prevHigh) ? 1 : 0) & (highActive ? 1 : 0)) != 0))
{
highBroken = true;
highActive = false;
}
if(((((lowSrc < prevLow) ? 1 : 0) & (lowActive ? 1 : 0)) != 0))
{
lowBroken = true;
lowActive = false;
}
if((((hh ? 1 : 0) & (showSwing ? 1 : 0)) != 0))
{
pine_label_style(pine_label_new((__pineBar - swingSize), pivHi, "HH"), (color)(CLEAR), (color)((color)ChartGetInteger(0, CHART_COLOR_FOREGROUND)), true, ANCHOR_LOWER, 0, "");
if(((((pine_hist(prevSwing, __pineBar, (int)(1)) == (-1)) ? 1 : 0) & (showHalf ? 1 : 0)) != 0))
{
pine_line_style(pine_line_new(prevLowIndex, pine_div((prevLow + pivHi), 2), (__pineBar - swingSize), pine_div((prevLow + pivHi), 2)), (color)(halfColor), (int)(lineStyle(halfStyle, __pineBar)), (int)(halfWidth), -1);
}
}
if((((lh ? 1 : 0) & (showSwing ? 1 : 0)) != 0))
{
pine_label_style(pine_label_new((__pineBar - swingSize), pivHi, "LH"), (color)(CLEAR), (color)((color)ChartGetInteger(0, CHART_COLOR_FOREGROUND)), true, ANCHOR_LOWER, 0, "");
}
if((((hl ? 1 : 0) & (showSwing ? 1 : 0)) != 0))
{
pine_label_style(pine_label_new((__pineBar - swingSize), pivLo, "HL"), (color)(CLEAR), (color)((color)ChartGetInteger(0, CHART_COLOR_FOREGROUND)), true, ANCHOR_UPPER, 0, "");
}
if((((ll ? 1 : 0) & (showSwing ? 1 : 0)) != 0))
{
pine_label_style(pine_label_new((__pineBar - swingSize), pivLo, "LL"), (color)(CLEAR), (color)((color)ChartGetInteger(0, CHART_COLOR_FOREGROUND)), true, ANCHOR_UPPER, 0, "");
if(((((pine_hist(prevSwing, __pineBar, (int)(1)) == 1) ? 1 : 0) & (showHalf ? 1 : 0)) != 0))
{
pine_line_style(pine_line_new(prevHighIndex, pine_div((prevHigh + pivLo), 2), (__pineBar - swingSize), pine_div((prevHigh + pivLo), 2)), (color)(halfColor), (int)(lineStyle(halfStyle, __pineBar)), (int)(halfWidth), -1);
}
}
if(highBroken)
{
pine_line_style(pine_line_new(prevHighIndex, prevHigh, __pineBar, prevHigh), (color)(bosColor), (int)(lineStyle(bosStyle, __pineBar)), (int)(bosWidth), -1);
pine_label_style(pine_label_new(MathFloor((__pineBar - pine_div((__pineBar - prevHighIndex), 2))), prevHigh, (((((prevBreakoutDir == (-1)) ? 1 : 0) & (choch ? 1 : 0)) != 0) ? "CHoCH" : "BOS")), (color)(CLEAR), (color)(bosColor), false, -1, (int)(6), "");
prevBreakoutDir = 1;
}
if(lowBroken)
{
pine_line_style(pine_line_new(prevLowIndex, prevLow, __pineBar, prevLow), (color)(bosColor), (int)(lineStyle(bosStyle, __pineBar)), (int)(bosWidth), -1);
pine_label_style(pine_label_new(MathFloor((__pineBar - pine_div((__pineBar - prevLowIndex), 2))), prevLow, (((((prevBreakoutDir == 1) ? 1 : 0) & (choch ? 1 : 0)) != 0) ? "CHoCH" : "BOS")), (color)(CLEAR), (color)(bosColor), true, ANCHOR_UPPER, (int)(6), "");
prevBreakoutDir = (-1);
}
}
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[])
{
// Pine evaluates oldest-to-newest. MQL4 hands OnCalculate
// SERIES-indexed arrays (0 == newest) while MQL5 hands over
// oldest-first, so the direction is forced explicitly rather
// than relying on either default. `x[n]` is then index i - n
// in both dialects, and the generated logic is identical.
ArraySetAsSeries(open, false);
ArraySetAsSeries(high, false);
ArraySetAsSeries(low, false);
ArraySetAsSeries(close, false);
ArraySetAsSeries(tick_volume, false);
ArraySetAsSeries(volume, false);
ArraySetAsSeries(time, false);
ArrayResize(prevSwing, rates_total);
if(prev_calculated == 0)
{
ArrayInitialize(prevSwing, PINE_NA);
}
__pineLastBar = rates_total - 1;
const int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
static bool __pineRealVolume = false;
if(start == 0)
{
__pineRestoreInitial();
__pineSnapBar = -1;
__pineRealVolume = rates_total > 0 && volume[rates_total - 1] > 0;
}
__pineRealtime = prev_calculated > 0;
for(int __pineBar = start; __pineBar < rates_total; __pineBar++)
{
if(__pineBar == __pineSnapBar)
__pineRestoreState(); // a re-run of this bar: back to its start
else if(__pineBar == __pineLastBar)
{
__pineSaveState(); // the forming bar: remember the state it starts from
__pineSnapBar = __pineBar;
}
if(__pineRealVolume) PineBar(__pineBar, open, high, low, close, volume, time);
else PineBar(__pineBar, open, high, low, close, tick_volume, time);
}
return rates_total;
}
void OnDeinit(const int reason)
{
ObjectsDeleteAll(0, "pine_");
}Original Pine Script
© Leviathan — Mozilla Public License 2.0. Reproduced for attribution and comparison; the converted code above is a derivative work offered under the same licence.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Leviathan
// Swing point generation inspired by @BacktestRookies
//@version=5
indicator("Market Structure - By Leviathan", overlay=true, max_labels_count=500, max_lines_count=500)
// Constants
color CLEAR = color.rgb(0,0,0,100)
// Inputs
swingSize = input.int(20, 'Swing Length', tooltip='The number of left and right bars checked when searching for a swing point. Higher value = less swing points plotted and lower value = more swing points plotted.' )
bosConfType = input.string('Candle Close', 'BOS Confirmation', ['Candle Close', 'Wicks'], tooltip='Choose whether candle close/wick above previous swing point counts as a BOS.')
choch = input.bool(false, 'Show CHoCH', tooltip='Renames the first counter trend BOS to CHoCH' )
showSwing = input.bool(true, 'Show Swing Points', tooltip='Show or hide HH, LH, HL, LL')
showHalf = input.bool(false, 'Show 0.5 Retracement Level', group='0.5 Retracement Level', tooltip='Show a possible 0.5 retracement level between the swing highs and lows of an expansion move.')
halfColor = input.color(color.rgb(41, 39, 176), 'Color', group='0.5 Retracement Level')
halfStyle = input.string('Solid', 'Line Style', ['Solid', 'Dashed', 'Dotted'], group='0.5 Retracement Level')
halfWidth = input.int(1, 'Width', minval=1, group='0.5 Retracement Level')
bosColor = input.color(color.rgb(112, 114, 119), 'Color', group='BOS Settings')
bosStyle = input.string('Dashed', 'Line Style', ['Solid', 'Dashed', 'Dotted'], group='BOS Settings')
bosWidth = input.int(1, 'Width', minval=1, group='BOS Settings')
// Functions
lineStyle(x) =>
switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
// Calculations
//Finding high and low pivots
pivHi = ta.pivothigh(high, swingSize, swingSize)
pivLo = ta.pivotlow(low, swingSize, swingSize)
//Tracking the previous swing levels to determine hh lh hl ll
var float prevHigh = na
var float prevLow = na
var int prevHighIndex = na
var int prevLowIndex = na
//Tracking whether previous levels have been breached
var bool highActive = false
var bool lowActive = false
bool hh = false
bool lh = false
bool hl = false
bool ll = false
//Variable to track the previous swing type, used later on to draw 0.5 Retracement Levels (HH = 2, LH = 1, HL = -1, LL = -2)
var int prevSwing = 0
if not na(pivHi)
if pivHi >= prevHigh
hh := true
prevSwing := 2
else
lh := true
prevSwing := 1
prevHigh := pivHi
highActive := true
prevHighIndex := bar_index - swingSize
if not na(pivLo)
if pivLo >= prevLow
hl := true
prevSwing := -1
else
ll := true
prevSwing := -2
prevLow := pivLo
lowActive := true
prevLowIndex := bar_index - swingSize
//Generating the breakout signals
bool highBroken = false
bool lowBroken = false
//Tracking prev breakout
var int prevBreakoutDir = 0
float highSrc = bosConfType == 'Candle Close' ? close : high
float lowSrc = bosConfType == 'Candle Close' ? close : low
if highSrc > prevHigh and highActive
highBroken := true
highActive := false
if lowSrc < prevLow and lowActive
lowBroken := true
lowActive := false
// Visual Output
//Swing level labels
if hh and showSwing
label.new(bar_index - swingSize, pivHi, 'HH', color=CLEAR, style=label.style_label_down, textcolor=chart.fg_color)
//Detecting if it is a hh after a hl
if prevSwing[1] == -1 and showHalf
line.new(prevLowIndex, (prevLow + pivHi) / 2, bar_index - swingSize, (prevLow + pivHi) / 2, color=halfColor, style=lineStyle(halfStyle), width=halfWidth)
if lh and showSwing
label.new(bar_index - swingSize, pivHi, 'LH', color=CLEAR, style=label.style_label_down, textcolor=chart.fg_color)
if hl and showSwing
label.new(bar_index - swingSize, pivLo, 'HL', color=CLEAR, style=label.style_label_up, textcolor=chart.fg_color)
if ll and showSwing
label.new(bar_index - swingSize, pivLo, 'LL', color=CLEAR, style=label.style_label_up, textcolor=chart.fg_color)
//Detecting if it is a ll after a lh
if prevSwing[1] == 1 and showHalf
line.new(prevHighIndex, (prevHigh + pivLo) / 2, bar_index - swingSize, (prevHigh + pivLo) / 2, color=halfColor, style=lineStyle(halfStyle), width=halfWidth)
//Generating the BOS Lines
if highBroken
line.new(prevHighIndex, prevHigh, bar_index, prevHigh, color=bosColor, style=lineStyle(bosStyle), width=bosWidth)
label.new(math.floor(bar_index - (bar_index - prevHighIndex) / 2), prevHigh, prevBreakoutDir == -1 and choch ? 'CHoCH' : 'BOS', color=CLEAR, textcolor=bosColor, size=size.tiny)
prevBreakoutDir := 1
if lowBroken
line.new(prevLowIndex, prevLow, bar_index, prevLow, color=bosColor, style=lineStyle(bosStyle), width=bosWidth)
label.new(math.floor(bar_index - (bar_index - prevLowIndex) / 2), prevLow, prevBreakoutDir == 1 and choch ? 'CHoCH' : 'BOS', color=CLEAR, textcolor=bosColor, style=label.style_label_up, size=size.tiny)
prevBreakoutDir := -1Convert your own Pine Script to MQL5
Your first conversion is free, in either direction. Paste a TradingView indicator or strategy and get MQL5 or MQL4 source, with every construct the engine could not map flagged by line.
Open the converterMore: all example conversions · how Pine Script maps to MQL5 · how the engine measures