PeriodAdaptiveMA

Download script
Author: Scriptong
PeriodAdaptiveMA

This script is designed as a specialized financial tool for the MetaTrader platform that calculates and displays a Daily Adaptive Moving Average. Unlike standard moving averages that might blend data from several days together, this tool is specifically engineered to isolate and analyze price action within a single trading day.

Core Logic Overview

The primary goal of this script is to provide a moving average that "resets" every time a new day begins. This allows traders to see the trend progression for the current day without the influence of previous days' data.

1. Environment & Compatibility Checks

When you first load the tool, it performs an automatic safety check. It verifies that the chart you are viewing is set to a timeframe smaller than one day (for example, 5-minute or 1-hour charts). If the chart is already set to a daily view or higher, the script will notify you that it cannot function correctly because its purpose is to track internal movements within a single day.

2. Intelligent Data Separation

The script contains logic to recognize the start of a new calendar day. It continuously monitors the time on your chart:

  • Reset Mechanism: Every time the calendar flips to a new day, the script clears its internal memory and starts a fresh calculation.
  • Isolation: This ensures that the moving average line you see is purely a reflection of today's price movements, preventing "leakage" from yesterday's trends.

3. Customizable Price Sources

The tool offers high flexibility regarding which part of the market price it should follow. You can choose how it calculates the "average" by selecting different types of price data:

  • Standard: It can track closing prices, opening prices, highs, or lows.
  • Calculated: It can also use complex averages such as the Median (midpoint of high/low), Typical Price (average of high, low, and close), or Weighted Price.

4. Dynamic Moving Average Calculation

For every price candle on your chart, the script performs a real-time calculation:

  1. It gathers the price data points for the current day only.
  2. It applies the specific Moving Average method you have chosen (e.g., Simple, Exponential, etc.).
  3. It plots a smooth line on your chart that represents the "momentum" of the current day's trading session.

Summary for the User

Essentially, this tool acts as a "Daily Trend Filter." It allows you to see how the price is behaving specifically today by creating a moving average that forgets everything that happened yesterday, providing a cleaner look at intraday momentum and volatility.

Indicators Used
Moving average indicator
Miscellaneous
Implements a curve of type %1
11 Views
0 Downloads
0 Favorites
PeriodAdaptiveMA
//+------------------------------------------------------------------+
//|                                                      MAOnDay.mq4 |
//|                                                        Scriptong |
//|                                                scriptong@mail.ru |
//+------------------------------------------------------------------+
#property copyright "Scriptong"
#property link      "scriptong@mail.ru"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Red
//---- input parameters
extern int       MethodMA=0;
extern int       PriceMA=0;
extern int       LargeTF = 1440;

bool Activate;
datetime NowDay, LastDay;
double Buffer[];
int Count;

//---- buffers
double MA[];
//+-------------------------------------------------------------------------------------+
//| Custom indicator initialization function                                            |
//+-------------------------------------------------------------------------------------+
int init()
  {
   Activate = False;
// - 1 - == Ïðîâåðêà ïðàâèëüíîñòè âûáðàííîãî ïîëüçîâàòåëåì òàéìôðåéìà ===================
   if (Period() >= LargeTF)
     {
      Comment("Èíäèêàòîð DayAdaptiveMA ðàáîòàåò íà òàéìôðåéìàõ, ìåíüøèõ, ÷åì D1.");
      return(0);
     }
// - 1 - == Îêîí÷àíèå áëîêà =============================================================
   
// - 2 - == Èíèöèàëèçàöèÿ èíäèêàòîðíîãî áóôåðà ==========================================
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0, MA);
   SetIndexEmptyValue(0, 0);
// - 2 - == Îêîí÷àíèå áëîêà =============================================================
   
// - 3 - == Èíèöèàëèçàöèÿ áóôåðà äëÿ ïîäñ÷åòà ñðåäíåãî ==================================
   ArrayResize(Buffer, MathCeil(LargeTF/Period())+1);
   ArrayInitialize(Buffer, 0);
// - 3 - == Îêîí÷àíèå áëîêà =============================================================
   
   Activate = True;
//----
   return(0);
  }
//+-------------------------------------------------------------------------------------+
//| Custom indicator deinitialization function                                          |
//+-------------------------------------------------------------------------------------+
int deinit()
  {
//----
   Comment("");
//----
   return(0);
  }
  
//+-------------------------------------------------------------------------------------+
//| Custom indicator iteration function                                                 |
//+-------------------------------------------------------------------------------------+
int start()
  {
// - 1 - == Ïðàâèëüíî ëè èíèöèàëèçèðîâàí èíäèêàòîð? =====================================
   if (!Activate) return(0);
// - 1 - == Îêîí÷àíèå áëîêà =============================================================
  
   int limit, counted_bars=IndicatorCounted();

// - 2 - == Ðàñ÷åò íîìåðà áàðà òåêóùåãî ÒÔ, ñîîòâåòñòâóþùåãî íà÷àëó äíÿ =================
   if(counted_bars>0) counted_bars--;
   limit = iBarShift(Symbol(), 0, iTime(Symbol(), LargeTF, 
                     iBarShift(Symbol(), LargeTF, Time[Bars-counted_bars])));
// - 2 - == Îêîí÷àíèå áëîêà =============================================================

   LastDay = 1;
   for (int i = limit; i >= 0; i--)
     {
// - 3 - == Åñëè íà÷àëñÿ íîâûé äåíü, ôîðìèðóåì âñå äàííûå çàíîâî ========================
      NowDay = iTime(Symbol(), LargeTF, iBarShift(Symbol(), LargeTF, Time[i]));
      if (LastDay != NowDay)
        {
         ArrayInitialize(Buffer, 0);
         Count = 0;
         LastDay = NowDay;
        }
// - 3 - == Îêîí÷àíèå áëîêà =============================================================
      
// - 4 - == Îïðåäåëåíèå öåíû, ïî êîòîðîé ïðîèçâîäèòñÿ ðàñ÷åò ÌÀ =========================
      switch (PriceMA)
        {  
         case 0: /*Close*/    Buffer[Count] = Close[i]; break;
         case 1: /*Open*/     Buffer[Count] = Open[i]; break;
         case 2: /*High*/     Buffer[Count] = High[i]; break;
         case 3: /*Low*/      Buffer[Count] = Low[i]; break;
         case 4: /*Median*/   Buffer[Count] = (High[i]+Low[i])/2; break;
         case 5: /*Typical*/  Buffer[Count] = (High[i]+Low[i]+Close[i])/3; break;
         case 6: /*Weighted*/ Buffer[Count] = (High[i]+Low[i]+2*Close[i])/4; break;  
        }
// - 4 - == Îêîí÷àíèå áëîêà =============================================================
      
// - 5 - == Ðàñ÷åò ñðåäíåé ñêîëüçÿùåé ïî äàííûì ñåãîäíÿøíåãî äíÿ ========================
      MA[i] = iMAOnArray(Buffer, Count+1, Count+1, 0, MethodMA, 0);
      Count++;      
// - 5 - == Îêîí÷àíèå áëîêà =============================================================
     } 

   return(0);
  }

Comments