Regime Lab

  • Библиотеки
  • Shipra Gupta
    Shipra Gupta
    Я — Шипра Гупта, трейдер и разработчик количественных стратегий с сильной подготовкой в области математики, экономики и алгоритмических торговых систем. За годы работы я получила обширный опыт на рынках Forex, золота, индексов, сырьевых товаров и криптовалют, сосредоточившись на создании торговых
  • Версия: 1.0

RegimeLab – Hidden Markov Model & Market Regime Detection

Most EAs fail because they run the right logic in the wrong regime. RegimeLab tells your EA which regime it is in, using published statistics instead of another moving average.

Features

  • Hidden Markov Model – 2-state Gaussian HMM fitted by Baum-Welch: probability of the turbulent state, state means, volatilities, persistence and expected duration.
  • Hurst exponent – Rescaled-range estimate on any symbol/timeframe or on your own array.
  • Variance ratio z-test – Lo-MacKinlay heteroskedasticity-robust test of momentum vs mean reversion.
  • Efficiency ratio – Kaufman path efficiency from 0 (noise) to 1 (straight line).
  • Volatility percentile – Current Wilder ATR ranked against its own history.
  • Composite label – TREND_UP, TREND_DOWN, MEAN_REVERT, RANDOM or HIGH_VOL in one call.

Quick start

1. Buy and download the library. MetaTrader installs it to MQL5\Libraries\RegimeLab.ex5.
2. Paste the import block below at the top of your EA, indicator or script.
3. Call the functions.

void OnTick()
  {
   int r=RL_Regime(_Symbol,PERIOD_H1,500,1,0.70,1.96);
   if(r==RL_REGIME_HIGH_VOL) return;                 // stand aside
   if(r==RL_REGIME_TREND_UP || r==RL_REGIME_TREND_DOWN) RunTrend(r);
   if(r==RL_REGIME_MEAN_REVERT) RunMeanRevert();
  }

Import block (copy into your code)

#define RL_OK            0
#define RL_ERR_PARAM     1
#define RL_ERR_DATA      2
#define RL_ERR_SYMBOL    3
#define RL_ERR_FIT       4
#define RL_REGIME_UNKNOWN      0
#define RL_REGIME_TREND_UP     1
#define RL_REGIME_TREND_DOWN   2
#define RL_REGIME_MEAN_REVERT  3
#define RL_REGIME_RANDOM       4
#define RL_REGIME_HIGH_VOL     5

#import "RegimeLab.ex5"
int RL_LastError();
double RL_Hurst(const string symbol,const ENUM_TIMEFRAMES tf,const int bars,const int shift);
double RL_HurstArray(const double &series[],const bool is_price);
bool RL_VarianceRatio(const string symbol,const ENUM_TIMEFRAMES tf,const int bars,const int q, const int shift,double &vr,double &z);
double RL_EfficiencyRatio(const string symbol,const ENUM_TIMEFRAMES tf,const int period,const int shift);
double RL_VolPercentile(const string symbol,const ENUM_TIMEFRAMES tf,const int atr_period, const int lookback,const int shift);
double RL_HMMFit(const string symbol,const ENUM_TIMEFRAMES tf,const int bars,const int shift, const int max_iter);
bool RL_HMMParams(const int state,double &mean,double &stdev,double &stay_prob);
double RL_HMMExpectedDuration(const int state);
double RL_HMMLogLikelihood();
int RL_Regime(const string symbol,const ENUM_TIMEFRAMES tf,const int bars,const int shift, const double hivol_prob,const double z_crit);
string RL_RegimeName(const int regime);
#import

Notes

  • Uses completed bars (shift ≥ 1): no repaint, no look-ahead.
  • 64 to 20,000 bars per call; bounded for optimisation.
  • Any symbol and timeframe, so multi-symbol and multi-timeframe filters fit in one EA.

Technical

  • Pure MQL5. No DLL, no WebRequest, no file I/O.
  • Every exported function validates its inputs. RL_LastError() returns the reason for any failed call.
  • Works in the Strategy Tester and live, on any broker, symbol and account currency.

Past performance shown in screenshots is from historical data and does not guarantee future results.

