CodeRe: Step Indicators for MT4

751
New Step NEMA indicator with Colored Bars

This is a new version of step ma of nema, seems to hug the price better, but remains to be seen if it is an improvement of the last version.
These users thanked the author mrtools for the post (total 14):
Zevia, RodrigoRT7, Jimmy, Karvamaha, Akela, 太虚一毫, Jedidiah, thomdel, boytoy, nbibu, 88FX88, vvFish, Abdi, mate


Re: Step Indicators for MT4

752
mrtools wrote: Tue Mar 04, 2025 8:05 am This is a new version of step ma of nema, seems to hug the price better, but remains to be seen if it is an improvement of the last version.
Now that looks very good. Indeed an even better version than the old one just trying it now 👍
These users thanked the author Jimmy for the post (total 2):
mrtools, boytoy
Myfxbook live trading results 📊

List of our most powerful reversal indicators + Guide to the "All Averages" Filters (ADXvma, Laguerre etc.)
Fibonacci numbers for indicator settings + How to draw Fibonacci Extensions + How to draw Support & Resistance

CodeRe: Step Indicators for MT4

755
boytoy wrote: Tue Mar 04, 2025 7:53 pm Nothing short of epic but please! Could we get colored candlesticks instead of the old bars? 😇
New Step NEMA indicator with Colored Candlesticks

Thanks, changed to colored candlesticks instead of bars.
As per the previous post I wrote, this is a new version of step ma of nema, seems to hug the price better, but remains to be seen if it is an improvement of the last version.

What is the NEMA?

NEMA (n-EMA) can calculate up to 49 EMA's and it uses up to 50 calculating buffers internally.

It calculates EMA, DEMA, TEMA and so on depending on NemaDepth parameter. In simple terms, using "3" in the NemaDepth will give you Triple Exponential Moving Averages. Using "40" in the NemaDepth will give you Quadragintuple Exponential Moving Averages.

Nema can calculate all the known variations (offspring) of EMA : EMA, DEMA, TEMA, DecEMA and so on, up to "levels" or "depth" 50 (Quinquagintuple Exponential Moving Average).

Some known depths:
  • 1 (period) equals EMA: Single Exponential Moving Average
  • 2 (period) equals DEMA: A Double Exponential Moving Average
  • 3 period) equals TEMA: Triple Exponential Moving Average
  • 4 period) equals TEMA: Quadruple (Quad) Exponential Moving Average
  • 5 period) equals TEMA: Quintuple Exponential Moving Average
  • 10 (period) equals DecEMA: Decuple Exponential Moving Average
With 50 (period) being the maximal depth calculated by this indicator.


Re: Step Indicators for MT4

757
mrtools wrote: Wed Mar 05, 2025 1:07 am Yes, could be an onChart Wpr not sure though!
Hi Mr Tools and @ionone how are you?

This is the indicator code that Ionone mentioned above.

Code: Select all