Другие продукты этого автора
AMD Po3 for MetaTrader 5 Accumulation, manipulation, distribution: mapped for you. AMD Po3 is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator maps the reaction zones that matter right now: the nearest areas above and
KN Smart TP SL Signals — EMA 交叉 + 智能 TP/SL KN Smart TP SL Signals 是一款简洁的 MetaTrader 5 EMA 交叉指标,可将每一次经过确认的交叉转换为完整的可视化交易方案: Entry → Stop Loss → TP1 → TP2 → TP3 无需手动计算交易水平。 核心逻辑 快速 EMA 向上穿越慢速 EMA → 买入 快速 EMA 向下穿越慢速 EMA → 卖出 信号仅在 已收盘K线 上确认,从而避免当前正在形成的K线产生信号。 核心功能 EMA 交叉信号 可配置快速和慢速 EMA 基于 ATR 的止损 使用可配置 R 倍数计算 TP1 / TP2 / TP3 默认 1.5 ATR 止损 / 1R / 2R / 3R 止盈 自动绘制 Entry、SL 和 TP 水平线 盈利与亏损可视化区域 实时交易跟踪 TP/SL 状态更新 历史信号持续显示,便于复盘 可配置最大历史信号数量 可配置线条延伸长度 MT5 推送通知 ,支持信号、TP 和 SL 支持
IFVG Sniper Entry Engine — Описание для Маркетплейса MQL5 IFVG Sniper Entry Engine — это высокоточный индикатор для MT5, построенный вокруг одного из самых специфических и высоковероятных паттернов входа в Smart Money Concepts — инверсного имбаланса (Inverse Fair Value Gap, IFVG). Он незаметно отслеживает каждый сформированный на графике «сырой» Fair Value Gap, проверяет его на предмет инверсии (митигации), и в тот момент, когда квалифицирующий паттерн IFVG подтверждается, генерирует сигнал на П
Coppock Curve MultiFilter for MetaTrader 5 The classic Coppock curve with modern filters. Coppock Curve MultiFilter is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator plots its oscillator in a separate subwindow with
FREE
Tension Flow Trend — Динамическая лента HMA с историческим бэктестом RR Tension Flow Trend — это продвинутый трендовый индикатор для MetaTrader 5, который объединяет в себе трендовую ленту на основе скользящей средней Халла (HMA), анализ импульса Z-Score и встроенный визуальный модуль бэктестинга соотношения риска и прибыли (Risk:Reward) в одном графическом оверлее. Разработанный для выявления высоковероятных возможностей продолжения тренда, этот индикатор отфильтровывает рыночный шум, требуя ка
FREE
Adaptive RSI Supertrend for MetaTrader 5 Trend and RSI momentum in one view. Adaptive RSI Supertrend is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator draws one trend line that changes colour with the trend: bull co
FREE
Trend Target Ribbon [BOSWaves] Trend Target Ribbon [BOSWaves] — это продвинутый многофункциональный индикатор следования за трендом и управления рисками для MetaTrader 5 (MQL5). Он объединяет сглаженную основу Arnaud Legoux Moving Average (ALMA) с фильтрами подтверждения на основе волатильности и наклона, позволяя определять рыночные тренды, отображать динамические цветные ленты и автоматически строить многоуровневые торговые проекции Risk-to-Reward ($R$). Основные возможности 1. Трендовая лента
FREE
Structure-Anchored VWAP [WAT] Structure-Anchored VWAP [WAT] — это индикатор VWAP для MetaTrader 5, учитывающий рыночную структуру. Он привязывает VWAP к значимым свингам и структурным точкам, а не только к фиксированным сбросам в начале торговой сессии. Он объединяет рыночную структуру + Anchored VWAP + полосы отклонения + сигналы ретеста + управление сделкой на основе ATR в единую визуальную систему. Основные возможности 3 режима привязки — Swing, Structure и Fast Определение структуры — HH
FREE
Liquidity Intelligence System — Описание для Маркетплейса MQL5 Liquidity Intelligence System — это индикатор институционального уровня для MT5, который отображает пулы ликвидности Smart Money, обнаруживает сетапы снятия ликвидности с разворотом (sweep-and-reverse) и генерирует высокоточные торговые сигналы с помощью 16 независимо тестируемых сигнальных моделей — и все это внутри одного лаконичного индикатора. Как это работает Движок непрерывно выстраивает живую карту ликвидности, обнаруживая зон
Precision Sniper Trader Precision Sniper Trader — это профессиональный индикатор следования за трендом и подтверждения импульса, разработанный для трейдеров, которым важно чистое исполнение на графике, высокая вероятность входа и структурированное управление сделками на рынках Forex, золота, индексов и криптовалют. Созданный на основе подхода «снайперской точности», индикатор сочетает в себе трендовый анализ EMA, подтверждение импульса, динамические цели на основе ATR и интеллектуальную фильтрац
FREE
TrendIQ Pro for MetaTrader 5 Adaptive volatility trend with a trend cloud. TrendIQ Pro is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator draws one trend line that changes colour with the trend: bull colour for long
ИНДИКАТОР SQUEEZE MOMENTUM BREAKOUT ДЛЯ MT5 Профессиональная торговая система сжатия волатильности и пробоя импульса для MetaTrader 5 Squeeze Momentum Breakout — это профессиональный индикатор пробоя для MT5, разработанный для обнаружения взрывных рыночных движений после периодов консолидации с низкой волатильностью. Созданный для скальперов, внутридневных и импульсных трейдеров, этот индикатор объединяет сжатие волатильности, подтверждение импульса, фильтрацию по объему и структурированное упра
FREE
ИНДИКАТОР VOLUME BREAKOUT PRO ДЛЯ MT5 Профессиональная торговая система расширения объема и пробоя для MetaTrader 5 Volume Breakout Pro — это индикатор пробоя институционального уровня, разработанный специально для платформы MetaTrader 5. Созданный для скальперов, внутридневных трейдеров и трейдеров на пробой импульса, этот инструмент фокусируется на выявлении взрывных ценовых движений, вызванных аномальным расширением объема и дисбалансом ликвидности. Индикатор объединяет в себе: Логику среднев
FREE
Meridian Flow — Индикатор Smart Money Structure для MT5 Meridian Flow — это индикатор для MetaTrader 5, созданный для трейдеров, использующих Smart Money Concepts (SMC) и методологию ICT price action . Он автоматически определяет события BOS (Break of Structure) и CHoCH (Change of Character) на любом инструменте и таймфрейме, а затем строит полную карту риска — Entry, Stop Loss, TP1, TP2 и TP3 — для каждого сигнала, включая исторические. Сигналы появляются только на подтверждённых закрытых свеч
Adaptive Trend System for MetaTrader 5 A trend line that adapts to volatility. Adaptive Trend System is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator draws one trend line that changes colour with the trend: bull co
Market Path Forecast for MetaTrader 5 Projected price paths from swing statistics. Market Path Forecast is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator detects confirmed swing highs and lows and tracks how price b
FREE
RSI Signal Entries for MetaTrader 5 RSI extremes plus candle confirmation. RSI Signal Entries is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator plots its oscillator in a separate subwindow with clear extreme zones.
FREE
Trident Swing Projector for MetaTrader 5 Quarter-swing projections from ABC structures. Trident Swing Projector is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator detects confirmed swing highs and lows and tracks how
Z-Score Range Boxes Breakout for MetaTrader 5 Statistical extremes boxed, breakouts flagged. Z-Score Range Boxes Breakout is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator tracks the range or channel price is tradin
Precision Sniper Pro for MetaTrader 5 Four pillars: EMA, RSI, MACD and ADX. Precision Sniper Pro is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator watches for its signal condition and waits for the candle to close b
FREE
Stealth Trail Supertrend for MetaTrader 5 A supertrend that adapts its own multiplier. Stealth Trail Supertrend is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator draws one trend line that changes colour with the tre
Fibonacci Path Profile for MetaTrader 5 How price moved after similar retracements. Fibonacci Path Profile is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator detects confirmed swing highs and lows and tracks how pric
Strong Fade Signals for MetaTrader 5 Fade the overextended move, with a score. Strong Fade Signals is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator watches for its signal condition and waits for the candle to close
FREE
Fan Principle Signals for MetaTrader 5 The classic fan principle, as clear signals. Fan Principle Signals is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator detects confirmed swing highs and lows and tracks how price
McGinley Dynamic Fusion for MetaTrader 5 McGinley Dynamic crossovers with ATR levels. McGinley Dynamic Fusion is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator draws one trend line that changes colour with the trend
Liquidity Entry Signals for MetaTrader 5 Entries where liquidity gets taken. Liquidity Entry Signals is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator maps the reaction zones that matter right now: the nearest areas
Cardwell Range Pro for MetaTrader 5 RSI ranges that change with the market regime. Cardwell Range Pro is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator plots its oscillator in a separate subwindow with clear extreme
Adaptive RSI Supertrend for MetaTrader 5 Trend and RSI momentum in one view. Adaptive RSI Supertrend is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator draws one trend line that changes colour with the trend: bull co
Market Structure Target Tracker for MetaTrader 5 Swings, BOS, CHoCH and ATR targets. Market Structure Target Tracker is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator detects confirmed swing highs and lows and track
Smart TrendFlow Pro for MetaTrader 5 Channel breaks with a volatility heatmap. Smart TrendFlow Pro is a MetaTrader 5 indicator built for traders who want clear, rule-based chart reading without clutter. It focuses on one job and does it visibly on your chart, so you can make decisions faster and with more confidence. It works on gold (XAUUSD), forex, indices and crypto, on any timeframe from M5 to D1. How it works The indicator tracks the range or channel price is trading in and highlights per
Фильтр:
Нет отзывов
Ответ на отзыв