//+------------------------------------------------------------------+
//|                                          Atr_Percent-Shargyn.mq4 |
//|                                  Copyright 2025, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property indicator_separate_window
//--- Используем два буфера:
// Первый буфер - основная линия, рассчитываемая по динамическому ATR%
// Второй буфер - сдвинутая на один бар версия основной линии
#property indicator_buffers 2
//--- Настройки первой линии (динамический ATR%)
#property indicator_color1 clrBlue
#property indicator_width1 2
#property indicator_label1 "Dynamic_ATR_Percent"
//--- Настройки второй линии (смещённая на 1 бар)
#property indicator_color2 clrRed
#property indicator_width2 2
#property indicator_label2 "Shifted"
//--- Настройка уровня линии 0
#property indicator_level1 0
#property indicator_levelcolor clrBlue
#property indicator_levelstyle 2 
//--- Входные параметры для динамического ATR
input int    BasePeriodAtr      = 3;     // Базовый период для ATR
input int    VolatilityLookback = 14;    // Период для расчёта среднего диапазона (High-Low)
input double ThresholdHigh      = 0.002; // Порог высокой волатильности (единицы цены)
input double ThresholdLow       = 0.001; // Порог низкой волатильности (единицы цены)
input int    ExtraBars          = 2;     // Дополнительное увеличение периода при высокой волатильности
input int    ReduceBars         = 1;     // Снижение периода при низкой волатильности
//--- Объявляем буферы для расчёта линий
double DynamicATRBuffer[]; // Буфер для основной линии (ATR%)
double ShiftedBuffer[];    // Буфер для второй линии (сдвинутая на 1 бар)
//--- Статическая переменная для скользящей суммы диапазонов (High - Low)
// Она используется для вычисления среднего диапазона за VolatilityLookback баров
static double currentSumRange = 0.0;
//+------------------------------------------------------------------+
//| Функция инициализации индикатора                                 |
//+------------------------------------------------------------------+
int OnInit()
  {
   // Выделяем два буфера для индикатора
   IndicatorBuffers(2);
   // Настраиваем первую линию: рисуем линию и связываем с буфером DynamicATRBuffer
   SetIndexStyle(0, DRAW_LINE);
   SetIndexBuffer(0, DynamicATRBuffer);
   // Настраиваем вторую линию: рисуем линию и связываем с буфером ShiftedBuffer
   SetIndexStyle(1, DRAW_LINE);
   SetIndexBuffer(1, ShiftedBuffer);
   // Возвращаем статус успешной инициализации
   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[])
  {
   // Проверяем, что имеется достаточно баров для расчёта
   if(rates_total < VolatilityLookback + 1)
      return(0);
      
   // Определяем граничное значение, чтобы окно суммирования (баров для VolatilityLookback)
   // полностью укладывалось в исторических данных
   int limit = rates_total - VolatilityLookback - 1;
   
   // Пересчитываем скользящую сумму для первого обрабатываемого бара
   // Суммируем разности (high - low) для баров с индексами от 1 до VolatilityLookback
   currentSumRange = 0.0;
   for(int j = 1; j <= VolatilityLookback && j < rates_total; j++)
      currentSumRange += ( high[j] - low[j] );
   
   // Основной цикл расчёта по всем барам от 0 до limit
   for(int i = 0; i < limit; i++)
   {
      // 1. Вычисляем средний диапазон за VolatilityLookback баров,
      //    начиная с бара с индексом i+1
      double avgRange = currentSumRange / VolatilityLookback;
      
      // 2. Определяем динамический период ATR:
      //    Начинаем с базового периода BasePeriodAtr и корректируем его
      //    в зависимости от того, насколько avgRange выше порога ThresholdHigh
      //    или ниже порога ThresholdLow.
      int dynamicPeriod = BasePeriodAtr;
      if(avgRange > ThresholdHigh)
         dynamicPeriod = BasePeriodAtr + ExtraBars;
      else if(avgRange < ThresholdLow)
         dynamicPeriod = BasePeriodAtr - ReduceBars;
      if(dynamicPeriod < 1)
         dynamicPeriod = 1;
      
      // 3. Вычисляем ATR с динамическим периодом для текущего бара i
      //    Функция iATR возвращает значение ATR для заданного периода и бара
      double atrValue = iATR(_Symbol, PERIOD_CURRENT, dynamicPeriod, i);
      
      // 4. Рассчитываем процентное отклонение ATR от среднего диапазона:
      //    ((atrValue / avgRange) - 1) * 100
      double percentDeviation = 0.0;
      if(avgRange != 0)
         percentDeviation = ((atrValue / avgRange) - 1) * 100;
      
      // Сохраняем вычисленное значение в буфер основной линии
      DynamicATRBuffer[i] = percentDeviation;
      
      // 5. Формируем вторую линию как значение предыдущего бара основной линии.
      //    Если i > 0, тогда берем значение из DynamicATRBuffer[i-1], иначе – текущее значение.
      if(i > 0)
         ShiftedBuffer[i] = DynamicATRBuffer[i-1];
      else
         ShiftedBuffer[i] = DynamicATRBuffer[i];
      
      // 6. Обновляем скользящую сумму для следующего бара:
      //    - Вычитаем диапазон бара с индексом i+1
      //    - Прибавляем диапазон бара с индексом i+VolatilityLookback+1 (если он доступен)
      if(i < limit - 1)
      {
         int removeIndex = i + 1;
         int addIndex = i + VolatilityLookback + 1;
         if(addIndex < rates_total)
         {
            currentSumRange = currentSumRange - (high[removeIndex] - low[removeIndex])
                                              + (high[addIndex] - low[addIndex]);
         }
      }
   }   
   // Возвращаем общее количество баров, обработанных индикатором
"This indicator calculates dynamic ATR% - the percentage deviation of the moving ATR value (with a dynamic period depending on volatility) from the average range (High–Low) for a given period. The first line shows the resulting ATR% value, and the second line is the same value, shifted one bar back. Thus, the indicator allows you to assess market volatility by taking into account the adaptive period and visually display a delayed signal"

credits to Sharg.yn
These users thanked the author RodrigoRT7 for the post:
mrtools

Re: Step Indicators for MT4

759
boytoy wrote: Wed Mar 05, 2025 6:56 pm Candlesticks and lines arent working when you turn off Auto Candlestick Width option can we get a fix please... super eager to use this over the old Step nema
Thanks again, something weird was going on when turning off auto width and using filtered price, so changed a lot of stuff and it seems to be working now when auto width off, tried most of the other options and seems good now, hopefully! Posted the fixed version in the last post and sorry for the hassle! TBH never figured out exactly what was causing the error was something had never seen before.
These users thanked the author mrtools for the post:
vvFish